--- url: /zh/docs/common/faq/core.md --- # Core 常见问题与解决方法 ## **问题1:误删除单机pg\_xlog处理恢复** ### 问题描述 一套单机数据库的pg\_xog磁盘空间占用接近100%,打算清除80%的xlog时候,误操作导致整个pg\_xlog目录全部被删除,数据库宕机。 (xlog空间用满,一般由归档不成功或者有复制槽未清理,导致xlog不回收) ### 解决方案 先确定暂时没法从系统层面恢复误删除文件,从数据库层面进行恢复。 #### pg\_resetxlog `pg_resetxlog /ogdata/data/dn1 -f`\ [pg\_resetxlog](https://docs.opengauss.org/zh/docs/latest/tool_and_commandreference/pg_resetxlog.html) 由于xlog全部删除,使用pg\_resetxlog强制重新设置xlog文件,然后拉起数据库,数据库可以正常启动起来。(如果报postmaster.pid错误,手动删除数据目录下该文件再启动。) > \[!WARNING]注意 > > 1. 假如近一段时间没有写业务,即可以确保脏页的数据全部落盘,后面重启后也不需要从xlog回放数据,这么做可以保证集群恢复后正常。 > 2. 假如正好有写的业务落盘xlog但是还未刷脏,那么就会导致部分数据丢失,出现不一致的问题。(对于这种极端场景,能恢复大部分数据。) #### 集群恢复 集群启动后,由于应用侧一直在链接访问,运行一会后出现数据库coredump。 ![image](figures/fig_1.png) 可以看到日志里面有PANIC级别日志: ![image](figures/fig_2.png) 该错误是数据页上的LSN,比正常运行的要大,在有业务访问表的时候直接校验不过core掉。数据页上的没法回滚回去。 STATEMENT打印了访问的表名称,该表是受到影响的,没法正常恢复。 避免频繁数据库core掉,针对出问题的表,重命名下,避免访问表就引发数据库故障。 `alter table t1 rename to t1_bak;` 因为有些表保留历史数据,可基于旧表的定义建立新表。 ``` ## 查询表定义,根据表定义建新表 select * from pg_get_tabledef('app_monitor_bak'); 新建表遇到有约束(主键、外键、唯一约束)冲突的,删除约束 alter table app_monitor_bak drop constraint app_monitor_pkey; ``` 对于新建的表,业务用户权限不够的,可以给业务用户赋予表的所有权限。 #### enable\_roach\_standby\_cluster 以上操作已恢复了集群,下一步考虑如何恢复数据。 由于受到影响的表已经不可查,查询就coredump,考虑在查询时候如何可以关闭校验。 开启 `enable_roach_standby_cluster=on`,重启数据库进程后,再次查询异常的表,不会产生coredump,而且可以查出来数据。 ``` ### 然后将受损坏的表数据导入到新建表里面 insert into table_new select * from table_bak; ``` Select该页面大概率是因为触发了heap\_prune,进而导致core掉,从代码上看,开启enable\_roach\_standby\_cluster后,可以跳过prune。 该参数未在社区有说明,不建议开启,除非极端情况下;开启后也建议只对表做查询操作,不能做任何更新。最保险的还是开启后导出数据,重建集群导入数据。 heap\_page\_prune\_opt 函数 跳过校验: ![image](figures/fig_3.png) upgrade\_mode设置为1,应该也有相同的效果跳过校验。 > \[!WARNING]注意 > > pgxlog目录不要手动删除,清理不掉是有其他原因导致,修复后让数据库自行清理。 ## **问题2:主机core掉定位过程** ### 问题描述 定位命令 `addr2line -e bin/gaussdb fbcf8d -C -f` 主节点进程突然宕机,未生成core文件。 ### 解决方案 查看ffic日志记录: ![image](figures/fig_2_1.png) Addr2line可以定位到函数所在行,获取到具体的调用关系: ![image](figures/fig_2_2.png) ![image](figures/fig_2_3.png) ![image](figures/fig_2_4.png) 问题出在这一行: ![image](figures/fig_2_5.png) atal signal info: `si_signo = 7 (SIGBUS), si_code = 4,si_addr = 0x14b5afefa000` 这个错误信息表示程序在访问内存时发生了总线错误(SIGBUS)。 * si\_signo 是信号编号,这里表示接收到的信号是 SIGBUS,总线错误信号。 * si\_code 是信号代码,表示具体的错误类型。在这种情况下,`si_code = 4` 通常表示试图访问未对齐的内存地址或者访问硬件上不存在的物理内存地址。 * si\_addr 是导致错误的内存地址,这里表示在访问地址 0x14b5afefa000 时发生了总线错误。 * RAX = 0x000014b5afefa000 dmesg -T 查看当时有硬件异常,正好对应于core堆栈的地址:目前认为是内存异常导致。 ![image](figures/fig_2_6.png) ![image](figures/fig_2_7.png) ![image](figures/fig_2_8.png) ![image](figures/fig_2_9.png) ## **问题3:某客户业务版本定时任务开启后数据库异常分析** ### 问题描述 501版本B库下创建定时任务导致数据库异常退出,重新拉起库,数据库进程很快退出。 `gsql (openGauss 5.0.1 build 98ae973e) compiled at 2024-06-27 14:56:02 commit 0 last mr` ![image](figures/fig_3_1.png) ![image](figures/fig_3_2.png) 相关堆栈如下: ![image](figures/fig_3_3.png) 相关日志如下: ![image](figures/fig_3_4.png) ### 根本原因及分析 根本原因及分析见[pr](https://gitee.com/opengauss/openGauss-server/pulls/4861) ### 解决方案 目前采用job\_queue\_processes=0,不开启定时任务来进行规避: * 解决方案一:如需开启定时任务,需要升级相关业务库; * 解决方案二:不升级库的情况下,将定时任务写成脚本的形式来进行规避。 社区openGauss 5.0.2版本无问题: ![image](figures/fig_3_5.png) 对应社区openGauss 5.0.3版本无问题: ![image](figures/fig_3_6.png) 对应社区openGauss 6.0.1版本无问题: ![image](figures/fig_3_7.png) ## **问题4:某客户alter table .. after core问题故障报告** ### 问题描述 观察到数据库集群主从之间频繁切换,并且产生了core文件。在集群状态异常前,数据库进行了表结构变更操作,其中变更涉及了alter table ... after语法。 ![image](figures/fig_5_1.png) 数据库版本:openGauss 5.0.0 ### 问题分析定位过程 1. 根据现象描述,高度疑似某个5.0.0版本已知的bug,该bug由alter table ... after|first语法引入,在5.0.2版本中修改解决。该bug具体表现为使用上述语法后,未更新统计信息前,查询表会偶现core问题。 2. 已知上述bug的产生原理是alter table after后,pg\_statistic(记录统计信息的系统表)未更新但是pg\_attrribute(记录库内表字段属性的系统表)已更新,两者产生差异从而导致的core,因此规避方法为analyze table,更新统计信息即可。用此方法,将所有涉及到alter table ..after操作的表,全部进行了analyze操作。进行该操作后,问题未复现,基本证明是该bug引起。 3. 由于产生了core堆栈,我们最终通过core堆栈再双重确认下问题是否由该bug引起。 这里我们在core堆栈中主要确认两个问题: ``` 1. core堆栈里执行的sql是否涉及相关表执行过 alter table ... after操作。 ``` ![image](figures/fig_5_2.png) ``` 对比Sql中涉及的表以及当晚做过analyze的表,发现sql中的部分表在当晚进行过alter table .. after操作。 ``` ![image](figures/fig_5_3.png) ``` 2. 打印core堆栈中涉及查询的字段在统计信息表中的属性: ``` ![image](figures/fig_5_4.png) ``` 该操作符2060在pg_operator中对应的是timestamp类型的操作符。 ``` ![image](figures/fig_5_5.png) ``` 而实际查询是text。因此可以确认是由于统计信息异常导致的问题。 ``` 4\. 最终得到如下结论: 本问题为已知问题:[issue=I8SZS3](https://e.gitee.com/opengaussorg/dashboard?issue=I8SZS3),对应issue截图如下: ![image](figures/fig_5_6.png) 修改pr如下:[pr](https://gitee.com/opengauss/openGauss-server/pulls/4694) 问题修改的版本为openGauss 5.0.2 ### 问题根因 使用`alter table ... add/modify/change ... first/after`语法进行指定位置增加/更新列时,会使目标表在pg\_attribute中的列序号重新排列,但代码中未更新目标表在pg\_statistic中的列序号,导致pg\_attribute中的列序号与pg\_statistic对应的列序号不一致。 在查询优化过程中,会按照pg\_attribute中的列序号到pg\_statistic获取对应列的统计信息元组,此时会获取到错误的统计信息元组,在后续的处理中会按照pg\_attribute中的列数据类型进行数据解析、内存申请/释放等操作,从而引起宕机。(例如使用text类型的方法解析日期数据类型即会宕机) ### 规避方案 问题存在版本:openGauss 5.0.0,openGauss 5.0.1: 1. 尽量避免使用first | after语法进行表结构的变更,不使用改语法时不会出现上述问题; 2. 如业务侧一定要使用,应在使用上述语法后,立即对涉及的该ddl的表执行analyze table的操作。 > \[!WARNING]注意 > 该方法存在一定风险,因为analyze操作是不锁表的,在没有执行完成时,可能会执行查询,同样存在宕机风险。 ## **问题5:某客户在线数据库core问题分析** ### 问题描述 * 2026.04.14:有2套集群从mysql迁移到openGauss 5.0.1版本,2026.04.14发生主机切换的告警。 * 2026.04.14:2套集群先从mysql全量迁移到openGauss,迁移过程无问题,而后开启增量迁移。 * 2026.04.15 08:54:集群1发生主备切换操作。 * 2026.04.15 16:54:集群2发生主备切换的操作。 经查询系统相关信息,均是源主机产生coredump导致宕机,由CM选择备机升主。两者均产生core文件且堆栈一致。 ### 定位过程 1. 解core文件,core在了datum2autoinc函数(属于seq自增序列) ![image](figures/fig_6_1.png) `cons_autoinc->datum2autoinc_func`为空,会走到最有一个分支,该分支实际执行地址没有值。 本地调试正常的操作,应该走到 `cons_autoinc->datum2autoinc_func != NULL` 的分支里面。怀疑可能是钩子函数的问题。 ![image](figures/fig_6_2.png) 2. 打印coredump时候的sql,为 insert 语句。手动将语句在数据库实际执行,执行结果正常,未出现core问题。(说明不是数据类型等引起的,否则会是必现问题) ![image](figures/fig_6_3.png) 3. 查看序列信息,也都在范围内,未越界。 ![image](figures/fig_6_4.png) 4. 第二套集群同样的core堆栈,也是插入seq导致core掉。 ### 问题原因 钩子函数为空,在钩子函数的赋值、设置以及获取方面可能有问题。 问题的分析和修复过程见PR: [PR](https://gitee.com/opengauss/openGauss-server/pulls/4849) 1. 在开启globalsyscache后,系统表信息会记录到globalcache中。 2. Autovacuum不加载dolphin插件。当autovacuum woker清理该表时候,构建时候会将钩子函数cons\_autoinc->datum2autoinc\_func置为NULL,但是由于xmin未推进等原因不会真正清理。但是globalsyscache中的钩子函数已经被置为NULL。 3. 客户端的会话线程在访问表时候,会构建以及初始化钩子函数,但是从localcache找,找不到然后会去globalcache找,会在globalcache中找到现成的需要的表数据结构信息。但是该结构中,由于autovacuum清理到了钩子函数,导致客户端会话也无法找到该函数,走到非预期分支产生coredump。 该问题在5.0.2以及6.0.0RC1以上版本修复。 ### 规避措施 * **概况:** 该问题是由于开启globalcache后,客户端backend线程和autovacuum都会查找以及设置globalcache里面表结构信息,出现冲突问题导致。 * **规避措施:** 可以通过关闭globalcache来规避,各个backend线程使用自身的localcache,互不影响。 * **LocalCache说明:** Localsyscache中存放系统表以及业务表结构元数据。 当一个新的会话链接访问表时候,会先从localsyscache中看其是否存在,如果不存在则走打开表流程,读取到数据后会缓存在localsyscache中。这个会话如果是一个长链接,那么localcache会缓存会话中所有访问到的表结构信息。每个session都会做同样的操作,session级别缓存。 * **GlobalCache说明:** 如上localcache是session级别缓存,那么多个session可能都会打开和缓存同样的表结构数据。这样会导致重复数据占用内存。 引入globalsyscache后,会将表结构数据缓存到globalcache中,新的会话访问表时候,先从localcache找,找不到则去globalcache找,globalcache找不到则从本地打开,这样节省了多个session的cache占用,也能从globalcache内存拿数据,比磁盘读要快一些。 * **关闭globalcache带来的影响:** 新会话从globalcache读数据,比从磁盘读取性能上要快一些。(仅读取表结构) 如果会话是长链接,只要长链接不断开,那么该会话localcache一直会保存所打开的表结构信息,性能不会比globalcache慢上多少。 需要确认: local\_syscache\_threshold 配置是否够用,避免local\_syscache\_threshold缓存达到上限频繁进行置换。 可以通过`select * from gs_session_memory_detail where sesstype = 'postgres' order by usedsize limit 10;`来确定。 ### 复现验证 * **数据库版本:** 5.0.1 * **用例:** 参考[ISSUES I90JHX](https://gitee.com/opengauss/openGauss-server/issues/I90JHX?from=project-issue),表包含自增序列,进行增删改查操作。 * **并发数:** 用例启动100并发执行 * **数据库配置:** autovacuum\_naptime=10s 每隔10s执行一次autovacuum * 场景一:开启globalcache (enable\_global\_syscache=on) 运行10s左右,数据库core掉 ![image](figures/fig_6_5.png) 解core文件报错在在钩子函数为空 ![image](figures/fig_6_6.png) * 场景二:关闭globalcache (enable\_global\_syscache=off) 运行30min数据库进程正常。 ![image](figures/fig_6_7.png) --- --- url: /en.md --- --- --- url: /en/docs/common/contribute/documentation_writing_specifications.md --- # Documentation Writing Specifications This writing specification outlines the requirements for the structure, content elements, and language style of documents in the openGauss docs repository to ensure a consistent style across openGauss documentation. Before starting to write openGauss documentation, familiarize yourself with this specification. **Improvement suggestions are welcome**. ## Content Element Specifications ### Naming When creating new documents, add a MarkDown file (with the `.md` extension) to the appropriate directory. * **Rule**: Ensure the document name is unique and does not conflict with existing files. Rename if necessary. * **Rule**: Use **English** for all document names. * **Rule**: Avoid parentheses in file names, as they can disrupt directory display. Replace them with underscores (`_`) or hyphens (`-`). **Example**: ```text installation_and_deployment.md # Document for "Installation and Deployment" ``` ### Headings * **Rule**: Headings should clearly and concisely summarize the section content without omitting key details. * **Rule**: For procedural documents, use verb-object structures (for example, "Requesting Permissions"). Ensure consistency in heading structures for the same level and type. * **Rule**: Avoid ending headings with punctuation. Use parentheses for additional context and exclude special characters like `?`. * **Rule**: Separate headings from body text with a blank line. * **Rule**: Format headings with `#` followed by a space and the heading text. Increment heading levels one at a time, starting with the top-level heading. **Example**: ```markdown # Level 1 Heading ## Level 2 Heading ### Level 3 Heading #### Level 4 Heading ##### Level 5 Heading ###### Level 6 Heading ``` ### Body **Formatting instructions**: * *Italic*: Enclose text in single asterisks (`*`) for italic formatting. ```txt *italic text* ``` * **Bold**: Enclose text in double asterisks (`**`) for bold formatting. ```txt **bold text** ``` * ***Bold italic***: Enclose text in triple asterisks (`***`) for bold italic formatting. ```txt ***bold italic text*** ``` * Escape: Use a backslash (`\`) to escape special characters. ```txt \ ``` **Rule**: Always use the backslash (`\`) to escape characters as required. **Rule**: Separate consecutive escape characters with a space, for example, `\{ \}`. **Rule**: Maintain both Chinese and English versions of documentation. For translation support, contact . ### Images **Usage**: ```bash ![alt text](./path/to/image.png) ![alt text](./path/to/image.png "optional title") ``` **Rule**: Place all images in the **figures** subdirectory of the document folder. For example, the [Installation Guide](https://gitcode.com/opengauss/docs/tree/6.0.0/content/en/docs/InstallationGuide) stores its images in [this directory](https://gitcode.com/opengauss/docs/tree/6.0.0/content/en/docs/InstallationGuide/figures). Always use **relative paths** for references. **Rule**: Only use original or properly licensed images to avoid copyright issues. **Rule**: Position images adjacent to their relevant text sections. **Rule**: The preferred image format is PNG, with JPG as an alternative. Images must not exceed 640 pixels in height or 393 pixels in width, and should ideally be under 150 KB in file size. **Rule**: For screenshots, crop to focus on essential content within these dimensions. Use red borders or text labels to emphasize important details in graphics. **Example**: ```markdown ![](./figures/ci_check_result.jpg) ``` The `./` prefix in the path is mandatory for proper online display. ### Code Blocks Code examples illustrate how to implement specific features, serving as references for developers during coding and debugging. **Rule**: Ensure the code is logically and syntactically correct. **Rule**: Clearly separate input and output sections where applicable. **Rule**: Include comments to explain critical steps in the code. **Rule**: Enclose inline code and commands in single backticks (for example, `code snippet`). **Rule**: Format block code with either triple backquotes or four-space indentation (no TABs), preceded and followed by blank lines. **Examples** * Inline code ```markdown The `printf()` function ``` * Block code ```python #!/usr/bin/env python3 print("Hello, World!") ``` ```c #include int main(void) { printf("Hello world\n"); } ``` ### Lists * **Unordered lists**: Represented by asterisks (`*`), plus signs (`+`), or hyphens (`-`), each followed by a space. Maintain uniform markers within a list. ```markdown * First item * Second item * Third item + First item + Second item + Third item - First item - Second item - Third item ``` * **Ordered lists**: Numbered items with a trailing period (`.`). ```markdown 1. First item 2. Second item 3. Third item ``` * **Nested lists**: Sub-items indented by four spaces (no TABs). ```markdown 1. First item: - Sub-item A - Sub-item B 2. Second item: - Sub-item A - Sub-item B ``` **Rule**:Use ordered lists when items follow a clear sequence or logical order. **Rule**:Use unordered lists for parallel relationships or multiple-choice options. **Rule**:Omit punctuation for terms or phrases in list items. **Rule**:Include periods for complete sentences in list items. **Rule**:If mixing phrases and sentences is unavoidable, apply periods to all items. **Rule**:Alternatively, separate items with semicolons, ending the final item with a period. ### Annotation Symbols The following annotation symbols may appear in documentation to indicate different scenarios and levels of importance. Select the appropriate symbol based on the significance of the information being highlighted. | Symbol | Purpose/Meaning | Usage | |--------|----------------|-------| | **Warning** | Failure to follow this warning may cause task interruption or unexpected results, though recovery is possible. | `> [!WARNING]Warning` `> Content` | | **Note** | Provides helpful tips or useful reference information. | `> [!NOTE]Note` `> Content` | > \[!NOTE]Note > > * Choose the appropriate annotation symbol based on the documentation context and apply the correct styling. > * Notes/Warnings can contain nested ordered/unordered lists, but avoid tables and code blocks. > * To prevent style breaks, ensure `>` remains continuous. > * Keep note/warning content concise. Consider placing lengthy explanations in the main text or splitting them into sections. Avoid excessive empty lines within styled blocks. ### Links **Rule**: Verify link destinations exist to prevent navigation errors. Use standard Markdown syntax instead of HTML. **Examples**: ```markdown - Website link This is the link to the [DataKit website](https://www.datakit.com). - Relative path [CI Pipeline Rules](./ci_rules.md) ``` ### Tables **Rule:** Use standard Markdown table syntax in documentation. Avoid HTML table formatting. **Example:** ```markdown | Header 1 | Header 2 | | -------- | -------- | | Cell 1 | Cell 2 | | Cell 3 | Cell 4 | ``` **Alignment options:** * `-:` Right-aligned content * `:-` Left-aligned content * `:-:` Centered content **Rule**: Omit punctuation when all cells in a column contain terms/phrases. **Rule**: Use periods when all cells contain complete sentences. **Rule**: Apply periods uniformly if mixed content cannot be avoided. ### Punctuation **Rule:** For numbered/bulleted lists, use periods consistently if items are complete sentences. Omit punctuation if all items are phrases. **Maintain uniformity: either apply punctuation throughout or omit it entirely.** **Rule:** Always use half-width (ASCII) numerals. **Rule:** Reserve exclamation marks exclusively for warnings about critical consequences involving equipment safety or personal harm. Avoid exclamation marks in all other contexts. ## Language Style Specifications **Rule:** Submissions must exclusively pertain to openGauss features. **Rule:** Content must not include sensitive information or material exhibiting strong racial/gender discrimination. **Rule:** All submissions must be original work without intellectual property infringement. **Rule:** Content must remain factual and objective. Avoid exaggerated promotional language. **Unacceptable documentation practices** Submitting excessive pull requests in a short timeframe via automated tools to address trivial issues (such as typos, grammar errors, date inaccuracies, and awkward phrasing) without substantive value. --- --- url: /zh/docs/common/contribute/markdownlint_rules.md --- # markdownlint 检查规则 本文介绍了 markdownlint v0.12.0 版本规则以及 openGauss Docs 仓的规则设置,参照依据 。对 markdownlint 规则有任何疑问或交流,请联系 wu-donger[@Evawudonger](https://gitcode.com/Evawudonger)。 ## markdownlint 介绍 markdownlint 是一款检查 Markdown 文件格式的工具,可以根据设置的规则对 Markdown 文件进行全面的检查。文档写作时可以借助 VSCode 等工具的 markdownlint 插件修复格式问题。 ## openEuler docs 仓规则设置 * openEuler 规则采用如下方案: * MD003 (标题样式) 规则将参数 `style`设置为`atx`。 * MD029(有序列表的前缀序号)规则将参数`style`设置为`ordered`。 * 屏蔽 MD004(无序列表)这条规则。 * 屏蔽 MD007(无序列表缩进)这条规则。 * 屏蔽 MD009(行尾空格)这条规则。 * 屏蔽 MD013(行的长度)这条规则。 * 屏蔽 MD014(命令前使用$而不显示输出)这条规则。 * 屏蔽 MD020(closed atx样式的标题内没有空格)这条规则。 * 屏蔽 MD021(closed atx样式的标题内有多个空格)这条规则。 * 屏蔽 MD024(不能有重复内容的标题)这条规则。 * 屏蔽 MD025 (文档中有多个顶级标题)这条规则。 * 屏蔽 MD027(块引用符号后的多个空格)这条规则。 * 屏蔽 MD033(内联HTML)这条规则。 * 屏蔽 MD036(使用强调标记代替标题)这条规则。 * 屏蔽 MD046(代码块样式)这条规则。 * ruby 文件的书写方式如下: ```bash all rule 'MD003', :style => :atx rule 'MD029', :style => :ordered exclude_rule 'MD004' exclude_rule 'MD007' exclude_rule 'MD009' exclude_rule 'MD013' exclude_rule 'MD014' exclude_rule 'MD020' exclude_rule 'MD021' exclude_rule 'MD024' exclude_rule 'MD025' exclude_rule 'MD027' exclude_rule 'MD033' exclude_rule 'MD036' exclude_rule 'MD046' ``` ## 规则介绍 ### MD001 - 标题级别一次只能增加一个级别 * **错误示例** ```text # Header1 ### Header3 ``` * **正确示例** ```text # Header1 ## Header2 ### Header3 #### Header4 ``` ### MD002 - 第一个标题应该是顶层标题 * **参数** * `level`:指定最高级标题的级数,默认值是1。 * **错误示例** ```text ## This is not a H1 header ### Another header ``` * **正确示例** ```text # Start with a H1 header ## Then use a H2 for subsections ``` ### MD003 - 标题样式 * **参数** * `style`:指定文档标题的样式,有 `consistent`、`atx`、`atx_closed`、`setext`、`setext_with_atx`五种。**本仓已设置为 `atx`**。 * **错误示例** ```text # ATX style H1 ## Closed ATX style H2 ## Setext style H1 =============== ``` * **正确示例** ```text # ATX style H1 ## ATX style H2 ``` ### MD004 - 无序列表样式 **本仓已屏蔽这条规则。** * **参数** * `style`:指定无序列表的样式,有 `consistent(定义时符号前后保持一致)`、`asterisk(用星号定义)`、`plus(用加号定义)`、`dash(用减号定义)`、`sublist(定义多重列表的时候用不同的符号定义)`五种,默认为 `consistent`。 * **错误示例** ```text * Item 1 + Item 2 ``` * **正确示例** ```text * Item 1 * Item 2 ``` ### MD005 - 同一级别的列表项缩进不一致 * **错误示例** ```text * Item1 * nested item 1 * nested item 2 * A misaligned item ``` * **正确示例** ```text * Item1 * nested item 1 * nested item 2 * nested item 3 ``` ### MD006 - 一级列表不能缩进 * **错误示例** ```text Some text * List item * List item ``` * **正确示例** ```text Some text * List item * List item ``` ### MD007 - 无序列表缩进 **本仓已屏蔽这条规则。** * **参数** * `ident`:指定无序列表嵌套时缩进的空格数,默认值是2。 * **错误示例** ```text * List item * Nested list item indented by 4 spaces ``` * **正确示例** ```text * List item * Nested list item indented by 2 spaces ``` ### MD009 - 行尾空格 **本仓已屏蔽这条规则。** * **参数** * `br_spaces`:指定在行尾可以添加的空格的数目,默认值为0,空格数目建议大于等于2,如果小于2,会默认为0。 ### MD010 - 不能使用tab键缩进,要使用空格 * **参数** * `code_blocks`:指定本条规则在代码块里是否 (true or false) 生效,默认是 true。 * **错误示例** ```text Some text * hard tab character used to indent the list item ``` * **正确示例** ```text Some text * Spaces used to indent the list item instead ``` ### MD011 - 反向链接语法 * **错误示例** ```text (Incorrect link syntax)[http://www.example.com] ``` * **正确示例** ```text [Correct link syntax](http://www.example.com) ``` ### MD012 - 多个连续的空行 * **参数** * `maximum`:指定文档中可以连续的最多的空行数,默认值是1。 * **错误示例** ```text Some text here Some more text here ``` * **正确示例** ```text Some text here Some more text here ``` > \[!NOTE]说明 > 如果代码块内有多个连续的空行,将不会触发此规则。 ### MD013 - 行的长度 **本仓已屏蔽这条规则。** * **参数** * `line_length`:指定行的最大长度,默认是80。 * `heading_line_length`:指定标题行的最大的长度,默认是80。 * `code_blocks`:指定规则是否(true or false)对代码块生效,默认是true。 * `tables`:指定规则是否(true or false)对表格生效,默认是true。 * `headings`:指定规则是否(true or false)对标题生效,默认是true。 ### MD014 - 命令前使用$而不显示输出 **本仓已屏蔽这条规则。** * **错误示例** ```text ls cat foo less bar ``` * **正确示例** ```text ls cat foo less bar ``` ```text $ ls foo bar $ cat foo Hello world $ cat bar baz ``` 在代码块中,终端命令前不需要要有$,但是如果代码中既有终端命令,也有命令的输出,则终端前可以有$。 ### MD018 - atx样式的标题后没有空格 * **错误示例** ```text #Header1 ##Header2 ``` * **正确示例** ```text # Header1 ## Header2 ``` ### MD019 - atx样式的标题后有多个空格 * **错误示例** ```text # Header1 ## Header2 ``` * **正确示例** ```text # Header1 ## Header2 ``` ### MD020 - closed atx样式的标题内没有空格 **本仓已屏蔽这条规则。** * **错误示例** ```text #Header1# ##Header2## ``` * **正确示例** ```text # Header1 # ## Header2 ## ``` ### MD021 - closed atx样式的标题内有多个空格 **本仓已屏蔽这条规则。** * **错误示例** ```text # Header1 # ## Header2 ## ``` * **正确示例** ```text # Header1 # ## Header2 ## ``` ### MD022 - 标题行的上下行应该都是空行 * **参数** * `lines_above`:指定标题行上方的空行数,默认值是1。 * `lines_below`:指定标题行下方的空行数,默认值是1。 * **错误示例** ```text # Header1 Some text Some more text ## Header2 ``` * **正确示例** ```text # Header1 Some text Some more text ## Header2 ``` ### MD023 - 标题必须从行首开始 * **错误示例** ```text Some text ## Indented header ``` * **正确示例** ```text Some text ## Header ``` ### MD024 - 不能有重复内容的标题 **本仓已屏蔽这条规则。** * **错误示例** ```text # Some text ## Some text ``` * **正确示例** ```text # Some text ## Some more text ``` ### MD025 - 文档中有多个顶级标题 **本仓已屏蔽这条规则。** * **参数** * `level`:指定文档最高级的标题,默认值是1。 * **错误示例** ```text # Top level header # Another top level header ``` * **正确示例** ```text # Title ## Header ### Another header ``` ### MD026 - 标题行尾的标点符号 * **参数** * `punctuation`:指定标题行尾不能有的标点符号,默认值是".,;:!?"。 * **错误示例** ```text # This is a header. ``` * **正确示例** ```text # This is a header ``` ### MD027 - 块引用符号后的多个空格 **本仓已屏蔽这条规则。** * **错误示例** ```text > This is a block quote with bad indentation > there should only be one ``` * **正确示例** ```text > This is a block quote with bad indentation > there should only be one ``` ### MD028 - 块引用内的空行 * **错误示例** ```text > This is a blockquote > which is immediately followed by > this blockquote. Unfortunately > in some parsers, this are treated as the same blockquote. ``` * **正确示例** ```text > This is a blockquote. > > This is the same blockquote. ``` ### MD029 - 有序列表的前缀序号 * **参数** * `style`:指定前缀序号的格式,有 `one`(只用1做前缀),`ordered`(从1开始的加1递增数字做前缀)两种,默认值是 `one`。**本仓设置为`ordered`**。 * **错误示例** ```text 1. Do this 1. Do that 1. Done ``` * **正确示例** ```text 1. Do this 2. Do that 3. Done ``` ### MD030 - 列表标记后的空格 * **参数** * `ul_single`:无序列表单个段落的前缀符号和文字之间的空格数,默认值是1。 * `ol_single`:有序列表单个段落的前缀符号和文字之间的空格数,默认值是1。 * `ul_multi`:无序列表多个段落的前缀符号和文字之间的空格数,默认值是1。 * `ol_multi`:有序列表单个段落的前缀符号和文字之间的空格数,默认值是1。 * **错误示例** ```text * Foo * Bar * Baz ``` * **正确示例** ```text * Foo * Bar * Baz ``` ### MD031 - 单独的代码块前后需要用空格隔开(除非是在文档的开头或者结尾) * **错误示例** ````text Some text ``` Code block ``` ``` Another code block ``` Some more text ```` * **正确示例** ````text Some text ``` Code block ``` ``` Another code block ``` Some more text ```` ### MD032 - 列表前后需要用空格隔开(除非是在文档的开头或者结尾) * **错误示例** ```text Some text * Some * List 1. Some 2. List Some text ``` * **正确示例** ```text Some text * Some * List 1. Some 2. List Some text ``` ### MD033 - 内联HTML **本仓已屏蔽这条规则。** * **错误示例** ```text

Inline HTML header

``` * **正确示例** ```text # Markdown header ``` ### MD034 - 使用纯URL * **错误示例** ```text For more information, see http://www.example.com/. ``` * **正确示例** ```text For more information, see . ``` ### MD035 - 水平线样式 * **参数** * `style`:指定创建水平线的方式,有 `consistent`、`***`、`---`或其他指定水平线的字符串,默认值是 `consistent`。 ### MD036 - 使用强调标记代替标题 **本仓已屏蔽这条规则。** * **参数** * `punctuation`:指定用于结尾的标点符号,以此符号结尾的强调不会被视为以强调代替标题,默认值是".,;:!?" * **错误示例** ```text **My document** Lorem ipsum dolor sit amet... _Another section_ Consectetur adipiscing elit, sed to eiusmod ``` * **正确示例** ```text # My document Lorem ipsum dolor sit amet... ## Another section Consectetur adipiscing elit, sed to eiusmod ``` ### MD037 - 强调标记内强调的符号和强调的文字之间不能有空格 * **错误示例** ```text Here is some ** bold ** text Here is some * italic * text Here is some more __ bold __ text Here is some more _ italic _ text ``` * **正确示例** ```text Here is some **bold** text Here is some *italic* text Here is some more __bold__ text Here is some more _italic_ text ``` ### MD038 - 单反引号和之间的内容不能有空格 * **错误示例** ```text ` some text ` `some text ` ` some text` ``` * **正确示例** ```text `some text` ``` ### MD039 - 链接文本和包围它的中括号之间内容不能有空格 * **错误示例** ```text [ a link ](http://www.example.com/) ``` * **正确示例** ```text [a link](http://www.example.com/) ``` ### MD040 - 代码块应指定代码块的编程语言 * **错误示例** ````text ``` #!/bin/bash echo Hello world ``` ```` * **正确示例** ````text ```bash #!/bin/bash echo Hello world ``` ```` * **常用的代码块编程语言** | 语言支持 | 关键字 | | ---------------- | -------- | | Python | python | | C | cpp | | Java | java | | Shell | bash | | Markdown | markdown | | JavaScript | js | | CSS | css | | SQL | sql | | PHP | php | | Text | text | | XML | html | | Bat | bat | | Protocol Buffers | protobuf | ### MD041 - 文件中的第一行应该是顶级标题 * **参数** * `level`:指定文档最高级的标题,默认值是1。 * **错误示例** ```text This is a file without a header ``` * **正确示例** ```text # File with header This is a file with a top level header ``` ### MD046 - 代码块样式 **本仓已屏蔽这条规则。** * **参数** * `style`:指定代码块定义格式,有 `fenced(使用三个反引号)`,`indented(使用缩进)`,`consistent(上下文一致)`三种,默认值是 `fenced`。 * **错误示例** ```text Some text. Code block Some more text. ``` * **正确示例** ````text Some text. ```ruby Code block ``` Some more text. ```` ### MD047 - 文件应以单个换行符结尾 * **错误示例** ```text # Header This file ends without a newline.[EOF] ``` * **正确示例** ```text # Header This file ends with a newline. [EOF] ``` ## VSCode 中 Markdown 插件 markdownlint 扩展库包含 markdown 文件规则库,以保证 markdown 文件与其标准保持一致。添加配置后,markdownlint 可以自动检查文档错误。 ### 安装 * 按下 `Ctrl_Shift+X`以打开扩展选项卡。 * 输入 `markdownlint` 以找到扩展。 * 点击 `Install` 按钮,然后再点击`Enable`按钮。 ### 配置 注意:VSCode 中 markdownlint 参照的版本是 David Anson 拟定的,与 openEuler 仓使用的 markdownlint 官方 v0.12.0 版本有差异。为了与 openEuler 仓配置的规则保持一致,可参考下方配置项。 * 在命令面板(`Ctrl+Shift+P`)中输入`Open Settings (JSON)`命令。 * 在 Json 对象中添加如下配置: ```bash "markdownlint.config":{ "default":true, "MD003":{"style":"atx"}, "MD029":{"style":"ordered"}, "MD004":false, "MD007":false, "MD009":false, "MD013":false, "MD014":false, "MD020":false, "MD021":false, "MD024":false, "MD025":false, "MD033":false, "MD036":false, "MD042":false, "MD043":false, "MD044":false, "MD045":false, "MD046":false, "MD048":false, "MD049":false, "MD050":false, "MD051":false, "MD052":false, "MD053":false, "MD055":false, "MD056":false, "MD057":false } ``` --- --- url: /en/docs/common/contribute/directory_structure_introductory.md --- # Overview ## Introduction This document describes the structure of the documentation repository. The **docs** and **docs-lite** directory in the repository contains content published on the official website. It includes **en** and **zh** subdirectories for English and Chinese documentation, respectively, mirroring the website structure. The repository also features an **archive** directory for documents not yet ready for publication. Once finalized, these documents are moved to the **docs** and **docs-lite** directory for website display. ```text ├─archive │ ├─en │ └─zh ├─docs │ ├─en │ └─zh ├─docs-lite │ ├─en │ └─zh ``` ## Document Repository Structure Overview Below is the directory structure (the following directory structures use **en** as an example): ```text ├─openGauss/docs ├─docs │ ├─zh │ └─en │ ├─release_notes │ ├─about_opengauss │ ├─getting_started │ ├─installation_guide │ ├─sql_reference │ ├─database_administration_guide │ ├─database_om_guide │ ├─performance_tuning_guide │ ├─data_migration_guide │ ├─resource_pooling │ ├─developer_guide │ ├─compilation_guide │ ├─extension_reference │ ├─database_reference │ ├─tool_and_commandreference │ ├─characteristic_description │ └─appendix ├─docs-lite │ ├─zh │ └─en ``` ### Directory Structure File (\_toc.yaml) Every manual includes a **\_toc.yaml** file. For example: ```yaml label: Installation Guide isManual: true sections: - label: Installation Overview href: ./installation_overview.md - label: Container-based Installation href: ./container_based_installation.md sections: - label: Installation on a Single Node href: ./installation_on_a_single_node_container.md ``` * label: The manual title. * isManual: A manual flag. * sections: * label: The name of the first-level directory. * href: A reference to the manual directory structure file. --- --- url: /zh/docs/common/contribute/documentation_writing_specifications.md --- # 写作规范 本写作规范针对 openGauss docs 仓的文档结构、内容元素和语言风格提出规范要求,确保 openGauss文档具备一致风格。 开发者开始 openGauss文档写作前,建议先了解本规范内容,**欢迎提出改进意见**。 ## 内容元素规范 ### 命名 对于新增文档,请在对应的文件目录下新增 MarkDown 文档(即以 .md 结尾的文件)。 【规则】zh/en目录下,新增文档名称不能与已有文档重名,如果有请重新命名。 【规则】文件名需要以**英文**小写命名。 【规则】若文件名有多个单词,请以下划线(\_)连接。 【规则】同一篇文档,中英文文档文件名保持一致。 【举例】 ```text installation_and_deployment.md #新增‘安装与部署’文档 ``` ### 标题 【规则】标题尽量采用简洁的语句概况反映章节的中心内容,注意不要省略必要的信息。 【规则】操作类文档标题尽量用动宾结构(例如:申请权限);相同级别,相同类型的标题结构保持一致。 【规则】标题不使用标点符号结尾,标题中尽量采用圆括号来表示补充说明,标题中不能出现特殊字符,如“?”。 【规则】标题与正文使用 1 整行换行隔开。 【规则】标题使用 “#” 空格连接标题名,标题级别一次只能增加一个级别且第一个标题应该是顶层标题。 【举例】 ```markdown # 一级标题 ## 二级标题 ### 三级标题 #### 四级标题 ##### 五级标题 ###### 六级标题 ``` ### 正文 【使用方法】 * 斜体:使用一个星号(\*)表示斜体。 ```txt *斜体文本* ``` * 粗体:使用两个星号(\*\*)表示粗体。 ```txt **粗体文本** ``` * 粗斜体:使用3个星号(\*\*\*)表示粗斜体。 ```txt ***粗斜体文本*** ``` * 转义:对特定内容使用转义符 \。 ```txt \<转义的标记符号> ``` 【规则】该转义的字符必须严格用转义符 \ 。 【规则】如果有连续两个转义符,转义符之间要有空格 { }。 【规则】国际化:需同时提供中英文文档,可联系[wu-donger](https://gitcode.com/Evawudonger)协助翻译。 ### 空格 【规则】编辑文档时中文和英文之间**建议**加空格,页面展示更美观,请保持全文一致。如果是产品名词如 “豆瓣FM”,请按照官方定义格式书写。 例如:openGauss 是一款支持 SQL2003 标准语法,支持主备部署的高可用关系型数据库。 【规则】中文和数字之间加空格。 【规则】数字和单位之间不加空格。 【规则】全角标点与其他字符之间不加空格。 例如:刚刚成为了 openGauss 的 maintainer,好开心。 ### 图片 【使用方法】 ```bash ![alt 属性文本](图片地址) ![alt 属性文本](图片地址 "可选标题") ``` 【规则】图片统一存放到文档同级目录下的 figures 文件夹中。例如,[《安装指南》](https://gitcode.com/opengauss/docs/tree/6.0.0/content/zh/docs/InstallationGuide)中的手册中使用的图片,统一存储在 路径下。该文件夹下的文件引用图片时,使用相对引用。 【规则】请使用原创图片,避免存在知识产权侵权风险。 【规则】图文配合使用,切忌图文分离。 【规则】图片格式首选 png,此外也接受 jpg。图片的高不超过 640px,宽不超过 393px,图片大小建议不超过 150K。 【规则】中文用中文插图,英文用英文插图。 【规则】图片路径不能包含中文。 【规则】如果是截图,请在允许的范围内只保留有用的信息。图形中需要突出的关键信息,可增加红色框线或者文字备注说明。 【举例】 ​图片以 `![](./figures/ci检查结果.jpg)` 格式书写,“./” 不可少,否则图片无法显示到现网。 ### 代码块 代码示例说明了如何实现特定功能,开发人员使用代码示例来编写和调试代码。 【规则】代码的逻辑和语法正确。 【规则】代码的输入和输出尽可能的分开。 【规则】保证代码中关键步骤要有注释说明。 【规则】文中行内代码和命令行使用 1 对反引号,如: `代码块`。 【规则】块级代码使用 3 个反引号或 4 个空格(不能用 TAB 键)缩进,且上下均用整行隔开。 【举例】 * 行内代码 ```txt `printf()` 函数 ``` * 块级代码 ```python #!/usr/bin/env python3 print("Hello, World!"); ``` ```c #include int main(void) { printf("Hello world\n"); } ``` ### 列表 * 无序列表:无序列表使用星号(**\***)、加号(**+**)或是减号(**-**)作为列表标记,这些标记后面要添加一个空格,然后再填写内容。同一个无序列表,建议使用同一个符号。 ```txt * 第一项 * 第二项 * 第三项 + 第一项 + 第二项 + 第三项 - 第一项 - 第二项 - 第三项 ``` * 有序列表:有序列表使用数字并加上 **.** 号来表示。 ```txt 1. 第一项 2. 第二项 3. 第三项 ``` * 嵌套列表:列表嵌套只需在子列表中的选项前面添加四个空格(注意不是Tab键)即可。 ```txt 1. 第一项: - 第一项嵌套的第一个元素 - 第一项嵌套的第二个元素 2. 第二项: - 第二项嵌套的第一个元素 - 第二项嵌套的第二个元素 ``` 【规则】有明显先后逻辑顺序情况请使用有序列表,并列关系、多选一情况请使用无序列表。 【规则】当项目列表是术语、短语时,统一不加标点符号。 【规则】当项目列表是句子时,统一加句号。 【规则】特殊情况下如果不能避免出现短语和句子混合的情况,统一加句号。 【规则】项目列表前几项以分号结尾,最后一项以句号结尾的形式也可以接受。 ### 注释符号 文档中会出现以下注释符号,代表不同的使用场景和提示程度。如果需要提示用户注意的信息,可以根据重要程度选择对应的注释符号。 | 注释符号 | 用途/含义 | 使用方法 | |--------|------------------------------------------------------------------|-----------------------------------------------------------------------------| | 注意 | 如未按该注意事项操作,可能会导致任务中断或结果异常,但是可恢复。 | `> [!WARNING]注意` `> 正文内容` | | 说明 | 提供帮助提示或有用的参考信息。 | `> [!NOTE]说明` `> 正文内容` | > \[!NOTE]说明 > > * 请根据文档具体场景选择对应的注释符号,并按照使用方法正确使用样式。方括号内是英文感叹号。 > * 说明/注意样式内可嵌套有序/无序列表,但不建议表格和代码块。 > * 为避免样式断开,需要保证 `>`连续。 > * 说明/注意内容避免过长,可考虑写在正文或者分段,请不要添加过多样式内空行。 ### 链接 【规则】链接需要确保指向的目标文件存在,否则会造成链接跳转不正常,不建议使用 HTML 的链接样式。 【规则】引用如果是某篇文档,建议用书名号包裹。 【举例】 ```markdown - 网站链接 DataKit 的安装步骤请参考[《安装与部署》](https://www.datakit.com)。 - 相对路径 [文档开发流水线门禁](./ci_rules.md) ``` ### 锚点 【规则】若要引用文档中的标题、图片或表格,可插入锚点,从而实现向文档特定位置的快速跳转。 【规则】锚点格式:将标题中大写字母转换为小写,空格替换为中划线`-`,并去除特殊符号。 【举例】 ```markdown # 安装前准备 A* 这是A-Tune的安装前准备。 ... 参考[安装前准备](#安装前准备-a)章节。 ``` ```markdown **图1** CI 检查结果 ![CI 检查结果](./figures/ci检查结果.jpg) ... 参考图1[CI 检查结果](#fig1)。 ``` ### 表格 【规则】markdown 文档中请使用以下方式创建表格,不建议使用 HTML 的表格样式。 【举例】 | 表头1 | 表头2 | | ---------- | -------- | | 单元格1 | 单元格2 | | 单元格4 | 单元格4 | 【使用方法】 设置表格的对齐方式: * -: 设置内容和标题栏居右对齐。 * :- 设置内容和标题栏居左对齐。 * :-: 设置内容和标题栏居中对齐。 【规则】当表格内一列全部是术语、短语时,统一不加标点符号。 【规则】当表格内一列全部是句子时,统一加句号。 【规则】特殊情况下如果不能避免出现短语和句子混合的情况,统一加句号。 ### 标点符号 【规则】单位与数字之间不建议加空格,比如 50m,10kg,64Kbit/s。 【规则】对于有序/无序列表,如果是长句子,建议统一以句号结尾,如果是短语,结尾可不用标点。**重点是前后一致,要么都加,要么都不加**。 【规则】中文文档使用全角标点。 【规则】数字使用半角字符。 【规则】感叹号使用场景为可能引发严重后果的操作或设备安全、人身安全的警告。其他场景不允许使用感叹号。 【规则】文内引用其他文档时添加书名号,同时建议增加引用文档的跳转链接。例如:安装 openGauss 数据库,安装方法参考[《openGauss 6.0.0 安装指南》](https://docs.opengauss.org/zh/docs/6.0.0/docs/InstallationGuide/InstallationGuide.html)。 ## 语言风格规范 【规则】提交内容必须是与 openGauss 特性相关内容。 【规则】内容不能包含敏感信息、有强烈的种族歧视或性别歧视的内容。 【规则】提交的内容必须是原创内容,不得侵犯他人知识产权。 【规则】提交的内容必须客观、真实,不允许使用夸大宣传等词汇。 **文档贡献中不受欢迎的行为** 短时间内通过自动化工具,提交大量的PR,提交大量的处理诸如拼写错误,语法错误,日期错误,语句不通顺等“无害的错误”的修正。 --- --- url: /zh/docs/common/faq/installation.md --- # 基础安装常见问题与解决方法 ## **问题1:6.0.0版本扩容失败** ### 问题描述 6.0.0版本数据库,进行扩容,扩容执行失败。 ### 问题定位 #### 节点ip对应多个hostname 1. 扩容失败报错如下: ![image](figures/fig_installation_1_1.png) 根据报错信息查看代码,在相应位置添加日志打印,发现是ip和hostname的映射有问题,因此在通过 ssh远程执行命令时报错。 如果也是使用6.0.0版本的用户,可以排查一下是否也需要修改,查看是否也存在该问题。(该问题一般 是由于在一台服务器上起了多了业务,除了数据库外。有其他业务也创建了互信,但是记录的ip hostname与数据库记录的不同导致),通过查看文件即可确认,如下所示: ```sh cat /etc/hosts ``` 2. 查看社区OM仓,发现已经有相关的修改pr: [pr-954](https://gitee.com/opengauss/openGauss-OM/pulls/954) [pr-969](https://gitee.com/opengauss/openGauss-OM/pulls/969) 3. 通过git工具将修改apply到6.0.0LTS版本中。 4. 编译OM ```sh cd openGauss-OM sh build.sh -3rd /xxxxxx/binarylibs ## 路径为3方库路径,3方库可在openGauss-server的readme中找到编译好的报就在package目录下面 ``` 5. 两种场景下进行本地验证。 1. 已安装的环境,替换OM包验证: * 下载官网安装包安装1主2备环境 192.168.0.19/20/21 * 缩容21节点,成功 * 修改/etc/hosts文件,是192.168.0.21对应多个hostanme,改为 * 清理21节点数据库 5- 在19节点执行扩容,预期应该失败 结果:失败 * 修改om代码,重新编译,并且替换OM安装包 替换OM的两个文件,重新解压om包,解压之后会自动覆盖之前的script目录 * 拷贝xml文件(原来的xml不要删),清理掉删除21节点信息 在主节点重新执行preinstall,-X指定的为新的xml文件。通过preinstall将之前安装的OM脚本替换掉 结果:执行成功 * 执行扩容,执行成功 2. 重新安装:只需替换掉安装包中OM包,安装之后进行扩容测试即可。 6. 验证无问题之后发给客户。 #### bclinux系统安装openGauss失败 安装包发给客户之后,客户环境进行验证,客户反映执行安装仍然失败。 1. 报错如下: ![image](figures/fig_installation_1_2.png) 问题如下: 在扩容节点上找不到文件ENVFILE; 扩容节点执行预安装gs\_preinstall失败。 2. 问题定位: * 在扩容节点上找不到文件ENVFILE问题: 1. 首先查看预安装命令以及报错的路径是否正常,常看之后无异常。 2. 查看代码发现,在预安装失败后,失败节点会自动清理环境变量问题,所以该报错是预安装失败导致。 * 预安装失败问题 1. 根据图中报错,会将结果重定向到gs\_local.log日志中,查看该日志,未发现异常(主节点日志 正常,待扩容节点无该日志生成) 2. 查看gs\_expersion扩容工具的日志,在$GAUSSLOG/om路径下,在该日志下发现异常,报 错:不支持bclinux系统安装。 3. 之前帮助客户定位过该问题,给客户提供过安装包以及修改方式;咨询客户对接的同事,发现 安装时是手动改的om脚本,没有把修改同步到安装包里面(之前对接的客户同事离职了,新同事按照文 档改的)。而在扩容的时候,om工具会向扩容节点将安装包传到扩容节点(不是发送的他们修改后的脚 本,是发送的安装包),因此确认是该问题导致。 4. 重新编译OM,将两个问题的修改都同步到6.0.0LTS版本中,验证后发给客户。该问题对应修改 的pr链接如下:[pr-802](https://gitee.com/opengauss/openGauss-OM/pulls/802) ![image](figures/fig_installation_1_3.png) 3. 其他问题 其间还出现了一个问题,缺少.so文件。 ![image](figures/fig_installation_1_4.png) * 查看是否存在该文件,`find/-namelibffi.so*`。结果如下: ![image](figures/fig_installation_1_5.png) * 该问题为.so文件的版本不一致,查找资料发现libffi.so.7与libffi.so.6兼容,因此可以创建软连接解决。 `ln-s/usr/lib/libffi.so.7/usr/lib/libffi.so.6` #### 扩容后扩容节点启动失败问题 客户验证,之前的问题并未报错,但是在最后一步拉起扩容节点的时候,拉起失败。 1. 报错如下: ![image](figures/fig_installation_1_6.png) 2. 问题定位: * 查看数据库状态,如下: ![image](figures/fig_installation_1_7.png) 初步确认该节点cm\_server和数据库进程启动都存在问题。 * 到对应节点上面进行查看`psux`: 查看该节点进程启动情况,发现cm相关的cm\_agent、cm\_server、om\_monitor进程以及数据库进程都没有,因此需要查看om\_monitor日志。 ```txt 前情提要:数据库启动顺序如下 定时任务->om_monitor->cmagent->cm_server、数据库、自定义资源 (crontab-l查看定位任务无异常,因此需要查看ommonitor日志) ``` om\_monitor日志中找到报错(如下图),发现是设置打开的最大句柄数不够,最小需要640000: ![image](figures/fig_installation_1_8.png) 查看命令`ulimit-n`或`ulimit-a`。 ### 解决方案 修改`/etc/security/limits.conf`文件,进行配置。 ``` omm   soft  as unlimited omm   hard  as unlimited omm   soft  nproc unlimited omm   hard  nproc unlimited ``` 修改之后,该节点会自动拉起(需要等待一段时间,定时任务1分钟一次拉起om\_monitor)问题解决。 ## **问题2:centos8版本安装适配** ### 背景描述 centos8从2021年年底开始停服,openGauss并未给centos8做安装适配。 但是存在部分客户仍然使用centos8以及相应发行版,但是社区发布的镜像不能直接拿来安装,需要单独为centos8出包。 ### 安装指导 #### 选型 centos8的内核版本和openssl版本: 更接近于openEuler20.03 (kernel=4.19.10 和 openssl=1.1.1d ) 而 Centos7 下 , ( kernel=3.10 和 openssl=1.1.0 ) , 在 centos 上 编 译 的 三 方 库 会 去 找 libssl.so.1.10导致找不到报错。 因此,适配centos8,使用社区发布的openEuler20.03的Server内核 + 编译适配的OM包 #### OM出包步骤 OM依赖一些三方组件,而这些三方组件依赖openssl,因此需要再centos8系统上重新编译OM 依赖的三方组件。 以5.0.0版本为例: 1. 下载三方库源码:`git clone https://gitee.com/opengauss/openGauss-third_party.git -b 5.0.0`。 2. 安装编译依赖:`yum install python3-devel libffi-devel expect libaio-devel readline-devel -y`。 3. 编译OM依赖的组件: 在 openGauss-third\_party/dependency/build 目录下,有一个 om\_build\_dependency.sh 脚本,该脚本里面放着om依赖的组件。 注释掉该组件里面的openssl,即不编译openssl组件。(我们要用系统的openssl) ![image](figures/fig_installation_2_1.png) 4. 编译三方依赖,编译的结果在源码目录下的 output 下:`sh om_build_dependency.sh`。 5. 三方库挪下二进制(将三方组件编译出来的so二进制,从python版本号的目录下,拷贝到上一级目录。) ```sh find . -name lib3.6 for i in `cat filepath`;do echo $i;cp $i/*.so $i/..;done ``` 这里是因为适配多个python版本需求,给每个so依赖建立个目录(如python3.6的目录是 lib3.6)存放,实际使用时候需要挪到上一层目录。(6.0.0版本后OM可以从lib3.6下面找,就不 需要这一步了。) 至此,OM依赖的三方组件编译完成。 6. 编译OM包 下载om代码,OM代码的 script/gs\_preinstall 文件删除这个函数(因为这里面校验了so文件的架构和系统是否匹配,但是我们新编的包里面没有这里需要的so文件,因此删除跳过) `check_os_and_package_arch`。 对于script下增加的 scp ssh ssh-\* 脚本转换格式。(主要是在安装时候遇到格式不对的报错) ![image](figures/fig_installation_2_2.png) ```sh echo "scp ssh ssh-add ssh-agent ssh-copy-id ssh-keygen" > sshfiles for i in `cat sshfiles`; do sed 's/^M//' $i > tmp_filename;mv -f tmp_filename $i;done; for i in `cat sshfiles`; do sed -i 's/\r$//' $i ;done; rm sshfiles cat -A file 检查下 ``` OM 打包 ```sh sh build.sh -3rd /opt/compile/openGauss-third_party/output/ ``` 7. 合并总包: 从社区下载完整的 openEuler20.03得ALL包,把里面的-om.tar.gz -om.sha256删除,将openGauss-OM/package下的包移动进来(OM包名字是否修改没关系,不需要识别),重 新打个ALL总包即可。 #### 其他问题 1. preinstall卡主不动可能是lib有问题,无法import导入。在lib下 python3 -c 'import xxx'进行检查。 ```sh [root@centos8 lib]# find . -name lib3.6 ./nacl/lib3.6 ./cryptography/hazmat/bindings/lib3.6 ./bcrypt/lib3.6 ``` 里面的so都要拷贝到外一层,即可lib3.6平级。 2. scp等脚本格式不对。 ```sh /data1/zxb/openGauss/om/script/ssh-keygen: /bin/bash^M: bad interpreter: No such file or directory /data1/zxb/openGauss/om/script/scp: /bin/bash^M: bad interpreter: No such file or directory ``` 这类错误更改下包格式: ```sh sed 's/^M//' file > tmp_filename;mv -f tmp_filename file sed -i 's/\r$//' file ``` ## **问题3:OM安装后,linux命令报错openssl不兼容** ### 问题描述 在部分系统中,使用 OM 安装完成 openGauss 数据库后,会出现例如 yum install 不可用, 或者 ssh 不可用的问题。 ### 问题现象 1. 在 openeuler20.03 系统上,使用 openGauss 3.0.3 之前的版本,OM 安装完成后,切换到 root 下使用 yum 安装组件,会出现如下错误: `symbol SSLv3_method version OPENSSL_1_1_0 not defined in file libssl.so.1.1 with link time reference`。 2. 在一些高版本系统中,如 centos8 以上。安装完成数据库后,使用 ssh 报错: ![image](figures/fig_installation_3_1.png) ### 问题定位 为了保证兼容和稳定,openGauss 在开源三方库里面引入了 openssl 组件进行管理和维护,这样依赖会导致 openGauss 使用的 openssl 版本和操作系统上自带 openssl 版本的可能存在不兼容的问题。 OM 安装完成后,会再 /etc/profile 里面写入自身的环境变量,如下: ```sh export GPHOME=/opt/huawei/install/om export UNPACKPATH=/opt/software/openGauss export PATH=$PATH:$GPHOME/script/gspylib/pssh/bin:$GPHOME/script export LD_LIBRARY_PATH=$GPHOME/script/gspylib/clib:$LD_LIBRARY_PATH export LD_LIBRARY_PATH=$GPHOME/lib:$LD_LIBRARY_PATH export PYTHONPATH=$GPHOME/lib export PATH=$PATH:/root/gauss_om/omm/script ``` 其中的LD\_LIBRARY\_PATH会将 openGauss 包中 lib 目录下的 so 库文件优先级提前,在使用如 yum 命令时候,就会优先去加载 openGauss lib 目录下的二级制。 而 openGauss lib 下放着 libssl.so 和 libcrypto.so ,这两个输入 openssl 的库文件。如果此时存在不兼容,那么在使用操作系统工具时候,如果工具依赖了 openssl 的相关不兼容函数,就会报错。 1. 编译选项不同导致不兼容 symbol SSLv3\_method 就是由于编译选项引起的不兼容现象。早起 openGauss-third-party 中的 openssl 在编译时候并未开启 sslv3-method,但是操作系统 yum 所依赖的二进制需要用到 sslv3 相关的函数,就导致报错 sslv3-method symbol not found。 2. 系统上对 openssl 做修改导致接口不兼容 在 Centos 8 以及相关的发行版中,操作系统自身对 openssl 做了很大的 patch 改动,其中存在对接口函数的增加和删除。 undefined symbol EVP\_KDF\_ctrl报错就是场景之一。 在原始的 openssl 中具有该函数,但是在 Centos8 系统上却对该函数做了删除。 此时安装了 openGauss 后,在 openGauss 的环境变量下,部分工具必然会出现问题。 ### 问题解决 1. 对于 symbol SSLv3\_method not found, 可以更新下三方库,在构建 openssl 的时候开启编译选项 enable-ssl3-method。 ![image](figures/fig_installation_3_2.png) 2. 对于 OM 安装过程中出现 undefined symbol EVP\_KDF\_ctrl 问题,可以把系统上的 libcrypto.so 放到 $TOOL/script/gspylib/clib 替换掉 om 包里面的 lib 文件。 3. 同意对于 OM 安装过程中出现问题的场景,由于 OM 需要依赖一些开源组件如 psutil,paramiko 等,这些组件编译的二进制文件依赖 openssl 进而产生了不兼容问题,可以在操作系统上手动安装如下四个组件: ```sh psutil netifaces cryptography paramiko ``` 然后 OM 安装时候, preinstall 加上 --unused-third-party 即可使用系统的组件替代 OM 包中的组件,进而规避该问题。 `./gs_preinstall -U xx -G xx -X /xx/single.xml --unused-third-party` 4. 对于在安装后,使用 ssh 工具出现 undefined symbol EVP\_KDF\_ctrl 问题的场景; 可以再在使用 ssh 之前, 把系统的 lib 库库优先级放到前面,就不会影响 ssh。 ```sh export LD_LABRRRY_PATH=/usr/lib64:$LD_LABRRRY_PATH;ssh ***.***.***.***00 command; ``` 这个问题由于系统自身对 openssl 做了修改,尤其在 Centos8 上, 删除 openssl 中的函数在 openGauss 中还继续使用,该兼容问题无法解决,只能通过加载环境变量的优先级方式来规避。 ## **问题4:preinstall出现pssh相关报错时的解决方法** ### 问题描述 \[GAUSS-51222] : Failed to check hostname mapping. Command: "pssh -s -H hostname1 hostname". Error: ![image](figures/fig_installation_4.png) ### 解决方法 当出现如上报错时,大概率是因为先前安装过数据库,环境变量存在一定的问题。Pssh的二进制文件保存在openGauss的安装包中链接如下: `script/gspylib/pssh/bin`。 当出现该问题时,大概率是系统原先就有pssh,或者是om安装出现了未知的bug导致没有正确关联环境变量。 此时我们只需要在root用户下关联环境变量即可,注意需要在所有主备环境下关联环境变量 `Vim /etc/profile` Export对应环境变量即可, 关联后发现正常preinstall。 ## **问题5:Yat使用安装** ### Yat使用安装 * 环境要求:Java 1.8+,Python 3.6+ * 下载yat: ```sh git clone https://gitee.com/opengauss/Yat/tree/master/yat-master cd Yat/yat-master chmod 755 gradlew ./gradlew pack ``` ![image](figures/fig_installation_5_1.png) ```sh cd Yat/yat-master/pkg ./install -F ``` ![image](figures/fig_installation_5_2.png) * 生成测试套:yat suite init -d exp-imp-lob ![image](figures/fig_installation_5_3.png) * 初始后的路径如下: ![image](figures/fig_installation_5_4.png) * 编辑conf/nodes.yml,配置测试库信息:数据库创建相关数据库及用户并赋权 ![image](figures/fig_installation_5_5.png) ![image](figures/fig_installation_5_6.png) /usr/local/yat创建lib目录,将驱动放进目录,将驱动设置为755 ![image](figures/fig_installation_5_7.png) * 拷贝社区相关用例到testcase: ![image](figures/fig_installation_5_8.png) * 拷贝社区相关用例的期望到expect: ![image](figures/fig_installation_5_9.png) * schedule目录下创建test1.schd,将用例编号放进去,sql用例不带后缀.sql ![image](figures/fig_installation_5_10.png) * 执行测试:两个用例通过,说明脚本跟期望是匹配的。 ![image](figures/fig_installation_5_11.png) ### 常见问题 #### 问题1:打包过慢问题:更换国内镜像网站 ![image](figures/fig_installation_5_12.png) `vim /data/guowb/Yat/yat-master/gradle/wrapper/gradle-wrapper.properties` ![image](figures/fig_installation_5_13.png) #### 问题2:./gradlew pack报错 ![image](figures/fig_installation_5_14.png) **解决方法:** 备份build.gradle.kts,然后删掉报错行。 ![image](figures/fig_installation_5_15.png) #### 问题3:初始化报错 ![image](figures/fig_installation_5_16.png) **解决方法:** ```sh ulimit -c unlimited chmod 777 corefile ``` ![image](figures/fig_installation_5_17.png) #### 问题4:执行过程中报用例名不合法 ![image](figures/fig_installation_5_18.png) **解决方法:** `vim conf/configure.yml`将下面一行放开注释。 ![image](figures/fig_installation_5_19.png) ## **问题6:安装时出现Could not create file : Invalid argument报错** ### 问题描述 ```sh creating template1 database in /home/opp/data2/base/1 ... 2024-05-09 06:15:10.730 [unknown] [unknown] localhost 548254040080 0[0:0#0] [BACKEND] WARNING: macAddr is 578/2886795268, sysidentifier is 37923857/316241, randomNum is 2360857425 2024-05-09 06:15:10.771 [unknown] [unknown] localhost 548254040080 0[0:0#0] [DBL_WRT] PANIC: Could not create file "global/pg_dw_meta": Invalid argument 2024-05-09 06:15:10.771 [unknown] [unknown] localhost 548254040080 0[0:0#0] [DBL_WRT] BACKTRACELOG: tid[758]'s backtrace: /home/ott/mppdb_temp_install/bin/gaussdb() [0x12c073c] /home/ott/mppdb_temp_install/bin/gaussdb(_Z9errfinishiz+0x334) [0x12b7470] /home/ott/mppdb_temp_install/bin/gaussdb(_Z14dw_create_filePKc+0xd4) [0x212c8b4] /home/ott/mppdb_temp_install/bin/gaussdb(_Z21dw_generate_meta_fileP21st_dw_batch_meta_file+0x20) [0x212af68] /home/ott/mppdb_temp_install/bin/gaussdb(_Z12dw_bootstrapv+0xb8) [0x212a6c4] /home/ott/mppdb_temp_install/bin/gaussdb(_Z13BootStrapXLOGv+0x16ec) [0x216bd44] /home/ott/mppdb_temp_install/bin/gaussdb(_Z20BootStrapProcessMainiPPc+0xae4) [0x143d14c] /home/ott/mppdb_temp_install/bin/gaussdb(main+0x5d4) [0x1a45a2c] /lib64/libc.so.6(__libc_start_main+0xe0) [0x7fa68bcf60] /home/ott/mppdb_temp_install/bin/gaussdb() [0xba53cc] Use addr2line to get pretty function name and line could not write to child process: Broken pipe ``` 安装时出现如下错误,主要报错信息为`Could not create file : Invalid argument` ### 问题根因 opengauss源码中,为了提升性能,在读写文件时,使用了IO\_DIRECT这一参数,主要功能为,不经过缓存直接通过IO操作读取文件,这里通过这个操作可以减少数据复制和减少内核态和用户态之间的上下文切换次数。 当使用了不支持O\_DIRECT的文件系统时,则无法进行数据库的初始化。 ### 解决方案 首先我们检测下文件系统是否支持O\_DIRECT,执行如下cpp编译的文件即可。 ```sh #include #include #include int main() { int fd = open("testfile", O_RDWR | O_DIRECT); if (fd == -1) { perror("not support"); return 1; } close(fd); printf("support"); return 0; } ``` > \[NOTE]说明 > > * 只要我们在当前磁盘下可以通过O\_DIRECT的方式打开文件,则证明该文件系统是支持。 > * 当不支持时,我们需要更换支持的磁盘目录,或者重新给磁盘安装支持O\_DIRECT的文件系统。 ## **问题7:安装后启动失败,报错缺少gs\_initdb,gaussdb;容器环境下报错illegal instruction时的解决方案** ### 背景描述 在使用官网提供的镜像安装数据库,有时会遇到一些 "非法指令" "illegal instruction" 的问题,或者在一些本地搭建的虚拟机上,数据库启动失败,但是没有很明确的错误信息的问题。 这些往往是由于 CPU 指令集不兼容导致的。 常见的有 3 种: 1. arm CPU 下的 lse 指令 2. x86\_64 CPU 下的 rdtscp 指令 3. x86\_64 CPU 下的 avx 指令 #### arm CPU 下的 lse 指令 官网发布的 openEuler\_arm 包,在编译的时候,打开了ARM\_LSE指令集做了编译的优化。但是对于一些其他 arm 服务器,不一定支持。 构建脚本: ```sh build\script\utils\make_compile.sh # it may be risk to enable 'ARM_LSE' for all ARM CPU, but we bid our CPUs are not elder than ARMv8.1 ``` 实测在 鲲鹏 920 和 麒麟 990 的 cpu 芯片下是支持安装的。 cpu 可以通过 lscpu 名称查看。 对于其他不自持该指令的系统,需要去掉 -D\_\_ARM\_LSE 指令重新编译即可。 在编译脚本中 build\script\utils\make\_compile.sh,删除掉所有的 -D\_\_ARM\_LSE , 重新打包数据库。 ```sh sh build.sh -m release -3rd /sdb/binarylibs -pkg # -3rd 是对应三方库二进制的目录 ``` patch 如下图: ![image](figures/fig_installation_7_1.png) #### x86 服务器下 rdtscp 指令 rdtscp 指令集用来检索 CPU 周期计数器,MOT 特性有用到 在 server 中位置如下: src\gausskernel\storage\mot\core\infra\synchronization\cycles.h ```sh /** * @brief Retrieve the CPU cycle counter using rdtscp instruction * @detail Force processor barrier and memory barrier * @return The CPU cycle counter value. */ static __inline __attribute__((always_inline)) uint64_t Rdtscp() { #if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) uint32_t low, high; __asm__ __volatile__("rdtscp" : "=a"(low), "=d"(high) : : "%rcx"); return (((uint64_t)high << 32) | low); #elif defined(__aarch64__) unsigned long cval = 0; asm volatile("isb; mrs %0, cntvct_el0" : "=r"(cval) : : "memory"); return cval; #else #error "Unsupported CPU architecture or compiler." #endif } ``` 有些自己搭建的虚拟机可能没有这个指令集,导致数据库无法启动。 **检测方法** 使用 lscpu 命令进行检测是否具有该指令集: `lscpu | grep rdtscp` **解决方法** 如果没有该指令集,需要开启 CPU 直通模式 (host-passthrough)。 #### x86 服务器下 avx 指令 avx 指令集用来进行加速计算,主要是 db4ai 在使用。该指令集从 2.1.0 版本开始引入,如果存在 2.1.0 之前版本可以运行数据库而 2.1.0 之后数据库启动失败,也有可能是没有该指令导致。 **检测方法** 使用 lscpu 命令进行检测是否具有该指令集: `lscpu | grep avx` **解决方法** 如果没有该指令集,从代码中删掉该指令集的引用,重新打包数据库。 该指令集的引用在 Makefile 里面,可以全局搜索 -mavx , 删掉如下编译选项里面加载-mavx 指令,然后重新打包构建即可。 ```sh ifeq ($(PLATFORM_ARCH),x86_64) override CPPFLAGS += -mavx endif ``` ## **问题8:安装时出现路径冲突的解决方法** ### 问题描述 安装opengauss在preinstall阶段会出现如下问题 The /usr2/test/om/install already exists. Please remove it. It should be a symbolic link to $GAUSSHOME if it exists ![image](figures/fig_installation_8_1.png) ### 问题定位 脚本在检测文件是否存在时,检测的不是最终的目录,而是第二层的目录,因此预安装前应确保第二层目录是不存在的才可以正常安装。 ### 解决方案 此时我们发现/usr2/test/om是不存在的,但是/usr2/test是存在的。 当我们删除/usr2/test后,再执行则不报错,安装成功。 ## **问题9:镜像获取错误** ### 问题描述 preinstall预安装报错某个so文件不存在,但是实际该文件是存在的。 ![image](figures/fig_installation_9_1.png) ![image](figures/fig_installation_9_2.png) ### 解决方案 这种问题是由于取错了架构的包导致,可以通过 file 查看文件的架构,和 `uname -p` 核对系统架构是否匹配。(新版本OM增加了对架构的校验) ![image](figures/fig_installation_9_3.png) ## **问题10:Python版本不匹配导致安装卡住** ### 问题描述 系统上的python版本和OM需要的版本不匹配时候报错甚至preinstall执行会卡住。 ![image](figures/fig_installation_10_1.png) ![image](figures/fig_installation_10_2.png) ### 问题定位 根本原因在于OM所依赖的三方库,强绑定了python版本,进而导致om对python版本强依赖。 ![image](figures/fig_installation_10_3.png) | 操作系统 | Python版本 | |----------------|------------| | Centos7.6 | 3.6 | | openEuler20.03 | 3.7 | | openEuler22.03 | 3.9 | | openEuler24.03 | 3.11 | ### 问题解决 6.0.0之后,OM支持多种不同的python版本,可以解决该问题,其实也是对所依赖的三方库在不通的python下构建二进制,按需获取。 ![image](figures/fig_installation_10_4.png) 此外preinstall也提供了一种方式,可以选择用系统自带的依赖,可以做到任意版本都能兼容。 `./gs_preinstall -U omm -G omm -X single.xml --unused-third-party` \*\*前提:\*\*系统使用pip install如下组件: * psutil * netifaces * cryptography * paramiko ## **问题11:建立互信失败** ### 问题定位 互信可以让节点之间免密进行ssh scp,安装过程需要root和omm用户互信,通过在本节点发起命令在其他主备节点执行。 建立互信失败往往是系统层面配置的相关问题导致,排查时候可以检查sshd服务状态,以及排查系统日志。 `systemctl status sshd -l; /var/log/message` ![image](figures/fig_installation_11_1.png) ![image](figures/fig_installation_11_2.png) 常见的是目录权限被随意更改,权限有严格要求,不是越大越好。此外需要排查下关闭selinux相关配置: ```sh setenforce 0 sed -i '/^SELINUX=/c'SELINUX=disabled /etc/selinux/config ``` ## **问题12:系统兼容适配** ### 问题描述 OM安装对于其他一些系统出现安装不支持的问题。 ![image](figures/fig_installation_12_1.png) ### 解决方案 社区发布的镜像可以适配安装系统: | 系统版本 | 架构 | 发行版 | |---------------- |------------|------------| | Centos7 | X86 |红旗Asianux 7| | openEuler | X86+ARM |麒麟v10、UOS、FUSIONOS、UNIONTECH| OM做过适配,可以直接使用社区的包来在这些系统进行安装: ![image](figures/fig_installation_12_2.png) 对于其他的系统,只要是基于centos7或者openEuler的发行版,可以经过很简单的适配就能使用社区镜像安装。 1. 修改系统的 /etc/os-release相关文件为已适配的系统,通过OM校验。 2. 修改OM代码,增加一个系统适配: [PR-675](https://gitee.com/opengauss/openGauss-OM/pulls/675/files) \*\*系统选择:\*\*遇到用户使用一个新的系统,应该选择社区哪个镜像? 主要关注操作系统的内核版本(uname -a),和社区发行的是否匹配。 ![image](figures/fig_installation_12_3.png) | 社区发布镜像 | 匹配系统内核版本 | |----------------|----------------| | Centos 7 | 3.10 | | openEuler2003 | 4.19 | | openEuler2203 | 5.10 | ## **问题13:gs\_install校验失败** ### 问题描述 在gs\_install的第一步, CheckPreInstall.py失败。 ![image](figures/fig_installation_13_1.png) ### 解决方案 CheckPreInstall.py gs\_install的第一步检查preinstall是否完成。原理是检查环境变量里面GAUSS\_ENV的值: `1 - preinstall结束 2 - install完成`。 对于CheckPreInstall失败,主要检查两点: 1. omm用户的互信是否正常。 2. 各个节点环境变量里面 GAUSS\_ENV得值是否为1。 ## **问题14:启动失败-内存信号量不足** ### 问题描述 内存较小的机器,启动出现申请信号量不足的报错。 ![image](figures/fig_installation_14_1.png) ### 解决方案 在调用系统semget申请共享内存时候,资源不足导致。 1. 排查系统空闲内存和配置的shared\_buffer大小,可以适当调小shared\_buffer或者清理释放下系统内存。 2. 调整系统的shm配置。 ![image](figures/fig_installation_14_2.png) > \[NOTE]说明 > > * kernel.sem配置第二个参数过小会导致该问题。 > * kernel.shmall和shmmak配置过小也会导致问题。 ## **问题15:启动失败-指令集** ### 问题定位 gs\_install最后一步启动数据库,在启动时候报`gaussdb coredump,illegal instruction`等错误,往往是一些指令集引起启动失败。常见有三种: 1. ARM下LSE指令 LSE扩展指令集在armv8.1以上cpu才具有,社区构建包基于鲲鹏920,支持lse指令集并且也在社区发布的镜像带上了该指令集的优化。鲲鹏 920 和 麒麟 990 的 cpu 芯片下是支持安装的。 对于客户使用如飞腾2000的cpu,不支持该指令集,会导致coredump。 需要在构建脚本,去掉 -D\_\_ARM\_LSE指令集重新构建包。 ![image](figures/fig_installation_15_1.png) 2. x86下rdtscp指令 rdtscp用于时钟计算,目前仅MOT功能有使用到。系统没有该指令集也会导致启动coredump掉。解析core文件可以看到执行到该函数报错。 ![image](figures/fig_installation_15_2.png) 一般对于虚拟机常见该问题,可以开启CPU直通模式解决。 3. x86下avx指令集 avx指令集用于加速计算,AI功能有用到,从2.1.0版本开始引入。出现coredump问题也可以关注下是否有该指令集。也可以去掉该指令集后重新构建进行可用。 ![image](figures/fig_installation_15_3.png) ## **问题16:MOT引起启动失败** ### 问题描述 数据库在启动时候,会进行MOT一些初始化操作,即便MOT关掉也会执行这些操作,MOT初始化失败也会导致数据库启动失败。常见有两种情况: 1. rdtscp指令集不存在 2. Numa节点分布不均匀 ### 解决方案 lscpu可以查看NUMA节点分配情况,如下图是4个numa节点,每个有32核,分布是均匀的。 ![image](figures/fig_installation_16_1.png) 如果对于其他机器,这里面分配不均匀,如node0 32核,node1分配20核,那就会导致mot启动失败进而引起数据库启动不成功。 构建包时候,去掉mot功能。 `--disable-mot` ## **问题17:AZName和优先级引发cm启动失败** ### 问题定位 azname用来划分集群中的节点为哪个数据中心,azpriority对应优先级。 CM要求azname和优先级必须匹配,且不同的azname需要具有不同的az优先级,否则cm启动会一直报错。 表现也有可能为 cms虽然正常,但是cms主一直在发生切换(cms一直在重启) ### 解决方案 使用命令检查az配置情况: cm\_ctl view | grep az 确保不同的az具备不同的优先级。 ![image](figures/fig_installation_17_1.png) ## **问题18:主备建联失败** ### 问题描述 主备节点的通信端口未放开,安装在主备建联阶段失败。 主备安装最后步骤中,主备各个节点启动后,备机会做build建立主备关系操作。当需要的端口没有放开会导致build卡主或者失败。 ### 解决方案 1. 关闭防火墙 `systemctl stop firewalld` 2. 关闭iptables `iptables -F` 3. 关闭selinux `sed -i '/^SELINUX=/c'SELINUX=disabled /etc/selinux/config` ## **问题19:麒麟系统OM安装报错openssl不兼容** ### 问题描述 修复在麒麟系统升级openssh后,出现系统ssh和数据库libcrypto.so不兼容导致om无法使用的问题。 ### 根因分析 #### 问题现象 在麒麟v10-sp2 arm环境,由于修复安全漏洞,升级了openssh,导致系统上ssh命令无法使用,报错如下: ![image](figures/fig_installation_18_1.png) #### 规避和处理措施 在om的script目录下,创建ssh/scp/ssh-add/ssh-kengen/ssh-copy-id文件,里面添加如下脚本: 比如scp: ```bash #!/bin/bash export LD_LIBRARY_PATH=/usr/lib64 && /usr/bin/scp $@ ``` ssh: ```bash #!/bin/bash export LD_LIBRARY_PATH=/usr/lib64 && /usr/bin/ssh $@ ``` 在script下面创建复写ssh等文件,里面指定使用系统的lib库路径:参考修复[pr](https://gitee.com/opengauss/openGauss-OM/pulls/635/files) 。 #### 原因分析 1. openGauss自身引入libcrypto.so 组件 openGauss强依赖openssl开源组件,固定了该组件的版本(1.1.1n),并基于该版本源码编译了。 openssl,将编译的产物动态库(libssl.so.1.1 libcrypto.so.1.1) 打包到数据库的安装包里面。在安装时候会解压到 `$GAUSSHOME/lib` 下。 操作系统本身也有这两个文件(/usr/lib64 目录下),为了避免冲突,openGauss安装时候,通过设置环境变量的方式去加载这两个动态库。在omm用户下,`$GAUSSHOME/lib` 的优先级是要高于系统的。 因此会在omm的 `.bashrc` 里面写入下面的环境变量来保证优先级。 `export LD_LIBRARY_PATH=$GAUSSHOME/lib:$LD_LIBRARY_PATH` ![image](figures/fig_installation_18_2.png) 使用ldd命令可以看到,gaussdb必须加载自带的 `libcrypto.so.1.1`。 2. ssh在升级后,依赖系统的libcrypto.so ![image](figures/fig_installation_18_3.png) 但是在omm下,优先加载了openGauss的环境,导致ssh去依赖openGauss的libcrypto.so库,可以看到,此时已经提示系统的ssh和openGauss的libcrypto.so已经不兼容了。 ![image](figures/fig_installation_18_4.png) 最根本原因是由于,系统升级补丁后,新版本的openssl库和openGauss自身的不能兼容。 使用ldd分别看看系统升级后的libcrypto.so和openGauss lib下的,存在不兼容的接口: ![image](figures/fig_installation_18_5.png) ![image](figures/fig_installation_18_6.png) #### 修复方案 考虑几个修复方案: 1. 数据库升级openssl,加上1\_1\_1\_f和系统兼容 --- 但是假如后面存在升级补丁到其他openssh版本怎么办?数据库没法和系统保证同步升级。 2. 复写 ssh 到环境变量会不会有效果? `alias ssh='LD_LIBRARY_PATH=/usr/lib64/&&/usr/bin/ssh'`--- 这个只能执行一次,就会修改环境变量,导致数据库的不可用。 3. 把ssh打包到om包里面,后面只依赖自己包里面的ssh。 --- openGauss只发布openEuler-arm,上面的`openssh=7.8`,而像麒麟v10,`openssh=8.2`,也有不兼容现象。 4. OM里面ssh强依赖系统的,加载时候主动去导入系统的路径`LD_LIBRARY_PATH=/usr/lib64`。 **实现方案** 使用方案4:OM里面ssh强依赖系统的,加载时候主动去导入系统的路径。 主要涉及两处修改: 1. om里面的ssh强制指定系统,并加载系统依赖 `LD_LIBRARY_PATH=/usr/lib64`。 包括 `ssh scp ssh-agent ssh-add ssh-copy-id`。 2. 解决了om工具后,在omm下直接使用ssh也会报错:复写ssh工具到omm的环境变量路径下。 比如ssh工具 ```bash #!/bin/bash ########################################################################## ### # Copyright (c): 2021-2025, Huawei Tech. Co., Ltd. # FileName : ssh # Date : 2023-12-09 ########################################################################## ### export LD_LIBRARY_PATH=/usr/lib64 && /usr/bin/ssh $@ ``` 这样,如果不加载om的环境变量,则默认使用系统的ssh。如果加载了om环境变量,则使用系统ssh前导入系统的lib路径。保证手动使用ssh也可行。 [关联需求或issue](https://gitee.com/opengauss/openGauss-server/issues/I8MCW0?from=project-issue) --- --- url: /zh/docs/common/faq/faq.md --- # 常见问题 ## 1. openGauss 数据库开源许可协议是什么? 木兰宽松许可证 MulanPSL2 V2,无传染。 ## 2. openGauss 支持部署的硬件架构及操作系统有哪些? ARM:openEuler 20.03LTS(推荐采用此操作系统)| openEuler 22.03LTS | Kylin-V10 | FusionOS 22 |统信 X86:openEuler 20.03LTS | openEuler 22.03LTS | Kylin-V10 | CentOS 7.6 | Asianux 7.6 | FusionOS 22 |统信 ubuntu / centos8 /centos10 / 红旗需要适配编译数据库;在飞腾/海光等服务器上安装需要重新适配编译。 ## 3. openGauss 有哪些版本? openGauss 社区每两年发布一个 LTS 版本,LTS 版本作为长期支持版本,可规模上线使用。半年发布一个创新版本,创新版本供用户联创测试使用;涉及重大问题修复时,会按需发布补丁版本。同时按照不同场景分为以下版本: * openGauss 企业版:具备更齐全的集群管理功能,适合企业用户; * openGauss 极简版:安装配置简单,解压可用,适合个人开发者; * openGauss 轻量版:精简功能,缩减安装包大小,内存占用更少; * openGauss 分布式镜像:基于 ShardingSphere 和 k8s 的分布式容器化镜像。 详情参考 openGauss 官网“学习”->“文档”区域。 ## 4. openGauss 分布式部署方案是什么? * 基于 openLookeng 实现分布式分析能力,与 shardingsphere 配合 openGauss 组成 HTAP 数据库; * 基于分布式中间件 shardingsphere 使 openGauss 具备分布式数据库能力; * 使用 kubernetes 部署分布式数据库。 更多分布式部署方案请参考 openGauss 官网“学习”->“文档”区域。 ## 5. openGauss 支持的连接方式有哪些? * 连接方式有 JDBC / ODBC 以及其它语言的驱动; * 连接客户端工具 Data Studio 、Dbeaver、Navicat,可以参考官网“下载”->"支持工具"区域;同时 DataKit 的 WebDS 也支持客户端连接, 在官网“下载”->版本包 里,下载 DataKit 即可。 ## 6. openGauss 迁移方案有哪些? * openGauss 社区版本支持 MySQL 迁移,提供全量的迁移工具集,可在官网 “下载”->版本包,openGauss Tools 里下载;操作可参考 openGauss 社区官网“社区”->“迁移专区”; * openGauss DBV 的商业发行版支持常见数据库的迁移工具。 ## 7. openGauss 支持的生态工具有哪些? 参考官网“下载”->“支持工具”区域。 ## 8. openGauss 行业应用实践有哪些? 详细案例参考官网“社区”->“用户实践”版块。 openGauss 已经在包括金融、电信、政府、制造、能源、交通、医疗、教育等行业规模应用。 ## 9. 如何加入 openGauss 社区? 参考 openGauss 官网“社区”->“社区贡献”->“签署 CLA” 个人和企业分别通过签署个人/企业 CLA(贡献者许可协议)加入 openGauss 社区。 ## 10. openGauss 相关问题学习及咨询渠道有哪些? 学习渠道:openGauss 官网文档、openGauss 的 B 站视频、openGauss 视频号视频、openGauss 技术交流微信群。 咨询渠道:社区邮件列表->官网“社区”->“线上交流”版块,订阅对应 SIG 组邮件列表,咨询交流。 更多问题请添加社区微信小助手:openGauss-bot ## 11. cm 的基本命令 查询集群状态:cm\_ctl query -Civdp |停止集群:cm\_ctl stop |启动集群:cm\_ctl start |指定节点切换为主机:cm\_ctl switchover -n 2 -D dn1 |重建备机:cm\_ctl build -n 2 -D dn1 ## 12. cm 的命令在集群中任意节点执行都可以吗? cm 的命令可以远程执行,所以通常在任意节点均可执行,执行方式主要由两种: * 依赖节点间互信由 cm\_ctl 工具直接远程执行; * 将待执行指令发送给 cms 主,再由 cms 主下发到对应节点的 cma。因此只要互信和网络没有问题在集群中任意节点均可执行。 ## 13. openGauss 5.0.0 集群同步是否支持 v6 地址? 暂时只有 server 支持 ipv6, om cm 暂时不支持。 ## 14. 主从复制能指定用户吗?现在都是用的初始化用户,能否指定一个只有复制权限的用户,主备间数据同步能否指定用户 主备之间的数据复制固定是初始用户,无法指定。 ## 15. 安装前能否通过配置,默认指定字符集为 utf8,这样就不用在建库的时候指定了 gs\_install安装时指定--gsinit-parameter参数,完整命令为: `gs_install -X /home/guowb/single.xml --gsinit-parameter=""--locale=zh_CN.utf8 --encoding=UTF-8""`,创建后默认库为 utf8,创建新库 create database test1;不指定 encoding,字符集也为 utf8 ## 16. 归档和备份恢复区别和关系 归档:归档功能默认只是简单的备份 xlog 日志。 增量备份:是一个连续性的链式的行为,有一个基础的全量备份,在此基础上可以每隔一段时间就进行一次增量备份,每一次的增量备份都是在前一次的备份基础上的增量,也就是差分增量,通常是间隔固定时间增量备份一次,这样基础的全量备份和多次的增量备份就可以形成一个备份链,比如叫 A-->B-->C-->D,每个位置都会记录它的时间、lsn、xid、备份名,那么当你要恢复的时候就会根据你所要恢复到的位置去找最近的备份点,在这个备份点的基础上进行恢复,比如你要恢复到 C 和 D 之间的某个位置,那就基于 C 进行增量恢复,只需要回放 C 到你要恢复的位置之间的 xlog 即可,这样就不需要从 A 开始回放,可以大大的降低恢复的时间。另外 probackup 有很多备份管理功能,比如清理、合并等这些都是归档所不具备的。另外备份恢复的 pitr 恢复功能是需要借助归档功能来备份增量的 xlog 的。 ## 17. xlog 文件堆积可能有哪些原因 * 存在异常备机; * 存在非活跃的逻辑或物理复制槽; * 开启了归档,但是由于某些原因导致归档受阻; * 备份失败; * Xlog 回收速率慢于日志产生速度; * Xlog 相关参数配置不合理,与 xlog 保留数量相关的参数包括wal\_keep\_segments、checkpoint\_segments,集群状态正常的情况下最多有 wal\_keep\_segments + checkpoint\_segments \* 2 + 1 个。 ## 18. 根据 core 文件解析 core 堆栈步骤 * 官网下载版本、系统、架构匹配的符号表; * 将下载的符号表压缩包上传到环境,解压,将symbol/lib/和symbol/bin/目录下的所有内容拷贝到对应的$GAUSSHOME/lib和$GAUSSHOME/bin目录下,并保证权限正确; * 找到 core 文件目录,解压 core 文件,lz4 -d 文件名; * gdb gaussdb 解压后的 core 文件名(如果是其他的进程 core 了,gaussdb 替换为其他的二进制名称); * bt 查看 core 堆栈。 ## 19. 数据库启动报错回显信息为 waitpid xxx failed 由于数据库异常终止,gaussdb.state 文件错误,将数据目录下 gaussdb.state 文件删掉重新启动即可。 ## 20. 常见数据库场景下文件句柄数设置不足,导致数据库状态异常怎么处理 查看数据库日志数据库报错为PANIC:could not open file "pg\_xlog\*\*\*\*\*",系统文件句柄数设置不够,查看 ulimit -n 为 1024,建议参考官方安装文档,设置为 100w,重启系统后在启动数据库。 --- --- url: /zh/docs/common/contribute/contribution_process.md --- # 快速入门 ## 概述 openGauss 文档采用 Markdown 格式编写,通过 Git 进行版本控制,并托管在 Gitee 平台。文档修改通过 Pull Request(PR)工作流进行审核与合并。openGauss 文档存放在 openGauss/docs 仓,由 doc SIG 负责维护。 ## 快速开始 下面介绍文档开发流程。 1. Fork openGauss/docs 仓库。 访问 [Repository 首页](https://gitcode.com/opengauss/docs)。点击右上角的**Fork**按钮,按照指引,创建个人的云上 fork 仓库。 ![image](figures/forkdocs.png) 2. 克隆 openGauss/docs 仓库。 克隆 fork 仓库到本地,并关联本地与远程仓库。 ```bash git clone https://gitcode.com/{your_org}/docs.git cd docs git remote add upstream https://gitcode.com/opengauss/docs.git git fetch upstream ``` 3. 切换分支。 依据所需修改文档的版本,切换到对应的分支。此处以latest版本为例。 ```bash git checkout -b work upstream/master ``` 4. 按需更新文档。若新增文档文件,需维护[`_toc.yaml`目录配置文件](./directory_structure_introductory.md#目录配置文件格式_tocyaml)。 5. 提交变更并推送到远程仓库。 ```bash git add . git commit -m "提交原因" git push origin work ``` 6. 创建PR。 在个人文档仓库的 Pull Requests 页面 `https://gitcode.com/{your_org}/docs/pulls`,点击**新建Pull Request**创建PR。源分支选择 `{your_org}/docs/work`,目的分支选择 `openGauss/docs/master`。填写 PR 标题并简要说明修改内容,点击**创建Pull Request**。 7. 合入PR。 合入条件:文档流水线门禁通过,CLA 已签署,Issue 已关联,doc SIG maintainer 检视通过。 ![image](figures/approve.png) --- --- url: /zh/docs/common/faq/sql.md --- # 慢sql问题 常见问题与解决方法 ## **问题1:localsyscache不足偶发慢sql** ### 问题现象 某个sql正常执行小于10ms,但是在每天偶发会出现数次执行耗时超过1s。 statment\_history里面开启L1记录执行计划,发现出现慢sql时刻也是走了索引,和正常的执行计划一致。 ![image](figures/fig_sql_2_2.png) 在发生慢sql后,使用 `explain analyze ` 加上真实数据执行,实际耗时1ms以内: ![image](figures/fig_sql_2_6.png) 分析statment\_history信息,该sql执行耗时超过1s,比较突出的是访问到的 tuples和blocks数量很大,而从上面的explain里面看,不应该访问到这么多元祖; lock\_count和lock\_time较大。从这几类time来看,plan\_time占比最高。 ![image](figures/fig_sql_2_3.png) ![image](figures/fig_sql_2_4.png) 排查死元祖情况,该表只有3万多行,pg\_stat\_user\_tables查询该表死元祖很少,没达到触发autovacuum阈值条件,也可以排查访问了很多页不可见的页面碎片导致。 ![image](figures/fig_sql_2_5.png) ### 问题原因 对于耗时主要集中在plan\_time上,后面通过脚本在遇到慢sql时候打印堆栈(gs\_stack(pid)),发现问题出现在localsyscahce的清理上面。 因此在排查gs\_session\_memory\_detail视图,发现数据库 local cache 的usedsize达到了31M+(local\_syscache\_theshold为32M),通过打印数据堆栈确实发现因local cache不足触发了清理缓存的动作,该库涉及的数据库表分区较多(74个),因数据库问题(清理分区cache时性能存在问题)导致分区表的cache清理较慢,sql涉及跨分区查询需等待分区cache清理完毕,进而导致出现慢SQL,最终导致交易超时。 ### 问题处理 开启gloablsyscache,或者增加 local\_syscache\_threshold,能够覆盖会话使用。 ## **问题2:存储过程中第二条查询执行慢的问题** ### 问题描述 源表过滤出6800万数据然后聚合插入到目标表,第一次性能正常,第二次性能下降。总结通用问题现象为一个存储过程里包含两个查询,查询单独拿出来都跑得很快,但是若执行存储过程,总是前面的查询跑得快,后面的查询会很慢,交换两个查询的位置也是如此,存储过程如下: ![image](figures/fig_sql_3_1.png) ### 问题定位 获取存储过程中这两个查询的执行计划 ```sh set enable_auto_explain=on; set auto_explain_level=notice; ``` 执行存储过程,日志查看: ![image](figures/fig_sql_3_2.png) ![image](figures/fig_sql_3_3.png) 第一个执行计划中有并行线程间实现数据交换的stream算子,可见第一个查询走了SMP并行查询,但是第二个查询没有,因此第一个查询快而第二个查询慢。 ### 问题原因总结 根据issue中的用例跟踪代码可发现,在存储过程中执行第二条SQL时,在 pgxc\_planner 处会执行 set\_default\_stream,判断能否支持SMP,此时和第一次执行SQL不同之处在于 u\_sess->stream\_cxt.global\_obj 不为NULL,导致u\_sess->opt\_cxt.is\_stream为false,后续无法使用SMP。 ![image](figures/fig_sql_3_4.png) ### 规避&处理措施 \*\*规避措施:\*\*历史版本,存储过程中的语句不支持SMP并行执行,实际存储过程中的第一条语句会走并行,此类问题可以写成两个存储过程 \*\*处理措施:\*\*在spi执行结束时的 \_SPI\_end\_call处增加释放SMP group的逻辑。同时为了不释放外层的SMP,在smp里面新增变量记录SPI的\_connected数量,当前smp对应的\_connected必须大于等于 spi的\_connected才能释放。详见:[pr](https://gitcode.com/opengauss/openGauss-server/pull/7757) ## **问题3:freeze引发sql超时故障分析** ### 问题描述 某个业务出现2次sql查询慢的情况(正常耗时<1min,异常时刻查询5小时未结束(表数据100w行左右))。同样的业务有多套集群,两次问题发生在不同的集群上。对表做analyze后恢复。此外近期也出现几次其他业务sql超时。 ### 问题定位 1. 5小时未执行完sql,对比和正常的执行计划有差异。正常情况走的hashjoin,而慢sql时刻走的mergejoin。 异常sql执行计划: ![image](figures/fig_sql_4_2.png) 异常时刻走了mergejoin,mergejoin要求有序,200w行数据联表的seqscan + sort,导致等待事件全部在sort上面,也是耗时长的原因。 2. 查看表的统计信息更新情况(pg\_stat\_user\_tables) 最近两次出异常的表,上次的更新统计时间在上个月。(该表属于按日进行的分表,前一天会truncate清理数据,在当日会有大量的业务进来)。 按照autoanalyze的配置,当日应该会触发自动analyze(阈值0.02)。但是从早上到下午都没有触发autoanalyze更新。 ![image](figures/fig_sql_4_3.png) ![image](figures/fig_sql_4_4.png) 3. 自动清理说明 `autovacuum_mode=fix` 配置在做 vacuum 时候也会触发 analyze `autovacuum_naptime=20s` 配置每20s轮训一次是否需要做 `vacuum|anlayze` `autovacuum_analyze_scale_factor=0.02` 配置当变更的元祖数(增删改)超过总行书的2%,就会出发自动analyze。 检查上述配置没问题,那么autovacuum清理受到了阻塞。 4. 查看autovacuum线程 `Select query from pg_stat_activity where query ~ ‘vacuum’;` ![image](figures/fig_sql_4_5.png) `autovacuum_max_workers=10` 即只有10个autovacuum清理的工作线程。 但是从视图查询出来看,发现这10个worker线程被占满了,都在做 freeze 操作,导致资源倾斜,影响了正常业务的analyze。 5. Freeze是为了避免事务回卷,主动对老表的xid进行更新的操作。 Freeze操作将xmin标记为2,表明对所有事务都可见,同时进行清理clog文件。 ![image](figures/fig_sql_4_6.png) ![image](figures/fig_sql_4_7.png) 6. 查询是否满足触发freeze。 查询当前xid:`select txid_current();` ![image](figures/fig_sql_4_8.png)\ 查询数据库frozenxid: `select datname,datfrozenxid64 from pg_database;` ![image](figures/fig_sql_4_9.png)\ Autovacuum触发freeze的xid配置:autovacuum\_freeze\_max\_age 该集群配置400亿。 可以看到,最新xid 454亿,业务表的最小frozenxid=40亿,差值超过了400亿,满足触发freeze条件。 7. 该系统最大的特点是表+分区+toast表很多,导致freeze需要做很长的时间才能完成。 排查范围 4-55亿是当前触发freeze的表数量,还有2w张待做。其他范围也有很多表即将满足触发条件。 select count(\*) from pg\_class where relfrozenxid64::text::bigint between 4 and 5500000000; | Xid 范围 | 表数量 | | :--- | ---: | | 4 - 55亿 | 23404 | | 55亿 - 100亿 | 13029 | | 100亿 - 200亿 | 4565 | | 200亿 - 300亿 | 50126 | ### 问题原因 由于数据库触发了freeze机制,需要对大量的表做freeze推进xid,将10个worker全部占满,导致资源倾斜,影响了正常表的清理,进而引发多次sql超时现象。 ### 规避&处理措施 \*\*规避措施:\*\*Freeze属于数据库的正常行为,有几个方案可以优化下进度: 1. 增加autovacuum\_max\_workers个数(改配置需要重启) 当前只有10个在处理,但是考虑到XX的表多,而且主机的负载不是很高,可以考虑增加worker个数(20 - 30个),提升freeze速度。 2. 增加autovacuum\_freeze\_max\_age延迟清理(改配置需要重启) autovacuum\_freeze\_max\_age目前是400亿,即最新事务id(当前450亿) 和表的xid差距超过400亿才会触发freeze。 将改配置调大,可以将清理往后面拖延,增加清理触发的周期。 \*\*处理措施:\*\*针对影响业务查询的表,每天定时做vacum analyze更新统计信息,避免影响sql耗时。 ## **问题4:union 语句谓词不下推故障分析** ### 问题描述&问题定位 业务存在慢sql,sql较长,截取主要耗时的子查询与对应执行计划如下: 1. 观察openGauss的执行耗时,发现主要的耗时在union两端子句的join上: ![image](figures/fig_sql_6_1.png) 执行计划: ![image](figures/fig_sql_6_2.png) 2. 分析一段子句的执行计划,该子句也是由一个join构成。扫描trn在过滤条件下扫出了90万行,因此后续采用nestloop join也要循环90万次以上。另一端子句同理。并且我们发现sql本身在外层有对trn表的谓词过滤,因此可以确定性能的瓶颈点在于谓词没有下推给union两端的子句。 3. 分析oracle的执行计划来验证我们的结论 ![image](figures/fig_sql_6_3.png) 首先我们发现oracle有明显的谓词下推关键词 我们聚焦21行与27行,这两行为union两端子句扫描trn表的行,其对应的过滤条件如下: ![image](figures/fig_sql_6_4.png)\ 我们发现在oracle中,已经将对应的谓词下推(t.objinr = p.objinr),而其中t表已经做过了一轮过滤,所以union两端的时间会大大缩减,后续所有的操作都会因为join一端结果获取行数的大幅度减小而缩短时间。 4. 至此得出结论,openGauss在此种场景下不支持谓词下推。 ### 问题原因 谓词下推为oracle本身自己做的特性,openGauss与postgres均没有该特性 构造最小化复现用例(参考Oracle官网对该特性描述的sql) ```sh select prod.* from PROMOTIONS prod join ( select p.PROD_ID,AMOUNT_SOLD,s.PROMO_ID from sales s, PRODUCTS p where s.prod_id = p.prod_id union select p.PROD_ID,UNIT_PRICE,c.PROMO_ID from COSTS c, PRODUCTS p where c.prod_id = p.prod_id) V on prod.PROMO_ID=v.PROMO_ID and prod.prod_id = 'P8289'; ``` 考虑上述sql,如果存在谓词下推,那么外表prod会根据prod\_id = ‘P8289’先进行一轮过滤,过滤后的表prod.PROMO\_ID = v.PROMO\_ID这个谓词条件会下推至V中union两端的子句,相当于添加了条件s.PROMO\_ID in (select PROMO\_ID from PROMOTIONS where prod\_id = 'P8289') 因此效率得以提升。 在oracle中执行该语句: ![image](figures/fig_sql_6_5.png) 可以看到9与13发生了谓词下推。 在openGauss中做如下实验: 1. 执行sql: ```sh select prod.* from PROMOTIONS prod join ( select p.PROD_ID,AMOUNT_SOLD,s.PROMO_ID from sales s, PRODUCTS p where s.prod_id = p.prod_id union select p.PROD_ID,UNIT_PRICE,c.PROMO_ID from COSTS c, PRODUCTS p where c.prod_id = p.prod_id) V on prod.PROMO_ID=v.PROMO_ID and prod.prod_id = 'P8289'; ``` 耗时如下: ![image](figures/fig_sql_6_6.png) 2. 执行手动进行谓词下推的sql: ```sh select prod.* from PROMOTIONS prod join ( select p.PROD_ID,AMOUNT_SOLD,s.PROMO_ID from sales s, PRODUCTS p where s.prod_id = p.prod_id and s.PROMO_ID in (select PROMO_ID from PROMOTIONS where prod_id = 'P8289') union select p.PROD_ID,UNIT_PRICE,c.PROMO_ID from COSTS c, PRODUCTS p where c.prod_id = p.prod_id and c.PROMO_ID in (select PROMO_ID from PROMOTIONS where prod_id = 'P8289')) V on prod.PROMO_ID=v.PROMO_ID and prod.prod_id = 'P8289'; ``` ![image](figures/fig_sql_6_7.png) 因此手动谓词下推是有效的。 用例构造: ````sh -- 创建 PROMOTIONS 表 CREATE TABLE PROMOTIONS (     PROMO_ID INT PRIMARY KEY,     PROD_ID VARCHAR(50),     PROMO_NAME VARCHAR(100) ); -- 创建 SALES 表 CREATE TABLE SALES (     PROD_ID VARCHAR(50),     AMOUNT_SOLD INT,     PROMO_ID INT ); -- 创建 COSTS 表 CREATE TABLE COSTS (     PROD_ID VARCHAR(50),     UNIT_PRICE DECIMAL(10, 2),     PROMO_ID INT ); -- 创建 PRODUCTS 表 CREATE TABLE PRODUCTS (     PROD_ID VARCHAR(50) PRIMARY KEY,     PROD_NAME VARCHAR(100),     CATEGORY VARCHAR(50),     DESCRIPTION varchar(50) ); create index idx1 on PROMOTIONS(PROD_ID); create index idx2 on SALES(PROD_ID); create index idx3 on SALES(PROMO_ID); create index idx4 on COSTS(PROD_ID); create index idx5 on COSTS(PROMO_ID); CREATE OR REPLACE PROCEDURE GenerateData(IN numRows INT) LANGUAGE plpgsql AS $$ DECLARE     i INT := 0; BEGIN     -- 生成 PRODUCTS 数据     WHILE i < numRows LOOP         INSERT INTO PRODUCTS (PROD_ID, PROD_NAME, CATEGORY, DESCRIPTION)         VALUES (CONCAT('P', i), CONCAT('Product ', i), 'Category ' || (i % 5), 'Description for product ' || (i % 10));         i := i + 1;     END LOOP;     i := 0;     -- 生成 PROMOTIONS 数据     WHILE i < numRows LOOP         INSERT INTO PROMOTIONS (PROMO_ID, PROD_ID, PROMO_NAME)         VALUES (i, CONCAT('P', FLOOR(RANDOM() * numRows)), CONCAT('Promotion ', i));         i := i + 1;     END LOOP;   i := 0;     -- 生成 SALES 数据     WHILE i < numRows LOOP         INSERT INTO SALES (PROD_ID, AMOUNT_SOLD, PROMO_ID)         VALUES (CONCAT('P', FLOOR(RANDOM() * numRows)), FLOOR(RANDOM() * 1000), FLOOR(RANDOM() * numRows));         i := i + 1;     END LOOP;   i := 0;   -- 生成 COSTS 数据     WHILE i < numRows LOOP         INSERT INTO COSTS (PROD_ID, UNIT_PRICE, PROMO_ID) VALUES (CONCAT('P', FLOOR(RANDOM() * numRows)), ROUND(RANDOM() * 100, 2), FLOOR(RANDOM() * numRows));         i := i + 1;  END LOOP; END; $$; -- 使用存储过程 CALL GenerateData(10000);  -- 生成 10000 行数据 ``` ```` ### 规避措施 如上所述,问题出现的场景可以总结为,凡是出现union场景作为子句与另一张表join的情况,都会出现谓词不下推的场景。例如继续简化上述用例: ```sh select prod.* from PROMOTIONS prod join ( select AMOUNT_SOLD,s.PROMO_ID from sales s union select UNIT_PRICE,c.PROMO_ID from COSTS c ) V on prod.PROMO_ID=v.PROMO_ID and prod.prod_id = 'P8289'; ``` 此种情况也无法下推, 因此规避可以采用手动将条件下推至union两端的方式,如下: ```sh select prod.* from PROMOTIONS prod join ( select AMOUNT_SOLD,s.PROMO_ID from sales s where s.PROMO_ID in (select PROMO_ID from PROMOTIONS where prod_id = 'P8289') union select UNIT_PRICE,c.PROMO_ID from COSTS c where c.PROMO_ID in (select PROMO_ID from PROMOTIONS where prod_id = 'P8289')) V on prod.PROMO_ID=v.PROMO_ID and prod.prod_id = 'P8289'; ``` ## **问题5:hot\_standby\_feedback与延迟备库不能同时打开** ### 问题描述 在某一套业务配备了延迟备库后,突然发现某些sql性能开始下降,直至sql性能完全不可用,产生严重事故。 ### 临时解决方案 对于性能逐渐变差的问题,我们首先考虑的是索引失效。通过对表进行索引重建,或者进行vacuum后均可使得业务恢复正常状态。 ### 问题定位 1. 死元组未被及时清理 业务保留了现场,恢复至出问题的环境,上去查询死元组数量如下: ```sh bcpdb=# select * from pg_stat_user_tables where relname='t_task_inst'; -[ RECORD 1 ]-----+------------------------------ relid | 25013 schemaname | bcpapp relname | t_task_inst seq_scan | 0 seq_tup_read | 0 idx_scan | 0 idx_tup_fetch | 0 n_tup_ins | 0 n_tup_upd | 0 n_tup_del | 0 n_tup_hot_upd | 0 n_live_tup | 2515872 n_dead_tup | 549191 last_vacuum | last_autovacuum | last_analyze | 2024-08-19 17:26:16.497666+08 last_autoanalyze | vacuum_count | 0 autovacuum_count | 0 analyze_count | 1 autoanalyze_count | 0 last_data_changed | ``` 我们发现,死元组数量较多,这会极大的影响执行效率。 2. 死元组未被及时清理的原因:延迟备与hot\_standby\_feedback同时开启,导致oldestxmin很小,vacuum无法清理。 观察日志,发现虽然autovacuum有在执行,但是每次vacuum处理的死元组数量非常有限。 所有autovacuum相关参数参考[社区文档](https://docs.opengauss.org/zh/) 主要的参数为autovacuum\_vacuum\_threshold,autovacuum\_vacuum\_scale\_factor 这里附上整个autovacuum的执行逻辑如下: * Autovacuum对应线程,通过检测表的死元组数量(pgstat模块进行统计, 并有视图可以展示查看)是否达到阈值(autovacuum\_vacuum\_threshold,autovacuum\_vacuum\_scale\_factor参数控制);来判断是否对表做vacuum。 * 在vacuum过程中,需要根据oldestxmin判断能否进行实际的清理。这里的oldestxmin指的是可能用到的最小事务号(由多种因素共同计算得出,例如活跃的最小事务号等)。死元组涉及的事务号必须要小于oldestxmin才会被清理。   那么现在问题很明确了,正确触发了vacuum但是没有清理死元组,我们联想到延迟备库,因为延迟备才造成了这个问题,自然而然我们发现了一个可疑参数hot\_standby\_feedback 这个参数的原理参考如下文章:。 简而言之,hot\_standby\_feedback 可以解决备库读可能被中断的问题,他的原理上是主机在更新oldestxmin时,会综合考虑备机上的事务oldestxmin信息。 因此,当开启了延迟备后,oldestxmin实际上采用的是延迟备同步过来的,而备机配置了延迟了12h,这也就意味着12h内事务产生的死元组,是一定无法清理的。所以也就造成了上述问题。 ### 解决方案 关闭延迟备的hot\_standby\_feedback即可,本身延迟备没有读的需求。 * 补充说明 > 在数据库重启等场景下,备机会主动同步主机的配置参数,因此有可能改了延迟备机参数后,后面重启实例参数又被重置回去了。 > 对于这个场景,可以配置sync\_config\_strategy=none\_node,表示主备节点各自维护各自的配置,不进行同步。 --- --- url: /zh.md --- --- --- url: /zh/docs/common/contribute/ci_rules.md --- # 文档开发流水线门禁 为提升文档质量,openGauss docs 仓引入了自动化动检视工具,对文档中低错问题进行排查。 开发者提交PR后,会自动触发门禁进行检查。当返回如下结果时表示已经通过了工具检查: ![](./figures/ci_results.png) 通过门禁检查是PR合入的必要条件之一,检查项提示错误可在`Build Details`查看错误详细信息。 下面将对各个检查项进行介绍: ## tag-closed-check Tag Closed Check将检查文档里HTML标签闭合问题。请注意,代码块里的HTML标签将不会扫描。 反例: ```html
Header 1 Header 2
Data 1 Data 2
``` 正例: ```html
Header 1 Header 2
Data 1 Data 2
``` ## link-validity-check Link Validity Check 将检查文档中出现的所有链接是否有效。 反例: ```text ![错误官网](https://doc.opengauss.org/zh/) ``` 正例: ```text ![正确官网](https://docs.opengauss.org/zh/) ``` ## resource-existence-check 此检查项将确认本地图片或者链接是否有效。 反例: ```text ![ci图片](./ci检查结果.jpg) ``` 正例: ```text ![ci图片](./figures/ci检查结果.jpg) ``` ## toc-check * 新增文档为确保能在 openGauss 文档官网展示,需要在对应`_toc.yaml`文件增加所在章节位置,否则此检查项报错。`toc.yaml`文件格式可参考[\_toc.yaml文件写作规范](./directory_structure_introductory.md#目录配置文件格式_tocyaml)。 * 变更文档名称时,Toc Check会检查对应`_toc.yaml`文件是否同步修改文档名称。 * 在进行Toc Check检查时,门禁会对文档进行全量检查,检查每个`_toc.yaml`文件中所有的文件是否存在于文档对应的路径下,若`_toc.yaml`文件中记录的文件不存在,则会报错。 ## markdownlint Markdown Lint 对markdown文档的格式进行检视。markdownlint规则介绍及本仓规则设置,请参考[**检查规则**](https://gitcode.com/opengauss/docs/blob/stable-common/docs/zh/contribute/markdownlint_rules.md)。 ## codespell-check Codespell 主要用于检查文档中的单词拼写错误,详细信息可参考。 如果有特殊单词需要加入忽略清单,可联系[wu-donger](https://gitcode.com/Evawudonger)。 --- --- url: /zh/docs/common/contribute/directory_structure_introductory.md --- # 文档组织架构 ## 介绍 本文介绍 openGauss 文档仓的组织架构。 仓库目录定义如下:/docs(企业版)与 /docs-lite(轻量版)为核心文档目录,其下的 /zh、/en 子目录分别对应官网的中英文版本。此外,设有 /archive 作为文档临时存储区,用于存放待完善或暂不推广的文档,待其满足要求后,应迁移至核心目录以供官网发布。 ```text ├─archive │ ├─en │ └─zh ├─docs │ ├─en │ └─zh ├─docs-lite │ ├─en │ └─zh ``` ## 仓库目录结构说明 以企业版中文文档为例,文档中心的15本手册与仓库`/docs/zh`下的15个子目录一一对应,如下所示: ```text ├─openGauss/docs 仓 ├─docs │ ├─en │ └─zh │ ├─release_notes │ ├─about_opengauss │ ├─getting_started │ ├─installation_guide │ ├─sql_reference │ ├─database_administration_guide │ ├─database_om_guide │ ├─performance_tuning_guide │ ├─data_migration_guide │ ├─datavec │ ├─resource_pooling │ ├─developer_guide │ ├─compilation_guide │ ├─extension_reference │ ├─database_reference │ ├─tool_and_commandreference │ ├─characteristic_description │ └─appendix ├─docs-lite │ ├─en │ └─zh ``` ## 目录配置文件格式(\_toc.yaml) 每本手册都有一个独立的\_toc.yaml 目录配置文件,示例如下: ```yaml label: 安装指南 isManual: true sections: - label: 安装概述 href: ./installation_overview.md - label: 容器镜像安装 href: ./installing_the_container_image.md sections: - label: 单节点安装 href: ./installation_on_a_single_node_container.md - label: 一主两备安装 href: ./one_primary_and_two_backup_installations_without_cm_container.md ``` * label:手册名称。 * isManual:标识手册的目录配置文件。 * sections: * label:章节名称。 * href:文档内容文件地址(建议使用相对路径)。 --- --- url: /zh/docs/common/faq/migration.md --- # 迁移常见问题与解决方法 ## **问题1:Mysql longblob二进制正常迁移opengauss,导致二进制图片打不开** ### 问题描述 Opengauss B库兼容下longblob接收有问题,需要转成bytea。 ### 解决方案 datakit迁移配置修改: 1. 在配置迁移过程参数中,点击编辑任务配置参数。 ![image](figures/fig_migration_1_1.png) 点击高级参数 ![image](figures/fig_migration_1_7.png) 2. 将下列数值修改:在迁移过程中将mysql的longblob类型转换为bytea,点击保存。 ![image](figures/fig_migration_1_2.png) 3. 迁移: 迁移后的表类型为 ![image](figures/fig_migration_1_3.png) 4. 简单验证: mysql将图片二进制插入表中: ![image](figures/fig_migration_1_4.png) Opengauss将迁移过来的表数据读取输出图片: ![image](figures/fig_migration_1_5.png) ![image](figures/fig_migration_1_6.png) 将jpg文件放在windows桌面可正常打开。 ## **问题2:使用DataStudio实现数据迁移** ### 解决方案 #### DataStudio下载及使用 1. DataStudio下载:[DataStudio](https://opengauss.org/zh/download/archive/), 找到相关页面点击下载: ![image](figures/fig_migration_2_1.png) 2. 将下载的压缩包解压 ![image](figures/fig_migration_2_2.png) 3. 解压出现如下内容:点击exe程序,即可启动(确保windows环境有Java11,否则会报错) ![image](figures/fig_migration_2_3.png) 4. 即可进入到DataStudio主界面 ![image](figures/fig_migration_2_4.png) 5. 数据库执行如下: ```bash create database db_1; create roles test1 password 'xxxxxxxx'; grant all privileges to test1; create schema test1; gs_guc reload -D Dn -h "host all all 0.0.0.0/0 sha256" #(添加windows白名单到数据库配置文件) ``` 6. 客户段按照填完相关信息,不勾选启用SSL,点击确定,然后点击继续。 ![image](figures/fig_migration_2_5.png) 数据库连接成功: ![image](figures/fig_migration_2_6.png) #### 迁移数据 假设db\_1库,test1模式下有如下内容: ![image](figures/fig_migration_2_7.png) 1. 在**对象浏览器**窗格中,右键单击所选模式,选择**导出 DDL 和数据**。 Data Studio 显示**安全警告**对话框。 用户可关闭此对话框。详情请参见安全警告。 2. 单击**确定**。 Data Studio 显示**另存为**对话框。 3. 在**另存为**对话框中,选择定义和数据的保存位置,单击**保存**。状态栏会显示操作进度。 > \[!NOTE]说明 > > DataStudio导出文件位置必须有路径权限,否则会导出失败。 ![image](figures/fig_migration_2_8.png) 导出完成: ![image](figures/fig_migration_2_9.png) 导出后为模式下的整个sql, 新库可以使用gsql工具导入相关表sql。 ![image](figures/fig_migration_2_10.png) 在两个不同库,相同表结构下,可以将表数据导出,再导入表数据到其他库中相同的表,目前只能一个表依次操作导入,效率不高。 ![image](figures/fig_migration_2_11.png) --- --- url: /zh/docs/common/faq/driver.md --- # 驱动常见问题与解决方法 ## **问题1:20250607\_xx\_psycopy2驱动类型映射问题** ### 问题描述 * 【数据库版本】openGauss 6.0.0 LTS * 【模块】驱动,opengauss-psycopg2(6.0.0) * 【问题描述】2025年6月,用户通过SQLAlchemy(x.x.xx版本)调用opengauss-psycopg2(6.0.0版本)执行全表查询时,高概率出现报错`Value Error: invalid literal for int() with base 10: '{}'`,导致业务报错中断。 ### 问题定位 1. 根据报错堆栈,程序在调用fetchall()接口时报错,定界报错模块。 ![image](figures/fig_driver_1_1.png) 这里花了一些时间捋清楚代码的调用链。SQLAlchemy ORM 层 ->psycopg2 (DBAPI) 驱动层 ->libpq (openGauss C API) 层(代码示例见#-解决方案)。报错的地方是dbapi\_cursor.fetchall(),所以,问题应该出在psycopg2驱动中的类型转换。 2. 查看psycopg2中实现,找到问题代码 `dbapi_cursor.fetchall()`最终调用到了psycopg2驱动中的`curs_fetchall -> _psyco_curs_buildrow -> _psyco_curs_buildrow_fill -> typecast_cast`,在typecast\_cast函数中进行类型转换。 通过对正常流程的debug调试,转换函数实际走的是下面的流程: ![image](figures/fig_driver_1_2.png) 调试过程:先按照debug方式编译psycopg2, 并开启debug日志输出,方便定位。 执行`python3 -m pdb test_string_to_int.py`,打断点之后执行c,加载符号表。 ![image](figures/fig_driver_1_3.png) `ps ux`找到对应的python进程,执行`gdb python3 pid` ![image](figures/fig_driver_1_4.png) 在psycopg2要跟踪的函数打断点,执行c ![image](figures/fig_driver_1_5.png) 在python的debug程序中执行c,在出现`Value Error: invalid literal for int() with base 10: '{}'`报错时,程序会停到psycopg2的断点函数上,证明psycopg2中将text(报错字段类型)的转换函数注册为了int的转换函数。 继续寻找`self->ccast`回调函数的赋值点,在两个地方有赋值: 1. register\_type\_uint,该函数是在B库下去注册uint1,uint2,uint4,uint8的cast函数 ![image](figures/fig_driver_1_6.png) 2. typecast\_from\_c,该函数是在init时,对所有基础类型注册cast函数 ![image](figures/fig_driver_1_7.png) 通过分析,怀疑register\_type\_uint在注册的时候出现问题,并通过回退这段代码证实。 3. 进一步定位问题根因 为了进一步确认在哪里将text类型映射成了int,我们在typecast\_add的代码中添加打印日志,在每一次cast函数注册时,打印出注册的oid和映射后的类型name ![image](figures/fig_driver_1_8.png) 继续运行程序,发现register\_type\_uint中注册了很多跟uint不想关的oid,其中就用`oid=25(text)`,确认了问题出现的原因。 进一步分析代码,发现问题点,\_typecast\_INTEGER\_types在malloc之后,没有memset,在后面判断是否值为0时,判断条件失效,从而导致注册不相关的其他类型。问题定位。 ![image](figures/fig_driver_1_9.png) 4. 问题原因总结 由于psycopg2中malloc之后没有memset,导致驱动出现类型映射错误现象,最终导致客户程序抛异常。 ### 规避&处理措施 * \*\*【规避措施】\*\*客户现场规避方案:回退到5.0.0 * \*\*【处理措施】\*\*问题最终解决方案:修改代码 ### 解决方案 * **【故障现象】** 驱动执行报错 * **【故障场景】** ORM框架调用驱动后报错 * **【检查手段】** 类似场景可通过以下几步去分析 1. 通过ORM框架调用函数链,找到驱动实际执行函数(代码分析); 2. 确认驱动中类型和cast函数的注册逻辑(代码分析); 3. Debug驱动代码,确认有问题的cast函数注册地方(debug); * **【处理方法】** 附代码示例: ``` import time from sqlalchemy.orm import declarative_base, relationship, sessionmaker from sqlalchemy import create_engine, Column, Integer, String, Text, TIMESTAMP, JSON, Boolean, ForeignKey, Date, DateTime, \ UniqueConstraint, Index, CheckConstraint from sqlalchemy.dialects.postgresql import UUID, BOOLEAN from datetime import datetime import base64 import threading import traceback import os #import logging #logging.basicConfig(level=logging.DEBUG) #logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG) #os.environ['PSYCOPG_DEBUG'] = '1' # 按照要求组织成一定的字符串,注意url特殊字符的转义 DB_URI = 'postgresql+psycopg2://:@:/' # 替换下面的参数以连接到你的openGauss数据库 # 格式为:'OpenGauss://<用户>:<密码>@<地址>:<端口>/<数据库名>' engine = create_engine(DB_URI, max_overflow=200, # 超过连接池大小外最多创建的连接 pool_size=100, # 连接池大小 pool_timeout=30, # 池中没有线程最多等待的时间,否则报错 pool_recycle=10, # 对线程池中的线程进行一次连接的回收的时间,如果是3600,表示1个小时后对连接进行回收 client_encoding='utf8' # 字符集 ) # 声明ORM基类 Base = declarative_base() class User(Base): __tablename__ = 'user5' id = Column(String(64), primary_key=True) extra = Column(Text,primary_key=True) enabled = Column(Boolean) default_project_id = Column(String(64)) created_at = Column(TIMESTAMP(timezone=False)) last_active_at = Column(Date) domain_id = Column(String(64)) def init_db(): # 创建继承base类的表的映射关系 Base.metadata.create_all(engine) def query(): Session = sessionmaker(bind=engine) session = Session() users = session.query(User).all() #users = session.query(User).filter_by(id) for user in users: if type(user.enabled) is not bool: print("is not bool", user.enabled) print("type=", type(user.enabled)) if __name__ == '__main__': init_db() try: for i in range(10000001): #t = threading.Thread(target=query) #t.start() if i % 1000 == 0: print("try ", i) query() #time.sleep(0.1) except BaseException as e: tb = traceback.format_exc() print("try ", i) print("catch except:", e, tb) ``` ## **问题2:executemany故障报告** ### 问题描述 openGauss的Python驱动psycopg2中,executemany接口执行批量插入相较于mysql性能较差。 ### 问题根因 Executemany接口继承于原生pg驱动,并且并未做修改,原生pg驱动同样存在该问题。该接口并没有对批量操作做任何优化,与在python中使用for循环无异。而在mysql的驱动中,executemany接口会把多个插入数据拼接成一个sql去执行。 Pg社区未做优化的原因: 参考以下链接中的讨论[issue](https://github.com/psycopg/psycopg2/issues/491) 可以看出pg社区的工程师认为,这种自动拼接的操作不应该由驱动来做而应该由业务人为的区分,所以一开始并未实现该功能。然而后续针对这个issue pg社区改变了想法,认为还是有必要做enhancement,所以添加了多个其他接口来实现批量执行的优化,原来的executemany保持不变。 其他接口使用方式如下: execute\_values接口可以达到mysql驱动中executemany接口相同的功能。 ### 解决方案 由于已经具备导成一条sql执行的接口,og社区也暂不考虑做executemany的优化。建议业务侧使用execute\_values接口适配后重新进行测试查看是否满足业务需求。 具体的execute\_values针对wakeloss脚本中的适配方案如下: ``` #添加库文件 from psycopg2.extras import execute_batch, execute_values #插入时,values后面跟一个占位符%s即可,数据格式不变,调用方法为execute_values(cursor, insert_query, values),详情还是参考https://www.psycopg.org/docs/extras.html#fast-exec #脚本中做如下修改可跑通 insert_query = """ INSERT IGNORE INTO {} ({}) VALUES %s """.format(d_table, ",".join(columns)) execute_values(cursor, insert_query, values) ``` ## **问题3:jdbc连接b兼容库问题** ### 问题描述 用户反馈500版本jdbc驱动连接500版本b兼容数据库会报错,在相同情况下使用300版本连接数据库正常。 ### 问题定位 1. 查看报错日志如下: `org.postgresql.util.PSQLException: [20.20.20.115:51808/20.20.20.115:16534] ERROR: permission denied for schema dolphin_catalog` 2. 问题复现 搭建环境 * 【安装数据库】编译安装5.0.0版本数据库 * 【编译dolphin插件】 1. 执行`git clone https://gitee.com/opengauss/Plugin.git -b v5.0.0` 2. 将Plugin目录下的dolphin全部拷贝到openGauss-server/contrib目录下,拷贝之后进入到openGauss￾server/contrib/dolphin目录下进行编译(需要设置好gcc等环境变量) 可以参考如下: ``` [lzf_500@openGauss115 JDBC]$ cat ~/.bashrc # Source default setting [ -f /etc/bashrc ] && . /etc/bashrc # User environment PATH PATH="$HOME/.local/bin:$HOME/bin:$PATH" export PATH export CODE_BASE=/home/lzf_500/openGauss-server/ export GAUSSHOME=$CODE_BASE/mppdb_temp_install/ export LD_LIBRARY_PATH=$GAUSSHOME/lib::$LD_LIBRARY_PATH export PATH=$GAUSSHOME/bin:$PATH export BINARYLIBS=/home/lzf_500/binarylibs export GCC_PATH=$BINARYLIBS/buildtools/gcc7.3 export CC=$GCC_PATH/gcc/bin/gcc export CXX=$GCC_PATH/gcc/bin/g++ export LD_LIBRARY_PATH=$GAUSSHOME/lib:$GCC_PATH/gcc/lib64:$GCC_PATH/isl/lib:$GCC_PATH/mpc/lib/:$GCC_PATH/mpfr/l ib/:$GCC_PATH/gmp/lib/:$LD_LIBRARY_PATH ``` * 【前置准备】 1. 创建b库 2. 创建用户 3. 修改b库参数 4. 修改数据库设置 5. 官网上下载300与500版本JDBC驱动,编写测试脚本,进行测试 a. java的测试demo OpenGaussJDBCExample.java ```java importjava.sql.Connection; importjava.sql.DriverManager;importjava.sql.ResultSet; importjava.sql.Statement; importjava.sql.SQLException; publicclassOpenGaussJDBCExample{ //数据库连接信息 privatestaticfinalStringDB_URL="jdbc:postgresql://xx.xx.xx.115:16534/test";privatestaticfinalStringUSER="user"; privatestaticfinalStringPASS="passwd@123"; publicstaticvoidmain(String[]args){ Connectionconn=null; Statementstmt=null; try{ //注册JDBC驱动 Class.forName("org.postgresql.Driver"); //打开连接 System.out.println("连接到数据库..."); conn=DriverManager.getConnection(DB_URL,USER,PASS); //执行查询 //执行查询 System.out.println("创建查询语句..."); stmt=conn.createStatement(); Stringsql="select*fromtest1.t1where1+1;"; esultSetrs=null; for(inti=0;i<1;i++){ rs=stmt.executeQuery(sql); //打印查询结果 while(rs.next()){ //根据查询结果字段类型获取数据 //intid=rs.getInt("a"); //Stringname=rs.getString("name");//打印结果 //System.out.println("ID:"+id); } rs.close(); } //完成后关闭 rs.close(); stmt.close(); conn.close(); }catch(SQLExceptionse){ //处理JDBC错误 se.printStackTrace }catch(Exceptione){ //处理Class.forName错误 e.printStackTrace(); }finally{ //关闭资源 try{ if(stmt!=null)stmt.close(); }catch(SQLExceptionse2){ try{ if(conn!=null)conn.close(); }catch(SQLExceptionse){ se.printStackTrace(); } } System.out.println("程序结束!"); } } } ``` b. 测试脚本 test.sh ,修改文件名和路径名,选择使用300驱动或者500驱动 ```sh javac-cp.:/home/lzf_500/JDBC/3.0.0/postgresql.jarOpenGaussJDBCExample.java java-cp.:/home/lzf_500/JDBC/3.0.0/postgresql.jarOpenGaussJDBCExample ``` * 【问题复现】 1. 修改OpenGaussJDBCExample.java 中`String sql = " select * from test1.t1;"`; 300与500驱动执行均未报错 2. 咨询兼容性开发同事,设计用例`String sql = " select * from test1.t1 where 1+1;"`; 300驱动与500驱动均报错,如下: ```sql 连接到数据库... Jan 17, 2025 11:38:01 AM org.postgresql.core.v3.ConnectionFactoryImpl openConnectionImpl INFO: [2c831c08-0ebd-4694-b34b-29d14fa704f7] Try to connect. IP: 20.20.20.115:16534 Jan 17, 2025 11:38:01 AM org.postgresql.core.v3.ConnectionFactoryImpl openConnectionImpl INFO: [20.20.20.115:51808/20.20.20.115:16534] Connection is established. ID: 2c831c08-0ebd-4694-b34b- 29d14fa704f7 Jan 17, 2025 11:38:01 AM org.postgresql.core.v3.ConnectionFactoryImpl openConnectionImpl INFO: Connect complete. ID: 2c831c08-0ebd-4694-b34b-29d14fa704f7 创建查询语句... org.postgresql.util.PSQLException: [20.20.20.115:51808/20.20.20.115:16534] ERROR: permission denied for schema dolphin_catalog Detail: N/A at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2901) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2630) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:362) at org.postgresql.jdbc.PgStatement.runQueryExecutor(PgStatement.java:561) at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:538) at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:396) at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:338) at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:324) at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:301) at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:240) at OpenGaussJDBCExample_500.main(OpenGaussJDBCExample_500.java:33) 程序结束! ``` 3. 修改用例,进行确认`String sql = " select * dolphin_calalog.dolphin_int4pl(1,1);"`; 结果和场景2一致 4. 查看数据库pg\_log日志,进行分析,也是该语句执行报错 ```log 2025-01-1711:16:17.332t2test20.20.20.1152814615264033440[0:0#0]forschemadolphin_catalog 2025-01-1711:16:17.332t2test20.20.20.1152814615264033440[0:0#0]2025-01-1711:16:17.332t2test20.20.20.1152814615264033440[0:0#0]privilegesfortheobject. 2025-01-1711:16:17.332t2test20.20.20.1152814615264033440[0:0#0]systemtablestogettheacloftheobject. 2025-01-1711:16:17.332t2test20.20.20.1152814615264033440[0:0#0]fromtest1.t1where1+1 2025-01-1711:16:17.332t2test20.20.20.1152814615264033440[0:0#0]tid[1138099]'sbacktrace: ``` 5. 授予权限 ```sql grantusageonschemadolphin_catalogtopublic; REVOKEUSAGEONSCHEMAdolphin_catalogFROMPUBLIC;(撤回语句,该sql不执行) ``` 然后再执行上述测试,300与500版本均能执行通过。 3. 问题探究 从现象来看,是因为执行了类似的`select 1+1;`等类似的操作,需要调用到dolphin\_catalog中的函数, 但是没有相应的权限,需要授予权限之后才能执行。 复现成功之后反馈给客户,向客户获取执行失败的sql进行结论验证,返回失败的都是同一条sql,如下所 示 ![image](figures/fig_driver_1_1.png) ## **问题4:修改用户名导致md5认证失败** ### 问题描述 修改了包含md5认证的用户名,会导致使用md5连接认证失败。 ### 解决方案 * 修改用户名: `ALTER USER btest RENAME TO atest;` * 查看加密方式: `password_encryption_type=1` 如果password\_encryption\_type为0或者1,则用户的密码是使用md5进行加密的。 md5加密不安全,opengauss在修改用户名后,为了安全起见,将md5的认证设置为不可用,必须重置密码才行。 `WARNING: Please alter the role's password after rename role name for compatible with PG client.` 原生pg驱动只能使用md5跟opengauss连接,所以报这个错了。重置下密码,pg驱动也可以继续用了。推荐用opengauss驱动。 ![image](figures/fig_driver_6.png) ## **问题7:修改表结构应用查询报错** ### 问题描述 修改表结构导致DDL报错,问题如图: 报错:`Error: cached plan must not change result type.` 背景:这个表使用alter语句,修改过一个字段的长度,从500改为2000。 ### 问题定位 DDL是被会话级别缓存的,改了之后需要重连会话。 1. 对于这个问题,可以应用侧重启,重新`prepare execute`。 2. 重启数据库肯定可以解决,但不推荐。 问题修复 方案:在获取缓存中的 plan cache 时,如果结果集检查不通过,则主动失效并重建 plan cache PR: https://gitee.com/opengauss/openGauss-server/pulls/5157 修复版本: >=3.0.6 >=5.0.3 >=6.0.0 --- url: >- /en/docs/latest-lite/database_om_guide/error_no_space_left_on_device_is_displayed.md --- # "Error:No space left on device" Is Displayed ## Symptom The following error message is displayed when the database is being used: ``` Error:No space left on device ``` ## Cause Analysis The disk space is insufficient. ## Procedure * Run the following command to check the disk usage. The **Avail** column indicates the available disk space, and the **Use%** column indicates the percentage of disk space that has been used. ``` [root@openeuler123 mnt]# df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 255G 0 255G 0% /dev tmpfs 255G 35M 255G 1% /dev/shm tmpfs 255G 57M 255G 1% /run tmpfs 255G 0 255G 0% /sys/fs/cgroup /dev/mapper/openeuler-root 196G 8.8G 178G 5% / tmpfs 255G 1.0M 255G 1% /tmp /dev/sda2 9.8G 144M 9.2G 2% /boot /dev/sda1 10G 5.8M 10G 1% /boot/efi ``` ``` The demand for remaining disk space depends on the increase in service data. Suggestions: - Check the disk space usage status, ensuring that the remaining space is sufficient for the growth of disk space for over one year. - If the disk space usage exceeds 60%, you must clear or expand the disk space. ``` * Run the following command to check the size of the data directory. ``` du --max-depth=1 -h /mnt/ ``` The following information is displayed. The first column shows the sizes of directories or files, and the second column shows all the sub-directories or files under the **/mnt/** directory. ``` [root@openGauss36 mnt]# du --max-depth=1 -h /mnt 83G /mnt/data3 71G /mnt/data2 365G /mnt/data1 518G /mnt ``` * Clean up the disk space. You are advised to periodically back up audit logs to other storage devices. The recommended log retention period is one month. **pg\_log** stores database process run logs which help database administrators locate faults. You can delete error logs if you view them every day and handle errors in time. * Delete useless data. Back up data that is not used frequently or used for a certain period of time to storage media with lower costs, and clean the backup data to free up disk space. * If the disk space is still insufficient, expand the disk capacity. --- --- url: /en/docs/latest/resource_pooling/error_no_space_left_on_device_is_displayed.md --- # "Error:No space left on device" Is Displayed ## Symptom The following error message is displayed when the cluster is being used: ``` Error:No space left on device ``` ## Cause Analysis The disk space is insufficient. ## Procedure * Run the following command to check the disk usage. The **Avail** column indicates the available disk space, and the **Use%** column indicates the percentage of disk space that has been used. ``` [root@openeuler123 mnt]# df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 255G 0 255G 0% /dev tmpfs 255G 35M 255G 1% /dev/shm tmpfs 255G 57M 255G 1% /run tmpfs 255G 0 255G 0% /sys/fs/cgroup /dev/mapper/openeuler-root 196G 8.8G 178G 5% / tmpfs 255G 1.0M 255G 1% /tmp /dev/sda2 9.8G 144M 9.2G 2% /boot /dev/sda1 10G 5.8M 10G 1% /boot/efi ``` ``` The demand for remaining disk space depends on the increase in service data. Suggestions: - Check the disk space usage status, ensuring that the remaining space is sufficient for the growth of disk space for over one year. - If the disk space usage exceeds 60%, you must clear or expand the disk space. ``` * Run the following command to check the size of the data directory. ``` du --max-depth=1 -h /mnt/ ``` The following information is displayed. The first column shows the sizes of directories or files, and the second column shows all the sub-directories or files under the **/mnt/** directory. ``` [root@openGauss36 mnt]# du --max-depth=1 -h /mnt 83G /mnt/data3 71G /mnt/data2 365G /mnt/data1 518G /mnt ``` * Clean up the disk space. You are advised to periodically back up audit logs to other storage devices. The recommended log retention period is one month. **pg\_log** stores database process run logs which help database administrators locate faults. You can delete error logs if you view them every day and handle errors in time. * Delete useless data. Back up data that is not used frequently or used for a certain period of time to storage media with lower costs, and clean the backup data to free up disk space. * If the disk space is still insufficient, expand the disk capacity. --- --- url: >- /en/docs/latest-lite/database_om_guide/lock_wait_timeout_is_displayed_when_a_user_executes_an_sql_statement.md --- # "Lock wait timeout" Is Displayed When a User Executes an SQL Statement ## Symptom "Lock wait timeout" is displayed when a user executes an SQL statement. ``` ERROR: Lock wait timeout: thread 140533638080272 waiting for ShareLock on relation 16409 of database 13218 after 1200000.122 ms ERROR: Lock wait timeout: thread 140533638080272 waiting for AccessExclusiveLock on relation 16409 of database 13218 after 1200000.193 ms ``` ## Cause Analysis Lock waiting times out in the database. ## Procedure * After detecting such errors, the database automatically retries the SQL statements. The number of retries is controlled by **max\_query\_retry\_times**. * To analyze the cause of the lock wait timeout, find the SQL statements that time out in the **pg\_locks**and **pg\_stat\_activity**system catalogs. --- --- url: >- /en/docs/latest/resource_pooling/lock_wait_timeout_is_displayed_when_a_user_executes_an_sql_statement.md --- # "Lock wait timeout" Is Displayed When a User Executes an SQL Statement ## Symptom "Lock wait timeout" is displayed when a user executes an SQL statement. ``` ERROR: Lock wait timeout: thread 140533638080272 waiting for ShareLock on relation 16409 of database 13218 after 1200000.122 ms ERROR: Lock wait timeout: thread 140533638080272 waiting for AccessExclusiveLock on relation 16409 of database 13218 after 1200000.193 ms ``` ## Cause Analysis Lock waiting times out in the database. ## Procedure * After detecting such errors, the database automatically retries the SQL statements. The number of retries is controlled by **max\_query\_retry\_times**. * To analyze the cause of the lock wait timeout, find the SQL statements that time out in the **pg\_locks**and **pg\_stat\_activity**system catalogs. --- --- url: >- /en/docs/latest-lite/database_om_guide/too_many_clients_already_is_reported_or_threads_failed_to_be_created_in_high_concurrency_scenarios.md --- # "too many clients already" Is Reported or Threads Failed To Be Created in High Concurrency Scenarios ## Symptom When a large number of SQL statements are concurrently executed, the error message "sorry, too many clients already" is displayed or an error is reported, indicating that threads cannot be created or processes cannot be forked. ## Cause Analysis These errors are caused by insufficient OS threads. Check **ulimit -u** in the OS. If the value is too small (for example, less than 32768), the errors are caused by the OS limitation. ## Procedure Run **ulimit -u** to obtain the value of **max user processes** in the OS. ``` [root@openGauss36 mnt]# ulimit -u unlimited ``` Use the following formula to calculate the minimum value: ``` value=max (32768, number of instances x 8192) ``` The number of instances refers to the total number of instances on the node. To set the minimum value, add the following two lines to the **/etc/security/limits.conf** file: ``` * hard nproc [value] * soft nproc [value] ``` The file to be modified varies based on the OS. For versions later than CentOS6, modify the **/etc/security/limits.d/90-nofile.conf** file in the same way. Alternatively, you can run the following command to change the value. However, the change becomes invalid upon OS restart. To solve this problem, you can add **ulimit -u**\[*value*] to the global environment variable file **/etc/profile**. ``` ulimit -u [values] ``` In high concurrency mode, enable the thread pool to control thread resources in the database. --- --- url: >- /en/docs/latest/resource_pooling/too_many_clients_already_is_reported_or_threads_failed_to_be_created_in_high_concurrency_scenarios.md --- # "too many clients already" Is Reported or Threads Failed To Be Created in High Concurrency Scenarios ## Symptom When a large number of SQL statements are concurrently executed, the error message "sorry, too many clients already" is displayed or an error is reported, indicating that threads cannot be created or processes cannot be forked. ## Cause Analysis These errors are caused by insufficient OS threads. Check **ulimit -u** in the OS. If the value is too small (for example, less than 32768), the errors are caused by the OS limitation. ## Procedure Run **ulimit -u** to obtain the value of **max user processes** in the OS. ``` [root@openGauss36 mnt]# ulimit -uunlimited ``` Use the following formula to calculate the minimum value: ``` value=max (32768, number of instances x 8192) ``` The number of instances refers to the total number of instances on the node. To set the minimum value, add the following two lines to the **/etc/security/limits.conf** file: ``` * hard nproc [value] * soft nproc [value] ``` The file to be modified varies based on the OS. For versions later than CentOS6, modify the **/etc/security/limits.d/90-nofile.conf** file in the same way. Alternatively, you can run the following command to change the value. However, the change becomes invalid upon OS restart. To solve this problem, you can add **ulimit -u**\[*value*] to the global environment variable file **/etc/profile**. ``` ulimit -u [values] ``` In high concurrency mode, enable the thread pool to control thread resources in the database. --- --- url: >- /en/docs/latest/installation_guide/optional_setting_the_standby_node_to_readable.md --- # (Optional) Setting the Standby Node to Readable Readable standby node is an optional feature. You need to modify the configuration parameters and restart the primary and standby nodes before using this feature. After the readable standby node function is enabled, the standby node is readable, meeting data consistency requirements. ## Procedure 1. If the openGauss database instance is running on the primary and standby nodes, stop the database instance on both nodes. 2. Open the **postgresql.conf** configuration files of the primary and standby nodes based on the corresponding paths , find the corresponding parameters, and change the parameter values to **wal\_level=hot\_standby**, **hot\_standby = on**, and **hot\_standby\_feedback = on**. 3. Set the max\_standby\_streaming\_delay, max\_prepared\_transactions, max\_standby\_archive\_delay, hot\_standby\_feedback parameter as required by referring to the parameter description in the Development Guide. 4. After the modification, start the primary and standby nodes. --- --- url: >- /zh/docs/latest/installation_guide/optional_setting_the_standby_node_to_readable.md --- # (可选)设置备机可读 备机可读特性为可选特性,需要修改配置参数并重启主备机器后才能使用。在开启备机可读之后,备机将支持读操作,并满足数据一致性要求。 ## 操作步骤 1. 如果主备机上的openGauss数据库实例正在运行,请先分别停止主备机上的数据库实例。 2. 分别打开主机与备机的postgresql.conf配置文件,找到并将对应参数修改为:wal\_level=hot\_standby;hot\_standby = on;hot\_standby\_feedback = on。 3. 参数max\_standby\_streaming\_delay、 max\_prepared\_transactions、 max\_standby\_archive\_delay、 hot\_standby\_feedback可以参考《数据库参考》按需进行设置。 4. 修改完成后,分别启动主备机即可。 --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin_at_variable.md --- # @variable变量 ## 功能描述 openGauss在MySQL兼容模式下,支持用户变量`@variable`的以下两种使用形式: * 支持使用SET命令声明`@variable`,形如:`set @variable = value`或`set @variable := value`。 * 支持使用SELECT命令为`@variable`变量赋值,形如`select @variable := value`。 利用`@variable`特性能够实现SQL中的递归查询,详见[示例3](#示例3)。递归查询是一种特殊的查询技术,它通过循环调用一个单独的查询来遍历整个数据集。递归查询通常用于查询树形结构或图形结构数据。这些数据结构通常有父节点和子节点之间的关系。 ## 注意事项 * 使用此功能需开启参数enable\_set\_variable\_b\_format,表示允许数据库在MySQL兼容模式下使用自定义用户变量的功能。 * 用户变量是针对当前登录openGauss的用户的私有变量,声明过的`@variable`变量在客户端连接到数据库实例的整个过程中都是有效的。 * SET命令支持的赋值符号可以是`:=`或`=`,而select赋值时仅支持使用`:=`。 * 若使用prepare from为SQL语句命名时,用户自定义变量存储的字符串仅支持select、insert、update、delete、merge语法,且必须是单条语句。 * 无论SET或是SELECT都可以同时对多个变量进行赋值。 * 带变量赋值的查询无法使用smp并行特性。 ## 示例 **示例1:** 使用SET命令为变量赋值。 1、设置参数enable\_set\_variable\_b\_format为on。 ```sql SET enable_set_variable_b_format=on; ``` 2、使用SET定义变量。 ```sql set @VAR1_1102053=123; set @var2_1102053:=1111::int4; set @var3_1102053 := @var6_1102053 := @$var7_1102053:=12345678::int8; ``` 3、直接查看变量的值。 ```sql select @VAR1_1102053,@VAR2_1102053,@VAR3_1102053; ``` 返回结果如下: ```sql @var1_1102053 | @var2_1102053 | @var3_1102053 ---------------+---------------+--------------- 123 | 1111 | 12345678 (1 row) ``` 4、创建测试表。 ```sql create table table_1102053 (id int,name text); ``` 5、向测试表中插入数据时使用声明过的变量。 ```sql insert into table_1102053 values(@VAR1_1102053,'test'); ``` 6、查看测试表数据。 ```sql select * from table_1102053; ``` 返回结果如下,变量`@VAR1_1102053`的值被插入到了表中对应位置: ```sql id | name -----+------ 123 | test (1 row) ``` **示例2:** SELECT直接为变量赋值并查看。 1、设置参数enable\_set\_variable\_b\_format为on。 ```sql SET enable_set_variable_b_format=on; ``` 2、执行如下SELECT语句。 ```sql select @var:=1 as col1,@va:=3; ``` 返回结果如下: ```sql col1 | ?column? ------+---------- 1 | 3 (1 row) ``` **示例3:** 使用@变量实现递归查询。 1、设置参数enable\_set\_variable\_b\_format为on。 ```sql SET enable_set_variable_b_format=on; ``` 2、创建测试表并插入数据。 ```sql CREATE TABLE my_table_1162203 ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL, parent_id INT, CONSTRAINT uc_name UNIQUE (name), CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES my_table_1162203(id) ); -- 插入数据 INSERT INTO my_table_1162203 (name, parent_id) VALUES ('a1', 1), ('a2', 2), ('a3', 1), ('a4', 2), ('a5', 1), ('a6', 2); ``` 3、查看测试表数据。 ```sql select * from my_table_1162203; ``` 返回结果如下,三个字段的含义分别记为每条记录的ID,名称,父节点ID。 ```sql id | name | parent_id ----+------+----------- 1 | a1 | 1 2 | a2 | 2 3 | a3 | 1 4 | a4 | 2 5 | a5 | 1 6 | a6 | 2 (6 rows) ``` 4、使用SET命令为变量赋值,指定`@parent_id`为1。 ```sql SET @parent_id := 1; ``` 5、检索给定节点的所有兄弟节点,返回所有父节点ID为1的记录。 ```sql SELECT id, name FROM my_table_1162203 WHERE parent_id = ( SELECT parent_id FROM my_table_1162203 WHERE id = @parent_id ); ``` 返回结果如下: ```sql id | name ----+------ 1 | a1 3 | a3 5 | a5 (3 rows) ``` 6、以下语句等效于步骤4(定义变量)和步骤5(查询)的结合,在一个语句里实现了同样的递归查询效果: ```sql SELECT id, name FROM my_table_1162203 WHERE parent_id = ( SELECT parent_id FROM my_table_1162203 WHERE id =(select @parent_id:= 1) ); ``` 返回结果如下: ```sql id | name ----+------ 1 | a1 3 | a3 5 | a5 (3 rows) ``` **示例4:** 使用set语法创建prepare语句。 1、设置参数enable\_set\_variable\_b\_format为on。 ```sql SET enable_set_variable_b_format=on; ``` 2、创建测试表。 ```sql create table tb1(id int); ``` 3、使用set语法将两个自定义变量赋值为字符串,内容为SQL语句。 ```sql set @sql1:='insert into tb1 values(5)'; --语句1 set @sql2:='select * from tb1'; --语句2 ``` 4、为步骤3中的两条SQL语句命名。 ```sql PREPARE stmt1 from @sql1; PREPARE stmt2 from @sql2; ``` 5、执行语句1,执行插入动作。 ```sql EXECUTE stmt1; ``` 6、执行语句2,查看测试表数据。 ```sql EXECUTE stmt2; ``` 返回结果为: ```sql id ---- 5 (1 row) ``` --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin_at_variable.md --- # @variable变量 ## 功能描述 openGauss在MySQL兼容模式下,支持用户变量`@variable`的以下两种使用形式: * 支持使用SET命令声明`@variable`,形如:`set @variable = value`或`set @variable := value`。 * 支持使用SELECT命令为`@variable`变量赋值,形如`select @variable := value`。 利用`@variable`特性能够实现SQL中的递归查询,详见[示例3](#示例3)。递归查询是一种特殊的查询技术,它通过循环调用一个单独的查询来遍历整个数据集。递归查询通常用于查询树形结构或图形结构数据。这些数据结构通常有父节点和子节点之间的关系。 ## 注意事项 * 使用此功能需开启参数enable\_set\_variable\_b\_format,表示允许数据库在MySQL兼容模式下使用自定义用户变量的功能。 * 用户变量是针对当前登录openGauss的用户的私有变量,声明过的`@variable`变量在客户端连接到数据库实例的整个过程中都是有效的。 * SET命令支持的赋值符号可以是`:=`或`=`,而select赋值时仅支持使用`:=`。 * 若使用prepare from为SQL语句命名时,用户自定义变量存储的字符串仅支持select、insert、update、delete、merge语法,且必须是单条语句。 * 无论SET或是SELECT都可以同时对多个变量进行赋值。 * 带变量赋值的查询无法使用smp并行特性。 ## 示例 **示例1:** 使用SET命令为变量赋值。 1、设置参数enable\_set\_variable\_b\_format为on。 ```sql SET enable_set_variable_b_format=on; ``` 2、使用SET定义变量。 ```sql set @VAR1_1102053=123; set @var2_1102053:=1111::int4; set @var3_1102053 := @var6_1102053 := @$var7_1102053:=12345678::int8; ``` 3、直接查看变量的值。 ```sql select @VAR1_1102053,@VAR2_1102053,@VAR3_1102053; ``` 返回结果如下: ```sql @var1_1102053 | @var2_1102053 | @var3_1102053 ---------------+---------------+--------------- 123 | 1111 | 12345678 (1 row) ``` 4、创建测试表。 ```sql create table table_1102053 (id int,name text); ``` 5、向测试表中插入数据时使用声明过的变量。 ```sql insert into table_1102053 values(@VAR1_1102053,'test'); ``` 6、查看测试表数据。 ```sql select * from table_1102053; ``` 返回结果如下,变量`@VAR1_1102053`的值被插入到了表中对应位置: ```sql id | name -----+------ 123 | test (1 row) ``` **示例2:** SELECT直接为变量赋值并查看。 1、设置参数enable\_set\_variable\_b\_format为on。 ```sql SET enable_set_variable_b_format=on; ``` 2、执行如下SELECT语句。 ```sql select @var:=1 as col1,@va:=3; ``` 返回结果如下: ```sql col1 | ?column? ------+---------- 1 | 3 (1 row) ``` **示例3:** 使用@变量实现递归查询。 1、设置参数enable\_set\_variable\_b\_format为on。 ```sql SET enable_set_variable_b_format=on; ``` 2、创建测试表并插入数据。 ```sql CREATE TABLE my_table_1162203 ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL, parent_id INT, CONSTRAINT uc_name UNIQUE (name), CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES my_table_1162203(id) ); -- 插入数据 INSERT INTO my_table_1162203 (name, parent_id) VALUES ('a1', 1), ('a2', 2), ('a3', 1), ('a4', 2), ('a5', 1), ('a6', 2); ``` 3、查看测试表数据。 ```sql select * from my_table_1162203; ``` 返回结果如下,三个字段的含义分别记为每条记录的ID,名称,父节点ID。 ```sql id | name | parent_id ----+------+----------- 1 | a1 | 1 2 | a2 | 2 3 | a3 | 1 4 | a4 | 2 5 | a5 | 1 6 | a6 | 2 (6 rows) ``` 4、使用SET命令为变量赋值,指定`@parent_id`为1。 ```sql SET @parent_id := 1; ``` 5、检索给定节点的所有兄弟节点,返回所有父节点ID为1的记录。 ```sql SELECT id, name FROM my_table_1162203 WHERE parent_id = ( SELECT parent_id FROM my_table_1162203 WHERE id = @parent_id ); ``` 返回结果如下: ```sql id | name ----+------ 1 | a1 3 | a3 5 | a5 (3 rows) ``` 6、以下语句等效于步骤4(定义变量)和步骤5(查询)的结合,在一个语句里实现了同样的递归查询效果: ```sql SELECT id, name FROM my_table_1162203 WHERE parent_id = ( SELECT parent_id FROM my_table_1162203 WHERE id =(select @parent_id:= 1) ); ``` 返回结果如下: ```sql id | name ----+------ 1 | a1 3 | a3 5 | a5 (3 rows) ``` **示例4:** 使用set语法创建prepare语句。 1、设置参数enable\_set\_variable\_b\_format为on。 ```sql SET enable_set_variable_b_format=on; ``` 2、创建测试表。 ```sql create table tb1(id int); ``` 3、使用set语法将两个自定义变量赋值为字符串,内容为SQL语句。 ```sql set @sql1:='insert into tb1 values(5)'; --语句1 set @sql2:='select * from tb1'; --语句2 ``` 4、为步骤3中的两条SQL语句命名。 ```sql PREPARE stmt1 from @sql1; PREPARE stmt2 from @sql2; ``` 5、执行语句1,执行插入动作。 ```sql EXECUTE stmt1; ``` 6、执行语句2,查看测试表数据。 ```sql EXECUTE stmt2; ``` 返回结果为: ```sql id ---- 5 (1 row) ``` --- --- url: >- /en/docs/latest-lite/performance_tuning_guide/case_adding_not_null_for_join_columns.md --- # **Case: Adding NOT NULL for JOIN Columns** ``` SELECT * FROM join_a a JOIN join_b b ON a.b = b.b; ``` The execution plan is as follows: ``` QUERY PLAN ---------------------------------------------------------------------------------------------------------------------- Hash Join (cost=58.35..14677.69 rows=1074607 width=16) (actual time=23.374..23.384 rows=10 loops=1) Hash Cond: (a.b = b.b) -> Seq Scan on join_a a (cost=0.00..2248.10 rows=100010 width=8) (actual time=0.495..12.551 rows=100010 loops=1) -> Hash (cost=31.49..31.49 rows=2149 width=8) (actual time=0.614..0.614 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on join_b b (cost=0.00..31.49 rows=2149 width=8) (actual time=0.009..0.183 rows=1000 loops=1) Total runtime: 23.716 ms (7 rows) ``` ## Optimization Analysis 1. As shown in the execution plan, the sequential scan phase is time consuming. 2. Therefore, you are advised to manually add **NOT NULL** for **JOIN** columns in the statement, as shown below: ``` SELECT * SELECT * FROM join_a a JOIN join_b b ON a.b = b.b where a.b IS NOT NULL; ``` The execution plan is as follows: ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------- Hash Join (cost=58.22..14560.97 rows=1063762 width=16) (actual time=13.237..13.247 rows=10 loops=1) Hash Cond: (a.b = b.b) -> Seq Scan on join_a a (cost=0.00..2248.10 rows=99510 width=8) (actual time=12.417..12.422 rows=10 loops=1) Filter: (b IS NOT NULL) Rows Removed by Filter: 100000 -> Hash (cost=31.49..31.49 rows=2138 width=8) (actual time=0.566..0.566 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on join_b b (cost=0.00..31.49 rows=2138 width=8) (actual time=0.011..0.229 rows=1000 loops=1) Filter: (b IS NOT NULL) Total runtime: 13.556 ms (10 rows) ``` --- --- url: >- /en/docs/latest/performance_tuning_guide/case_adding_not_null_for_join_columns.md --- # **Case: Adding NOT NULL for JOIN Columns** ``` SELECT * FROM join_a a JOIN join_b b ON a.b = b.b; ``` The execution plan is as follows: ``` QUERY PLAN ---------------------------------------------------------------------------------------------------------------------- Hash Join (cost=58.35..14677.69 rows=1074607 width=16) (actual time=23.374..23.384 rows=10 loops=1) Hash Cond: (a.b = b.b) -> Seq Scan on join_a a (cost=0.00..2248.10 rows=100010 width=8) (actual time=0.495..12.551 rows=100010 loops=1) -> Hash (cost=31.49..31.49 rows=2149 width=8) (actual time=0.614..0.614 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on join_b b (cost=0.00..31.49 rows=2149 width=8) (actual time=0.009..0.183 rows=1000 loops=1) Total runtime: 23.716 ms (7 rows) ``` ## Optimization Analysis 1. As shown in the execution plan, the sequential scan phase is time consuming. 2. Therefore, you are advised to manually add **NOT NULL** for **JOIN** columns in the statement, as shown below: ``` SELECT * SELECT * FROM join_a a JOIN join_b b ON a.b = b.b where a.b IS NOT NULL; ``` The execution plan is as follows: ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------- Hash Join (cost=58.22..14560.97 rows=1063762 width=16) (actual time=13.237..13.247 rows=10 loops=1) Hash Cond: (a.b = b.b) -> Seq Scan on join_a a (cost=0.00..2248.10 rows=99510 width=8) (actual time=12.417..12.422 rows=10 loops=1) Filter: (b IS NOT NULL) Rows Removed by Filter: 100000 -> Hash (cost=31.49..31.49 rows=2138 width=8) (actual time=0.566..0.566 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on join_b b (cost=0.00..31.49 rows=2138 width=8) (actual time=0.011..0.229 rows=1000 loops=1) Filter: (b IS NOT NULL) Total runtime: 13.556 ms (10 rows) ``` --- --- url: /en/docs/latest-lite/developer_guide/database_statement_execution_functions.md --- # **Database Statement Execution Functions** After the connection to the database server is successfully established, you can use the functions described in this section to execute SQL queries and commands. --- --- url: /en/docs/latest/developer_guide/database_statement_execution_functions.md --- # **Database Statement Execution Functions** After the connection to the database server is successfully established, you can use the functions described in this section to execute SQL queries and commands. * **[PQclear](pqclear.md)** * **[PQexec](pqexec.md)** * **[PQexecParams](pqexecparams.md)** * **[PQexecParamsBatch](pqexecparamsbatch.md)** * **[PQexecPrepared](pqexecprepared.md)** * **[PQexecPreparedBatch](pqexecpreparedbatch.md)** * **[PQfname](pqfname.md)** * **[PQgetvalue](pqgetvalue.md)** * **[PQnfields](pqnfields.md)** * **[PQntuples](pqntuples.md)** * **[PQprepare](pqprepare.md)** * **[PQresultStatus](pqresultstatus.md)** --- --- url: /zh/docs/latest-lite/developer_guide/database_statement_execution_functions.md --- # **数据库执行语句函数** 与数据库服务器的连接成功建立,便可以使用这里描述的函数执行SQL查询和命令。 * **[PQclear](pqclear.md)** * **[PQexec](pqexec.md)** * **[PQexecParams](pqexecparams.md)** * **[PQexecParamsBatch](pqexecparamsbatch.md)** * **[PQexecPrepared](pqexecprepared.md)** * **[PQexecPreparedBatch](pqexecpreparedbatch.md)** * **[PQfname](pqfname.md)** * **[PQgetvalue](pqgetvalue.md)** * **[PQnfields](pqnfields.md)** * **[PQntuples](pqntuples.md)** * **[PQprepare](pqprepare.md)** * **[PQresultStatus](pqresultstatus.md)** --- --- url: /zh/docs/latest/developer_guide/database_statement_execution_functions.md --- # **数据库执行语句函数** 与数据库服务器的连接成功建立,便可以使用这里描述的函数执行SQL查询和命令。 * **[PQclear](pqclear.md)** * **[PQexec](pqexec.md)** * **[PQexecParams](pqexecparams.md)** * **[PQexecParamsBatch](pqexecparamsbatch.md)** * **[PQexecPrepared](pqexecprepared.md)** * **[PQexecPreparedBatch](pqexecpreparedbatch.md)** * **[PQfname](pqfname.md)** * **[PQgetvalue](pqgetvalue.md)** * **[PQnfields](pqnfields.md)** * **[PQntuples](pqntuples.md)** * **[PQprepare](pqprepare.md)** * **[PQresultStatus](pqresultstatus.md)** --- --- url: >- /zh/docs/latest-lite/performance_tuning_guide/case_adding_not_null_for_join_columns.md --- # **案例:增加JOIN列非空条件** ``` SELECT * FROM join_a a JOIN join_b b ON a.b = b.b; ``` 执行计划下: ``` QUERY PLAN ---------------------------------------------------------------------------------------------------------------------- Hash Join (cost=58.35..14677.69 rows=1074607 width=16) (actual time=23.374..23.384 rows=10 loops=1) Hash Cond: (a.b = b.b) -> Seq Scan on join_a a (cost=0.00..2248.10 rows=100010 width=8) (actual time=0.495..12.551 rows=100010 loops=1) -> Hash (cost=31.49..31.49 rows=2149 width=8) (actual time=0.614..0.614 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on join_b b (cost=0.00..31.49 rows=2149 width=8) (actual time=0.009..0.183 rows=1000 loops=1) Total runtime: 23.716 ms (7 rows) ``` ## 优化分析 1. 分析执行计划可知,在顺序扫描阶段耗时较多。 2. 建议在语句中手动添加JOIN列的非空判断,修改后的语句如下所示。 ``` SELECT * FROM join_a a JOIN join_b b ON a.b = b.b where a.b IS NOT NULL; ``` 执行计划如下: ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------- Hash Join (cost=58.22..14560.97 rows=1063762 width=16) (actual time=13.237..13.247 rows=10 loops=1) Hash Cond: (a.b = b.b) -> Seq Scan on join_a a (cost=0.00..2248.10 rows=99510 width=8) (actual time=12.417..12.422 rows=10 loops=1) Filter: (b IS NOT NULL) Rows Removed by Filter: 100000 -> Hash (cost=31.49..31.49 rows=2138 width=8) (actual time=0.566..0.566 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on join_b b (cost=0.00..31.49 rows=2138 width=8) (actual time=0.011..0.229 rows=1000 loops=1) Filter: (b IS NOT NULL) Total runtime: 13.556 ms (10 rows) ``` --- --- url: >- /zh/docs/latest/performance_tuning_guide/case_adding_not_null_for_join_columns.md --- # **案例:增加JOIN列非空条件** ``` SELECT * FROM join_a a JOIN join_b b ON a.b = b.b; ``` 执行计划下: ``` QUERY PLAN ---------------------------------------------------------------------------------------------------------------------- Hash Join (cost=58.35..14677.69 rows=1074607 width=16) (actual time=23.374..23.384 rows=10 loops=1) Hash Cond: (a.b = b.b) -> Seq Scan on join_a a (cost=0.00..2248.10 rows=100010 width=8) (actual time=0.495..12.551 rows=100010 loops=1) -> Hash (cost=31.49..31.49 rows=2149 width=8) (actual time=0.614..0.614 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on join_b b (cost=0.00..31.49 rows=2149 width=8) (actual time=0.009..0.183 rows=1000 loops=1) Total runtime: 23.716 ms (7 rows) ``` ## 优化分析 1. 分析执行计划可知,在顺序扫描阶段耗时较多。 2. 建议在语句中手动添加JOIN列的非空判断,修改后的语句如下所示。 ``` SELECT * FROM join_a a JOIN join_b b ON a.b = b.b where a.b IS NOT NULL; ``` 执行计划如下: ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------- Hash Join (cost=58.22..14560.97 rows=1063762 width=16) (actual time=13.237..13.247 rows=10 loops=1) Hash Cond: (a.b = b.b) -> Seq Scan on join_a a (cost=0.00..2248.10 rows=99510 width=8) (actual time=12.417..12.422 rows=10 loops=1) Filter: (b IS NOT NULL) Rows Removed by Filter: 100000 -> Hash (cost=31.49..31.49 rows=2138 width=8) (actual time=0.566..0.566 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on join_b b (cost=0.00..31.49 rows=2138 width=8) (actual time=0.011..0.229 rows=1000 loops=1) Filter: (b IS NOT NULL) Total runtime: 13.556 ms (10 rows) ``` --- --- url: >- /zh/docs/latest-lite/performance_tuning_guide/case_sub_transaction_tpcc_performance_tuning.md --- # **案例:子事务TPCC性能调优** ## 现象描述 使用benchmark工具测试tpcc性能时,jdbc配置autosave="always"后,tpcc性能劣化明显。 经测试,500仓200并发,30分钟tpcc相同数据库参数的条件下,不开启autosave="always",tpmC性能为585258.37,开启autosave="always",tpmC性能为18322.86,劣化超过96%。 ## 优化分析 开启autosave='always'时,benchmark运行时数据库热力图如下所示,`SimpleLruWaitIO`函数占比高达66.5%。从热点可以看出,数据库热点集中在GetMultiXactIdMembers->SimpleLruWaitIO->SimpleLruWaitIO->LWLockAcqurie的流程上。MultiXactId可以理解为多事务id,一般出现执行select for share 或select for update时,当worker线程想要对元组加行锁时,如果发现该元组的xmax不为空,则会生成 multixactId并替换xmax,即一个multixactid意为多个transactionid对同一行元组加锁。openGauss使用multixact offset log和multixact member log存储multixactid信息,并使用类似于数据页面缓冲区管理机制的SLRU管理事务日志的缓存。其中multixactoffsetSLRU容量为8个页面,multixactmemberSLRU16个页面,并使用MultiXactOffsetCtlLock和MultiXactMemberCtrlLock控制页面在SLRU中的换入换出。 不同的事务id组合会生成不同的multixactid,在大量子事务并发的场景下,事务id数量变多,multixactid的数量会成倍增加。经测试,同样环境下,开启autosave会产生532MB的multixact memeber log和271MB的multixact offset log;不开启autosave时,multixact log大小在8k以内。当worker线程进行可见性判断、对tuple行锁时等multixact相关操作时,都可能会涉及到获取SLRU中的multixact信息,此时如果所需multixactid的页面不在内存中,就需要涉及内存中已有页面的换入换出,造成严重的锁冲突和频繁磁盘IO问题。 ![autosave=always](figures/tpcc_flame_autosave_always.png) ## 优化建议 openGauss自7.0.0-RC1版本引入优化,新增参数num\_slru\_buffers,用于设置multixact 相关日志的最大缓存槽位数,通过增大可缓存的最大槽位数,缓解multixact相关的锁冲突和频繁磁盘IO问题。 该场景的推荐配置如下: ``` num_slru_buffers='MXACT_OFFSET=256,MXACT_MEMBER=1024' ``` 经测试相同场景,500仓200并发,30分钟tpcc相同数据库参数的条件下,配置num\_slru\_buffers='MXACT\_OFFSET=256,MXACT\_MEMBER=1024',tpmC性能为210545.61,性能提升明显。 --- --- url: >- /zh/docs/latest/performance_tuning_guide/case_sub_transaction_tpcc_performance_tuning.md --- # **案例:子事务TPCC性能调优** ## 现象描述 使用benchmark工具测试tpcc性能时,jdbc配置autosave="always"后,tpcc性能劣化明显。 经测试,500仓200并发,30分钟tpcc相同数据库参数的条件下,不开启autosave="always",tpmC性能为585258.37,开启autosave="always",tpmC性能为18322.86,劣化超过96%。 ## 优化分析 开启autosave='always'时,benchmark运行时数据库热力图如下所示,`SimpleLruWaitIO`函数占比高达66.5%。从热点可以看出,数据库热点集中在GetMultiXactIdMembers->SimpleLruWaitIO->SimpleLruWaitIO->LWLockAcqurie的流程上。MultiXactId可以理解为多事务id,一般出现执行select for share 或select for update时,当worker线程想要对元组加行锁时,如果发现该元组的xmax不为空,则会生成 multixactId并替换xmax,即一个multixactid意为多个transactionid对同一行元组加锁。openGauss使用multixact offset log和multixact member log存储multixactid信息,并使用类似于数据页面缓冲区管理机制的SLRU管理事务日志的缓存。其中multixactoffsetSLRU容量为8个页面,multixactmemberSLRU16个页面,并使用MultiXactOffsetCtlLock和MultiXactMemberCtrlLock控制页面在SLRU中的换入换出。 不同的事务id组合会生成不同的multixactid,在大量子事务并发的场景下,事务id数量变多,multixactid的数量会成倍增加。经测试,同样环境下,开启autosave会产生532MB的multixact memeber log和271MB的multixact offset log;不开启autosave时,multixact log大小在8k以内。当worker线程进行可见性判断、对tuple行锁时等multixact相关操作时,都可能会涉及到获取SLRU中的multixact信息,此时如果所需multixactid的页面不在内存中,就需要涉及内存中已有页面的换入换出,造成严重的锁冲突和频繁磁盘IO问题。 ![autosave=always](figures/tpcc_flame_autosave_always.png) ## 优化建议 openGauss自7.0.0-RC1版本引入优化,新增参数num\_slru\_buffers,用于设置multixact 相关日志的最大缓存槽位数,通过增大可缓存的最大槽位数,缓解multixact相关的锁冲突和频繁磁盘IO问题。 该场景的推荐配置如下: ``` num_slru_buffers='MXACT_OFFSET=256,MXACT_MEMBER=1024' ``` 经测试相同场景,500仓200并发,30分钟tpcc相同数据库参数的条件下,配置num\_slru\_buffers='MXACT\_OFFSET=256,MXACT\_MEMBER=1024',tpmC性能为210545.61,性能提升明显。 --- --- url: >- /zh/docs/latest-lite/performance_tuning_guide/case_rewriting_sql_and_deleting_subqueries_2.md --- # **案例:改写SQL消除子查询(案例2)** ## 现象描述 如下SQL语句: ``` UPDATE normal_date n SET time = ( SELECT time FROM normal_date_part p WHERE p.id = n.id ) WHERE EXISTS (SELECT 1 FROM normal_date_part n2 WHERE n2.id = n.id); ``` 计划为: ``` QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Update on normal_date n (cost=224.40..2334150.22 rows=5129 width=16) (actual time=17.336..42944.734 rows=10000 loops=1) -> Hash Semi Join (cost=224.40..2334150.22 rows=5129 width=16) (actual time=16.997..42852.967 rows=10000 loops=1) Hash Cond: (n.id = n2.id) -> Seq Scan on normal_date n (cost=0.00..160.29 rows=5129 width=10) (actual time=0.113..7.271 rows=10000 loops=1) -> Hash (cost=160.29..160.29 rows=5129 width=10) (actual time=7.381..7.381 rows=10000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 430kB -> Seq Scan on normal_date n2 (cost=0.00..160.29 rows=5129 width=10) (actual time=0.052..3.501 rows=10000 loops=1) SubPlan 1 -> Partition Iterator (cost=0.00..455.00 rows=1 width=8) (actual time=21006.481..42756.884 rows=10000 loops=10000) Iterations: 331 -> Partitioned Seq Scan on normal_date_part p (cost=0.00..455.00 rows=1 width=8) (actual time=27228.532..27261.944 rows=10000 loops=3310000) Filter: (id = n.id) Rows Removed by Filter: 99990000 Selected Partitions: 1..331 Total runtime: 42947.153 ms (15 rows) ``` ## 优化说明 很明显,执行计划中存在SubPlan,并且SubPlan中的运算相当重,即此SubPlan是一个明确的性能瓶颈点。 根据SQL语意等价改写SQL消除SubPlan如下: ``` update normal_date n set time = p.time from normal_date_part p where p.id = n.id; ``` --- --- url: >- /zh/docs/latest/performance_tuning_guide/case_rewriting_sql_and_deleting_subqueries_2.md --- # **案例:改写SQL消除子查询(案例2)** ## 现象描述 如下SQL语句: ``` UPDATE normal_date n SET time = ( SELECT time FROM normal_date_part p WHERE p.id = n.id ) WHERE EXISTS (SELECT 1 FROM normal_date_part n2 WHERE n2.id = n.id); ``` 计划为: ``` QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Update on normal_date n (cost=224.40..2334150.22 rows=5129 width=16) (actual time=17.336..42944.734 rows=10000 loops=1) -> Hash Semi Join (cost=224.40..2334150.22 rows=5129 width=16) (actual time=16.997..42852.967 rows=10000 loops=1) Hash Cond: (n.id = n2.id) -> Seq Scan on normal_date n (cost=0.00..160.29 rows=5129 width=10) (actual time=0.113..7.271 rows=10000 loops=1) -> Hash (cost=160.29..160.29 rows=5129 width=10) (actual time=7.381..7.381 rows=10000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 430kB -> Seq Scan on normal_date n2 (cost=0.00..160.29 rows=5129 width=10) (actual time=0.052..3.501 rows=10000 loops=1) SubPlan 1 -> Partition Iterator (cost=0.00..455.00 rows=1 width=8) (actual time=21006.481..42756.884 rows=10000 loops=10000) Iterations: 331 -> Partitioned Seq Scan on normal_date_part p (cost=0.00..455.00 rows=1 width=8) (actual time=27228.532..27261.944 rows=10000 loops=3310000) Filter: (id = n.id) Rows Removed by Filter: 99990000 Selected Partitions: 1..331 Total runtime: 42947.153 ms (15 rows) ``` ## 优化说明 很明显,执行计划中存在SubPlan,并且SubPlan中的运算相当重,即此SubPlan是一个明确的性能瓶颈点。 根据SQL语意等价改写SQL消除SubPlan如下: ``` update normal_date n set time = p.time from normal_date_part p where p.id = n.id; ``` --- --- url: >- /zh/docs/latest-lite/performance_tuning_guide/case_rewrite_sql_to_eliminate_subqueries_and_utilize_parallel_query_execution.md --- # **案例:改写SQL消除子查询与使用并行查询** ## 现象描述 如下复杂连表查询语句,存在多个子查询,存在性能问题,耗时23秒多。 ```sql SELECT count( a.id ) AS newsCount, a.type1 AS type, a.NAME AS typeName, ifnull( a.parentType, '0' ) AS parentType, a.columnType AS columnType, ( SELECT NAME FROM t_column WHERE type = a.parentType ) AS parentTypeName, SUM( a.countRead1 ) AS countRead, SUM( a.countComment1 ) AS countComment, SUM( a.countShare1 ) AS countShare, SUM( a.countCollect1 ) AS countCollect FROM ( SELECT i.id AS id, i.type AS type1, m.NAME AS NAME, m.parent_type AS parentType, m.column_type AS columnType, ( SELECT count(*) FROM t_new_bor_hi h WHERE h.STATUS = 'Y' AND h.new_id = i.id ) countRead1, ( SELECT count(*) FROM t_news_comment c WHERE c.STATUS = 'Y' AND c.newsId = i.id ) countComment1, ( SELECT count(*) FROM t_news_share s WHERE s.STATUS = 'Y' AND s.new_id = i.id ) countShare1, ( SELECT count(*) FROM t_collect co WHERE co.STATUS = 'Y' AND co.news_id = i.id ) countCollect1 FROM t_news_info i JOIN t_column m ON m.type = i.type AND m.STATUS = 'Y' WHERE NAME IS NOT NULL AND i.STATUS = 'Y' and i.type is not null ) a GROUP BY a.type1; ``` ## 优化分析 原始SQL执行计划如下: ![original\_plan](figures/perf_case-sql_smp-original_plan.png) 根据执行计划可知,此SQL存在大量子查询,且大部分耗时为以下部分: ```sql SELECT i.id AS id, i.type AS type1, m.NAME AS NAME, m.parent_type AS parentType, m.column_type AS columnType, ( SELECT count(*) FROM t_new_bor_hi h WHERE h.STATUS = 'Y' AND h.new_id = i.id ) countRead1, ( SELECT count(*) FROM t_news_comment c WHERE c.STATUS = 'Y' AND c.newsId = i.id ) countComment1, ( SELECT count(*) FROM t_news_share s WHERE s.STATUS = 'Y' AND s.new_id = i.id ) countShare1, ( SELECT count(*) FROM t_collect co WHERE co.STATUS = 'Y' AND co.news_id = i.id ) countCollect1 FROM t_news_info i JOIN t_Column m ON m.type = i.type AND m.STATUS = 'Y' WHERE NAME IS NOT NULL AND i.STATUS = 'Y' and i.type is not null ``` 子查询执行计划: ![original\_subplan](figures/perf_case-sql_smp-original_subplan.png) 在这种场景下,改写消除子查询无明显性能提升,由于并行查询(SMP)不支持子查询算子,因此原 SQL 也无法直接使用并行查询。 此时需要先改造SQL,消除子查询才能使用并行特性。 将外层的 FROM 子句里面的以下子查询: ```sql ( SELECT count(*) FROM t_new_bor_hi h WHERE h.STATUS = 'Y' AND h.new_id = i.id ) countRead1, ( SELECT count(*) FROM t_news_comment c WHERE c.STATUS = 'Y' AND c.newsId = i.id ) countComment1, ( SELECT count(*) FROM t_news_share s WHERE s.STATUS = 'Y' AND s.new_id = i.id ) countShare1, ( SELECT count(*) FROM t_collect co WHERE co.STATUS = 'Y' AND co.news_id = i.id ) countCollect1 ``` 调整到外层 SELECT 部分后,得到新的 SQL 如下(为了方便比较结果,加上了order by): ```sql SELECT count( a.id ) AS newsCount, a.type1 AS type, a.NAME AS typeName, ifnull( a.parentType, '0' ) AS parentType, a.columnType AS columnType, ( SELECT NAME FROM t_column WHERE type = a.parentType ) AS parentTypeName, SUM( (SELECT count(*) FROM t_new_bor_hi h WHERE h.STATUS = 'Y' AND h.new_id = a.id) ) AS countRead, SUM( (SELECT count( c.id ) FROM t_news_comment c WHERE c.STATUS = 'Y' AND c.newsId = a.id) ) AS countComment, SUM( (SELECT count( s.id ) FROM t_news_share s WHERE s.STATUS = 'Y' AND s.new_id = a.id) ) AS countShare, SUM( (SELECT count( co.id ) FROM t_collect co WHERE co.STATUS = 'Y' AND co.news_id = a.id) ) AS countCollect FROM ( SELECT i.id AS id, i.type AS type1, m.NAME AS NAME, m.parent_type AS parentType, m.column_type AS columnType FROM t_news_info i LEFT JOIN t_column m ON m.type = i.type AND m.STATUS = 'Y' WHERE NAME IS NOT NULL AND i.STATUS ='Y' and i.type is not null ) a GROUP BY a.type1 order by newsCount; ``` 同时作以下参数配置: * 设置会话级并⾏参数,开启并行: ```sql set query_dop = 4; ``` * 设置会话级SQL rewirte参数: ```sql set rewrite_rule='magicset,intargetlist'; ``` 最终执行计划如下: ![perf\_case-sql\_smp-final\_plan\_p1](figures/perf_case-sql_smp-final_plan_p1.png) ![perf\_case-sql\_smp-final\_plan\_p2](figures/perf_case-sql_smp-final_plan_p2.png) 相比原SQL,加上了 order by 后,耗时也只有4秒左右,性能提升约 5 倍。 经比较验证,结果正确。 --- --- url: >- /zh/docs/latest/performance_tuning_guide/case_rewrite_sql_to_eliminate_subqueries_and_utilize_parallel_query_execution.md --- # **案例:改写SQL消除子查询与使用并行查询** ## 现象描述 如下复杂连表查询语句,存在多个子查询,存在性能问题,耗时23秒多。 ```sql SELECT count( a.id ) AS newsCount, a.type1 AS type, a.NAME AS typeName, ifnull( a.parentType, '0' ) AS parentType, a.columnType AS columnType, ( SELECT NAME FROM t_column WHERE type = a.parentType ) AS parentTypeName, SUM( a.countRead1 ) AS countRead, SUM( a.countComment1 ) AS countComment, SUM( a.countShare1 ) AS countShare, SUM( a.countCollect1 ) AS countCollect FROM ( SELECT i.id AS id, i.type AS type1, m.NAME AS NAME, m.parent_type AS parentType, m.column_type AS columnType, ( SELECT count(*) FROM t_new_bor_hi h WHERE h.STATUS = 'Y' AND h.new_id = i.id ) countRead1, ( SELECT count(*) FROM t_news_comment c WHERE c.STATUS = 'Y' AND c.newsId = i.id ) countComment1, ( SELECT count(*) FROM t_news_share s WHERE s.STATUS = 'Y' AND s.new_id = i.id ) countShare1, ( SELECT count(*) FROM t_collect co WHERE co.STATUS = 'Y' AND co.news_id = i.id ) countCollect1 FROM t_news_info i JOIN t_column m ON m.type = i.type AND m.STATUS = 'Y' WHERE NAME IS NOT NULL AND i.STATUS = 'Y' and i.type is not null ) a GROUP BY a.type1; ``` ## 优化分析 原始SQL执行计划如下: ![original\_plan](figures/perf_case-sql_smp-original_plan.png) 根据执行计划可知,此SQL存在大量子查询,且大部分耗时为以下部分: ```sql SELECT i.id AS id, i.type AS type1, m.NAME AS NAME, m.parent_type AS parentType, m.column_type AS columnType, ( SELECT count(*) FROM t_new_bor_hi h WHERE h.STATUS = 'Y' AND h.new_id = i.id ) countRead1, ( SELECT count(*) FROM t_news_comment c WHERE c.STATUS = 'Y' AND c.newsId = i.id ) countComment1, ( SELECT count(*) FROM t_news_share s WHERE s.STATUS = 'Y' AND s.new_id = i.id ) countShare1, ( SELECT count(*) FROM t_collect co WHERE co.STATUS = 'Y' AND co.news_id = i.id ) countCollect1 FROM t_news_info i JOIN t_Column m ON m.type = i.type AND m.STATUS = 'Y' WHERE NAME IS NOT NULL AND i.STATUS = 'Y' and i.type is not null ``` 子查询执行计划: ![original\_subplan](figures/perf_case-sql_smp-original_subplan.png) 在这种场景下,改写消除子查询无明显性能提升,由于并行查询(SMP)不支持子查询算子,因此原 SQL 也无法直接使用并行查询。 此时需要先改造SQL,消除子查询才能使用并行特性。 将外层的 FROM 子句里面的以下子查询: ```sql ( SELECT count(*) FROM t_new_bor_hi h WHERE h.STATUS = 'Y' AND h.new_id = i.id ) countRead1, ( SELECT count(*) FROM t_news_comment c WHERE c.STATUS = 'Y' AND c.newsId = i.id ) countComment1, ( SELECT count(*) FROM t_news_share s WHERE s.STATUS = 'Y' AND s.new_id = i.id ) countShare1, ( SELECT count(*) FROM t_collect co WHERE co.STATUS = 'Y' AND co.news_id = i.id ) countCollect1 ``` 调整到外层 SELECT 部分后,得到新的 SQL 如下(为了方便比较结果,加上了order by): ```sql SELECT count( a.id ) AS newsCount, a.type1 AS type, a.NAME AS typeName, ifnull( a.parentType, '0' ) AS parentType, a.columnType AS columnType, ( SELECT NAME FROM t_column WHERE type = a.parentType ) AS parentTypeName, SUM( (SELECT count(*) FROM t_new_bor_hi h WHERE h.STATUS = 'Y' AND h.new_id = a.id) ) AS countRead, SUM( (SELECT count( c.id ) FROM t_news_comment c WHERE c.STATUS = 'Y' AND c.newsId = a.id) ) AS countComment, SUM( (SELECT count( s.id ) FROM t_news_share s WHERE s.STATUS = 'Y' AND s.new_id = a.id) ) AS countShare, SUM( (SELECT count( co.id ) FROM t_collect co WHERE co.STATUS = 'Y' AND co.news_id = a.id) ) AS countCollect FROM ( SELECT i.id AS id, i.type AS type1, m.NAME AS NAME, m.parent_type AS parentType, m.column_type AS columnType FROM t_news_info i LEFT JOIN t_column m ON m.type = i.type AND m.STATUS = 'Y' WHERE NAME IS NOT NULL AND i.STATUS ='Y' and i.type is not null ) a GROUP BY a.type1 order by newsCount; ``` 同时作以下参数配置: * 设置会话级并⾏参数,开启并行: ```sql set query_dop = 4; ``` * 设置会话级SQL rewirte参数: ```sql set rewrite_rule='magicset,intargetlist'; ``` 最终执行计划如下: ![perf\_case-sql\_smp-final\_plan\_p1](figures/perf_case-sql_smp-final_plan_p1.png) ![perf\_case-sql\_smp-final\_plan\_p2](figures/perf_case-sql_smp-final_plan_p2.png) 相比原SQL,加上了 order by 后,耗时也只有4秒左右,性能提升约 5 倍。 经比较验证,结果正确。 --- --- url: >- /zh/docs/latest-lite/performance_tuning_guide/case_reconstructing_partitioned_tables.md --- # **案例:改建分区表** ## 现象描述 如下简单SQL语句查询, 性能瓶颈点在normal\_date的Scan上。 ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------- Seq Scan on normal_date (cost=0.00..259.00 rows=30 width=12) (actual time=0.100..3.466 rows=30 loops=1) Filter: (("time" >= '2022-09-01 00:00:00'::timestamp without time zone) AND ("time" <= '2022-10-01 00:00:00'::timestamp without time zone)) Rows Removed by Filter: 9970 Total runtime: 3.587 ms (4 rows) ``` ## 优化分析 从业务层确认表数据(在time字段上)有明显的日期特征,符合分区表的特征。重新规划normal\_date表的表定义:字段time为分区键、月为间隔单位定义分区表normal\_date\_part。修改后结果如下,性能提升近10倍。 ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------- Partition Iterator (cost=0.00..480.00 rows=30 width=12) (actual time=0.038..0.085 rows=30 loops=1) Iterations: 2 -> Partitioned Seq Scan on normal_date_part (cost=0.00..480.00 rows=30 width=12) (actual time=0.049..0.063 rows=30 loops=2) Filter: (("time" >= '2022-09-01 00:00:00'::timestamp without time zone) AND ("time" <= '2022-10-01 00:00:00'::timestamp without time zone)) Rows Removed by Filter: 31 Selected Partitions: 3..4 Total runtime: 0.360 ms (7 rows) ``` --- --- url: >- /zh/docs/latest/performance_tuning_guide/case_reconstructing_partitioned_tables.md --- # **案例:改建分区表** ## 现象描述 如下简单SQL语句查询, 性能瓶颈点在normal\_date的Scan上。 ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------- Seq Scan on normal_date (cost=0.00..259.00 rows=30 width=12) (actual time=0.100..3.466 rows=30 loops=1) Filter: (("time" >= '2022-09-01 00:00:00'::timestamp without time zone) AND ("time" <= '2022-10-01 00:00:00'::timestamp without time zone)) Rows Removed by Filter: 9970 Total runtime: 3.587 ms (4 rows) ``` ## 优化分析 从业务层确认表数据(在time字段上)有明显的日期特征,符合分区表的特征。重新规划normal\_date表的表定义:字段time为分区键、月为间隔单位定义分区表normal\_date\_part。修改后结果如下,性能提升近10倍。 ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------- Partition Iterator (cost=0.00..480.00 rows=30 width=12) (actual time=0.038..0.085 rows=30 loops=1) Iterations: 2 -> Partitioned Seq Scan on normal_date_part (cost=0.00..480.00 rows=30 width=12) (actual time=0.049..0.063 rows=30 loops=2) Filter: (("time" >= '2022-09-01 00:00:00'::timestamp without time zone) AND ("time" <= '2022-10-01 00:00:00'::timestamp without time zone)) Rows Removed by Filter: 31 Selected Partitions: 3..4 Total runtime: 0.360 ms (7 rows) ``` --- --- url: /en/docs/latest-lite/sql_reference/_pg_foreign_data_wrappers.md --- # \_PG\_FOREIGN\_DATA\_WRAPPERS **\_PG\_FOREIGN\_DATA\_WRAPPERS** displays information about a foreign-data wrapper. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_FOREIGN\_DATA\_WRAPPERS columns --- --- url: /en/docs/latest/sql_reference/_pg_foreign_data_wrappers.md --- # \_PG\_FOREIGN\_DATA\_WRAPPERS **\_PG\_FOREIGN\_DATA\_WRAPPERS** displays information about a foreign-data wrapper. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_FOREIGN\_DATA\_WRAPPERS columns --- --- url: /zh/docs/latest-lite/sql_reference/_pg_foreign_data_wrappers.md --- # \_PG\_FOREIGN\_DATA\_WRAPPERS 显示外部数据封装器的信息。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_FOREIGN\_DATA\_WRAPPERS字段 --- --- url: /zh/docs/latest/sql_reference/_pg_foreign_data_wrappers.md --- # \_PG\_FOREIGN\_DATA\_WRAPPERS 显示外部数据封装器的信息。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_FOREIGN\_DATA\_WRAPPERS字段 --- --- url: /en/docs/latest-lite/sql_reference/_pg_foreign_servers.md --- # \_PG\_FOREIGN\_SERVERS **\_PG\_FOREIGN\_SERVERS** displays information about a foreign server. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_FOREIGN\_SERVERS columns --- --- url: /en/docs/latest/sql_reference/_pg_foreign_servers.md --- # \_PG\_FOREIGN\_SERVERS **\_PG\_FOREIGN\_SERVERS** displays information about a foreign server. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_FOREIGN\_SERVERS columns --- --- url: /zh/docs/latest-lite/sql_reference/_pg_foreign_servers.md --- # \_PG\_FOREIGN\_SERVERS 显示外部服务器的信息。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_FOREIGN\_SERVERS字段 --- --- url: /zh/docs/latest/sql_reference/_pg_foreign_servers.md --- # \_PG\_FOREIGN\_SERVERS 显示外部服务器的信息。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_FOREIGN\_SERVERS字段 --- --- url: /en/docs/latest-lite/sql_reference/_pg_foreign_table_columns.md --- # \_PG\_FOREIGN\_TABLE\_COLUMNS **\_PG\_FOREIGN\_TABLE\_COLUMNS** displays column information about a foreign table. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_FOREIGN\_TABLE\_COLUMNS columns --- --- url: /en/docs/latest/sql_reference/_pg_foreign_table_columns.md --- # \_PG\_FOREIGN\_TABLE\_COLUMNS **\_PG\_FOREIGN\_TABLE\_COLUMNS** displays column information about a foreign table. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_FOREIGN\_TABLE\_COLUMNS columns --- --- url: /zh/docs/latest-lite/sql_reference/_pg_foreign_table_columns.md --- # \_PG\_FOREIGN\_TABLE\_COLUMNS 显示外部表的列信息。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_FOREIGN\_TABLE\_COLUMNS字段 --- --- url: /zh/docs/latest/sql_reference/_pg_foreign_table_columns.md --- # \_PG\_FOREIGN\_TABLE\_COLUMNS 显示外部表的列信息。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_FOREIGN\_TABLE\_COLUMNS字段 --- --- url: /en/docs/latest-lite/sql_reference/_pg_foreign_tables.md --- # \_PG\_FOREIGN\_TABLES **\_PG\_FOREIGN\_TABLES** stores information about all foreign tables defined in the current database, whereas displays information about foreign tables accessible to the current user. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_FOREIGN\_TABLES columns --- --- url: /en/docs/latest/sql_reference/_pg_foreign_tables.md --- # \_PG\_FOREIGN\_TABLES **\_PG\_FOREIGN\_TABLES** stores information about all foreign tables defined in the current database, whereas displays information about foreign tables accessible to the current user. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_FOREIGN\_TABLES columns --- --- url: /zh/docs/latest-lite/sql_reference/_pg_foreign_tables.md --- # \_PG\_FOREIGN\_TABLES 存储所有的定义在本数据库的外部表信息。只显示当前用户有权访问的外部表信息。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_FOREIGN\_TABLES字段 --- --- url: /zh/docs/latest/sql_reference/_pg_foreign_tables.md --- # \_PG\_FOREIGN\_TABLES 存储所有的定义在本数据库的外部表信息。只显示当前用户有权访问的外部表信息。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_FOREIGN\_TABLES字段 --- --- url: /en/docs/latest-lite/sql_reference/_pg_user_mappings.md --- # \_PG\_USER\_MAPPINGS **\_PG\_USER\_MAPPINGS** stores mappings from local users to remote users. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_USER\_MAPPINGS columns --- --- url: /en/docs/latest/sql_reference/_pg_user_mappings.md --- # \_PG\_USER\_MAPPINGS **\_PG\_USER\_MAPPINGS** stores mappings from local users to remote users. Only the sysadmin user has the permission to view this view. **Table 1** \_PG\_USER\_MAPPINGS columns --- --- url: /zh/docs/latest-lite/sql_reference/_pg_user_mappings.md --- # \_PG\_USER\_MAPPINGS 存储从本地用户到远程的映射。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_USER\_MAPPINGS字段 --- --- url: /zh/docs/latest/sql_reference/_pg_user_mappings.md --- # \_PG\_USER\_MAPPINGS 存储从本地用户到远程的映射。该视图只有sysadmin权限可以查看。 **表 1** \_PG\_USER\_MAPPINGS字段 --- --- url: >- /zh/docs/latest/ograc/fault_recovery_issues/issues_during_the_installation_phase/installation_failure_due_to_cm_voting_disk_abnormal.md --- # `CM` 投票盘(`gcc-disk`)异常导致安装失败 ## 现象描述 在两节点或多节点部署场景中,共享存储是最容易引发安装失败的环节,相关问题通常集中在 **`CM` 投票盘** 和 **`DSS` 共享盘** 两类。 本问题主要表现为: * 安装过程中在 **`CM` 阶段失败** * 两节点在初始化或启动 `CM` 时异常退出 * 日志中可能出现心跳写入失败、`load disk` 相关报错 `CM` 阶段安装失败时,`/opt/ograc/log/cms/cms_deploy.log` 中典型报错如下: ```text Exception: failed to set cms node information. command: sh /opt/ograc/action/cms/start_cms.sh -P install cms > /opt/ograc/log/cms/cms_deploy.log 2>&1 output: Execute cms/install.sh cmsctl.py install failed ``` ## 常见原因 * `gcc-disk` 软链接错误 * 两节点的 `gcc-disk` **未指向同一块共享盘** * 投票盘在抹除或初始化阶段无法正常写入 ## 排查与解决建议 1. 确认两节点 `gcc-disk` 指向同一 `LUN` 2. 使用 `/dev/disk/by-id` 等稳定路径重新建立软链接 3. 确认投票盘未被其他业务占用 > **提示**:`CM` 投票盘用于集群仲裁,一旦异常,集群将无法正常启动。 --- --- url: >- /zh/docs/latest/ograc/fault_recovery_issues/issues_during_the_installation_phase/installation_failure_due_to_dss_lun_registration_conflict.md --- # `DSS` `LUN` 注册冲突导致安装失败 ## 现象描述 在两节点或多节点部署场景中,`DSS` 共享盘异常会导致安装失败,常见表现如下: * 安装过程中的 `install` 或 `start` 阶段失败 * `DSS` 组件无法启动 * 在以下日志中出现异常信息: ```text /opt/ograc/log/dss/run/instance.log ``` `DSS` 注册阶段失败时,`/opt/ograc/log/dss/run/instance.log` 中典型报错如下: ```text ERROR [pid: 2127231] [MainThread] [tid:281460975927024] [dssctl.py:596] Reghl node cmd[source ~/.bashrc && /opt/ograc/dss/bin/dsscmd reghl -D /opt/ograc/dss] failed, details: Begin to register, Failed to get vg non entry info when reghl, errcode is -1. detail reason[2031]: The volume group has not been initialized. Failed to register. ``` ## 常见原因 * 共享 `LUN` 已被其他集群或历史环境注册 * 先前安装未正常卸载,残留注册信息 * 其他业务对共享盘进行了 `Persistent Reservation` ## `DSS` `LUN` 注册冲突的排查与清理 ### 查看 `LUN` 注册信息 ```shell sg_persist --in --read-keys /dev/xxx ``` 若返回如下内容,说明该 `LUN` 已存在注册信息: ```text PR generation=0xb6, 2 registered reservation keys follow: 0x1 0x2 ``` ### 清理注册信息 若节点角色发生过调整,或历史安装残留导致 `dsscmd reghl` 注册失败,建议使用当前节点实际使用的 reservation key 先注册当前主机,再执行 `clear` 操作。 `DSS` 节点号与 `SCSI-3 PR` key 的对应关系如下: ```text node_id=0 -> reservation key=1 node_id=1 -> reservation key=2 ``` 例如当前节点作为 `node_id=1` 安装时,使用 key `2` 清理每块共享盘: ```shell sg_persist -n -o -I -S 2 -d /dev/dss-disk1 sg_persist -n -o -I -S 2 -d /dev/dss-disk2 sg_persist -n -o -I -S 2 -d /dev/dss-disk3 sg_persist -n -o -I -S 2 -d /dev/gcc-disk sg_persist -n -o -C -K 2 -d /dev/dss-disk1 sg_persist -n -o -C -K 2 -d /dev/dss-disk2 sg_persist -n -o -C -K 2 -d /dev/dss-disk3 sg_persist -n -o -C -K 2 -d /dev/gcc-disk ``` 命令中的 `/dev/dss-disk1`、`/dev/dss-disk2`、`/dev/dss-disk3`、`/dev/gcc-disk` 为部署配置中的共享盘设备。 其中 `-I -S ` 表示先将当前主机注册为指定 key,`-C -K ` 表示使用该 key 执行 `clear`。`clear` 成功后会清空该 `LUN` 上的 `Persistent Reservation` 注册和预留状态,而不是只删除指定 key。 如果当前节点作为 `node_id=0` 安装,则将上述命令中的 key `2` 替换为 key `1`。 ### 确认清理结果 再次执行: ```shell sg_persist --in --read-keys /dev/xxx ``` 若输出如下内容: ```text there are NO registered reservation keys ``` 说明共享盘注册信息已成功清理,可重新执行安装或启动流程。 --- --- url: /zh/docs/latest-lite/database_reference/gs_auditing_policy_access.md --- # `GS_AUDITING_POLICY_ACCESS` `GS_AUDITING_POLICY_ACCESS` 系统表记录与DML数据库相关操作的统一审计信息。需要有系统管理员或安全策略管理员权限才可以访问此系统表。 **表 1** `GS_AUDITING_POLICY_ACCESS` 字段 --- --- url: /zh/docs/latest/database_reference/gs_auditing_policy_access.md --- # `GS_AUDITING_POLICY_ACCESS` `GS_AUDITING_POLICY_ACCESS` 系统表记录与DML数据库相关操作的统一审计信息。需要有系统管理员或安全策略管理员权限才可以访问此系统表。 **表 1** `GS_AUDITING_POLICY_ACCESS` 字段 --- --- url: /zh/docs/latest-lite/database_reference/gs_auditing_policy.md --- # `GS_AUDITING_POLICY` `GS_AUDITING_POLICY` 系统表记录统一审计的主体信息,每条记录对应一个设计策略。需要有系统管理员或安全策略管理员权限才可以访问此系统表。 **表 1** `GS_AUDITING_POLICY` 字段 --- --- url: /zh/docs/latest/database_reference/gs_auditing_policy.md --- # `GS_AUDITING_POLICY` `GS_AUDITING_POLICY` 系统表记录统一审计的主体信息,每条记录对应一个设计策略。需要有系统管理员或安全策略管理员权限才可以访问此系统表。 **表 1** `GS_AUDITING_POLICY` 字段 --- --- url: /zh/docs/latest-lite/database_reference/gs_masking_policy_filters.md --- # `GS_MASKING_POLICY_FILTERS` `GS_MASKING_POLICY_FILTERS` 系统表记录动态数据脱敏策略对应的用户过滤条件,当用户条件满足FILTER条件时,对应的脱敏策略才会生效。需要有系统管理员或安全策略管理员权限才可以访问此系统表。 **表 1** `GS_MASKING_POLICY_FILTERS`表字段 --- --- url: /zh/docs/latest/database_reference/gs_masking_policy_filters.md --- # `GS_MASKING_POLICY_FILTERS` `GS_MASKING_POLICY_FILTERS` 系统表记录动态数据脱敏策略对应的用户过滤条件,当用户条件满足FILTER条件时,对应的脱敏策略才会生效。需要有系统管理员或安全策略管理员权限才可以访问此系统表。 **表 1** `GS_MASKING_POLICY_FILTERS`表字段 --- --- url: /zh/docs/latest-lite/database_reference/gs_txn_snapshot.md --- # `GS_TXN_SNAPSHOT` `GS_TXN_SNAPSHOT` 是“时间戳-CSN”映射表,周期性采样,并维护适当的时间范围,用于估算范围内的时间戳对应的CSN值。 **表 1** `GS_TXN_SNAPSHOT` 字段 --- --- url: /zh/docs/latest/database_reference/gs_txn_snapshot.md --- # `GS_TXN_SNAPSHOT` `GS_TXN_SNAPSHOT` 是“时间戳-CSN”映射表,周期性采样,并维护适当的时间范围,用于估算范围内的时间戳对应的CSN值。 示例: ```sql openGauss=# select * from gs_txn_snapshot; snptime | snpxmin | snpcsn | snpsnapshot ---------+---------+--------+------------- ``` **表 1** `GS_TXN_SNAPSHOT` 字段 --- --- url: /zh/docs/latest/data_migration_guide/oracle2ograc_migration.md --- # 1. 概述 ## 1.1 目的 本文旨在对openGauss-FullReplicate工具进行介绍,指导用户如何完成工具安装、并使用工具完成数据迁移,具体支持迁移的迁移类型如下: * 从 Oracle 迁移至 oGRAC ## 1.2 openGauss-FullReplicate工具介绍 openGauss-FullReplicate是一个用Java编写的数据迁移工具。该工具提供了全量数据和对象的迁移能力,全量数据迁移采用多表并行迁移, 全量对象支持表、约束、索引、外键、视图、函数、触发器、存储过程和序列的迁移。 ## 1.3 注意事项 ### 1.3.1 一般性限制 * 创建 oGRAC 目标端数据库时,需要指定数据库编码格式与源端一致,并确保源端与目标端时区一致性 ### 1.3.2 对象迁移限制 * 由于内核兼容性在持续增强,对象迁移采用先透传再翻译的原则进行,即先直接透传对象创建语句在 oGRAC 端执行,若执行失败,再借助开源三方件druid进行翻译。 ### 1.3.3 Oracle迁移限制 * 要求Oracle版本为19 * 虚拟列(Virtual Column)在迁移时会自动过滤,不迁移到目标端 * 引用分区表(基于外键关系分区)暂不支持迁移 * 系统分区表(应用程序控制分区)暂不支持迁移 * 虚拟列分区表(基于虚拟列分区)暂不支持迁移 * 函数索引(Function-based Index)仅支持部分函数表达式 * 几何类型(geometry和geography)暂不支持迁移 * 视图、函数、触发器和存储过程目前仅支持迁移流程,迁移成功还需语法兼容 * 不支持oracle物化视图迁移(Materialized View) ### 1.3.4 迁移前准备 为了确保迁移过程的效率和准确性,建议在迁移前执行以下操作: 1. **更新Oracle表统计信息**:执行以下命令更新指定schema的表统计信息,这将有助于DataX生成更优的执行计划: ```sql EXEC DBMS_STATS.GATHER_SCHEMA_STATS('YOUR_SCHEMA_NAME', cascade=>TRUE); SELECT table_name, num_rows, last_analyzed FROM user_tables; ``` 其中 `YOUR_SCHEMA_NAME` 是您要迁移的Oracle schema名称。 2. **检查表空间使用情况**:确保目标端oGRAC数据库有足够的表空间用于迁移操作。 ### 1.3.5 迁移进度 迁移过程中,工具会记录迁移进度。迁移完成后,工具会在 `process/` 目录下生成多个JSON文件,记录各类对象的迁移进度和详情。 **process/ 目录下的文件列表:** * `datax_table.json` - 表迁移进度 * `primarykey.json` - 主键迁移进度 * `foreignkey.json` - 外键迁移进度 * `index.json` - 索引迁移进度 * `constraint.json` - 约束迁移进度 * `view.json` - 视图迁移进度 * `function.json` - 函数迁移进度 * `trigger.json` - 触发器迁移进度 * `procedure.json` - 存储过程迁移进度 * `sequence.json` - 序列迁移进度 * `migration_error.log` - 迁移错误日志 进度本身发生异常不影响整体迁移流程。另外migration\_error.log 迁移错误日志不区分对象类型,所有对象迁移错误都会记录在该文件中。 # 2. 安装方法 ## 2.1 安装环境要求 由于工具使用Java编写,因此需要提前安装Java运行环境,版本要求Java 17+。 ## 2.2 安装包下载 安装包下载地址:https://opengauss.obs.cn-south-1.myhuaweicloud.com/latest/tools/openGauss-FullReplicate-7.0.0-RC3.tar.gz 其中7.0.0-RC3表示当前版本号。 ```bash wget https://opengauss.obs.cn-south-1.myhuaweicloud.com/latest/tools/openGauss-FullReplicate-7.0.0-RC3.tar.gz ``` ## 2.3 安装包解压 下载完成后,解压压缩包。 ``` tar -zxvf openGauss-FullReplicate-7.0.0-RC3.tar.gz ``` 解压后参考目录如下: ```text openGauss-FullReplicate/ openGauss-FullReplicate/config/ openGauss-FullReplicate/config/config.yml openGauss-FullReplicate/build_commit_id.log openGauss-FullReplicate/openGauss-FullReplicate-7.0.0-RC3.jar ``` 其中openGauss-FullReplicate-7.0.0-RC3.jar为工具的主程序,config文件夹下为配置文件模板。 # 3. 配置文件说明 配置文件使用yaml文件规则配置,需要特别注意对齐,缩进表示层级关系,缩进时不允许使用Tab键,只允许使用空格,缩进的空格数目不重要,但相同层级的元素左侧需要对齐。 数据库用户名称使用大写用户名。 ```yaml # global settings # 是否记录进度 isDumpJson: true # 进度文件地址 statusDir: ./process # 目标数据库类型,如:opengauss, ograc targetType: ograc # 目标端数据库配置 ogConn: host: "192.168.0.2" port: 1611 # ograc 用户名 使用大写用户名 user: "username" password: "password" database: "database" charset: "utf8" params: sourceConfig: # 查询表的线程数 readerNum: 4 # 写表的线程数 writerNum: 4 # 线程队列容量 threadQueueCapacity: 20000 # 源端数据库连接信息 dbConn: host: "192.168.0.1" port: "1521" # oracle 用户名 使用大写用户名 user: "SCOTT" password: "password" database: "ORCL" charset: 'utf8' connectTimeout: 10 # schema映射关系 schemaMappings: SCOTT: ogtest datax: dataxHome: datax enableKeepDataXTemporaryConfig: true enableOutputDataxLogs: false ``` ## 配置参数详细信息 ### 全局配置参数 | 参数名 | 类型 | 必填 | 默认值 | 描述 | | :------------- | :------ | :--- | :----- | :----------------------------------- | | `isDumpJson` | Boolean | 是 | - | 是否记录进度 | | `statusDir` | String | 否 | - | 进度文件地址 | | `targetType` | String | 否 | - | 目标数据库类型,如:opengauss, ograc | | `ogConn` | Object | 是 | - | OGRAC数据库连接配置 | | `sourceConfig` | Object | 是 | - | 源数据库配置 | | `datax` | Object | 否 | - | DataX配置 | ### 数据库连接配置 (DatabaseConfig) | 参数名 | 类型 | 必填 | 默认值 | 描述 | | :--------------- | :------ | :--- | :----- | :----------------- | | `host` | String | 是 | - | 数据库主机地址 | | `port` | Integer | 是 | - | 数据库端口 | | `user` | String | 是 | - | 数据库用户名 | | `password` | String | 是 | - | 数据库密码 | | `database` | String | 是 | - | 数据库名称 | | `charset` | String | 否 | - | 字符集 | | `connectTimeout` | Integer | 否 | - | 连接超时时间(秒) | | `params` | Object | 否 | - | 其他连接参数 | ### 源数据库配置 (SourceConfig) | 参数名 | 类型 | 必填 | 默认值 | 描述 | | :-------------------- | :------ | :--- | :----- | :----------------- | | `readerNum` | Integer | 是 | - | 查询表的线程数 | | `writerNum` | Integer | 是 | - | 写表的线程数 | | `threadQueueCapacity` | Integer | 否 | - | 线程队列容量 | | `dbConn` | Object | 是 | - | 源端数据库连接信息 | | `schemaMappings` | Object | 是 | - | schema映射关系 | ### DataX配置 (DataXParamConfig) | 参数名 | 类型 | 必填 | 默认值 | 描述 | | :------------------------------- | :------ | :--- | :----- | :-------------------- | | `dataxHome` | String | 否 | - | DataX主目录 | | `readerName` | String | 否 | - | 读取器名称 | | `writerName` | String | 否 | - | 写入器名称 | | `channel` | Integer | 否 | - | 通道数 | | `errorRecordLimit` | Integer | 否 | - | 错误记录限制 | | `errorPercentageLimit` | Double | 否 | - | 错误百分比限制 | | `readBatchSize` | Integer | 否 | - | 读取批大小 | | `readTimeout` | Integer | 否 | - | 读取超时 | | `writeBatchSize` | Integer | 否 | - | 写入批大小 | | `writeTimeout` | Integer | 否 | - | 写入超时 | | `enableBatchWrite` | Boolean | 否 | - | 是否启用批写入 | | `enablePrepareStatement` | Boolean | 否 | - | 是否启用预处理语句 | | `batchWriteSize` | Integer | 否 | - | 批写入大小 | | `retryTimes` | Integer | 否 | - | 重试次数 | | `retryInterval` | Integer | 否 | - | 重试间隔 | | `enableKeepDataXTemporaryConfig` | Boolean | 否 | false | 是否保留DataX临时配置 | | `enableOutputDataxLogs` | Boolean | 否 | false | 是否输出DataX日志 | # 4. 迁移命令 完成配置文件配置后,即可开始迁移,迁移命令参考如下: 其中, --start参数为迁移的对象类型,--source参数为源端数据库类型,支持oracle,--config参数为配置文件路径。 迁移命令不支持并行执行(同时执行表,索引等迁移命令) ## 4.1 Oracle迁移命令 ```bash # 迁移表 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start datax_table --source oracle --config /**/**/config.yml # 迁移主键 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start primarykey --source oracle --config /**/**/config.yml # 迁移外键 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start foreignkey --source oracle --config /**/**/config.yml # 迁移索引 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start index --source oracle --config /**/**/config.yml # 迁移约束 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start constraint --source oracle --config /**/**/config.yml # 迁移视图 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start view --source oracle --config /**/**/config.yml # 迁移函数 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start function --source oracle --config /**/**/config.yml # 迁移触发器 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start trigger --source oracle --config /**/**/config.yml # 迁移存储过程 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start procedure --source oracle --config /**/**/config.yml # 迁移序列 java -jar openGauss-FullReplicate-7.0.0-RC3.jar --start sequence --source oracle --config /**/**/config.yml ``` # 5. 默认的类型转换规则 ## 5.1 列类型转换 | Oracle | oGRAC | 备注 | | :-------------------------------- | :-------------------------------- | :--------------------------------------------------- | | **数值类型** | | | | NUMBER | NUMBER | 保持精度 | | NUMBER | BIGINT | 自增类型 | | NUMBER(p) | NUMBER(p) | 保持精度 | | NUMBER(p,s) | NUMBER(p,s) | 保持精度和小数位 | | FLOAT | DOUBLE PRECISION | 转换为DOUBLE PRECISION | | FLOAT(n) | DECIMAL(38, 12) | 转换为DECIMAL(38, 12) | | BINARY\_FLOAT | BINARY\_FLOAT | 类型名称一致 | | BINARY\_DOUBLE | BINARY\_DOUBLE | 类型名称一致 | | DOUBLE PRECISION | DOUBLE PRECISION | 类型名称一致 | | **字符串类型** | | | | CHAR(n) | CHAR(n) | 保持长度,默认为BYTE | | CHAR(n CHAR) | CHAR(n CHAR) | 保持原类型,保持CHAR语义 | | VARCHAR2(n) | VARCHAR2(n BYTE) | 保持长度,默认为BYTE | | VARCHAR2(n CHAR) | VARCHAR2(n CHAR) | 保持CHAR语义 | | NCHAR(n) | NCHAR(n) | 保持原样 | | NVARCHAR2(n CHAR) | NVARCHAR2(n CHAR) | 保持原样 | | CLOB | CLOB | 类型名称一致 | | NCLOB | CLOB | 转换为CLOB | | **大对象类型** | | | | BLOB | BLOB | 类型名称一致 | | NBLOB | BLOB | 转换为BLOB | | RAW(n) | RAW(n) | 保持原类型,包含长度信息 | | LONG RAW | BLOB | 转换为BLOB | | BFILE | | 不兼容,抛出异常 | | **日期时间类型** | | | | DATE | DATETIME | 类型转换 | | TIMESTAMP | TIMESTAMP | 类型名称一致 | | TIMESTAMP(p) | TIMESTAMP(p) | 当精度<=6时保持原类型 | | TIMESTAMP(p) | TIMESTAMP(6) | 当精度>6时转换为TIMESTAMP(6) | | TIMESTAMP WITH TIME ZONE | TIMESTAMP WITH TIME ZONE | 类型名称一致 | | TIMESTAMP(p) WITH TIME ZONE | TIMESTAMP(p) WITH TIME ZONE | 当精度<=6时保持原类型 | | TIMESTAMP(p) WITH TIME ZONE | TIMESTAMP(6) WITH TIME ZONE | 当精度>6时转换为TIMESTAMP(6) WITH TIME ZONE | | TIMESTAMP WITH LOCAL TIME ZONE | TIMESTAMP WITH LOCAL TIME ZONE | 类型名称一致 | | TIMESTAMP(p) WITH LOCAL TIME ZONE | TIMESTAMP(p) WITH LOCAL TIME ZONE | 当精度<=6时保持原类型 | | TIMESTAMP(p) WITH LOCAL TIME ZONE | TIMESTAMP(6) WITH LOCAL TIME ZONE | 当精度>6时转换为TIMESTAMP(6) WITH LOCAL TIME ZONE | | INTERVAL YEAR TO MONTH | INTERVAL YEAR TO MONTH | 类型名称一致 | | INTERVAL YEAR(n) TO MONTH | INTERVAL YEAR(4) TO MONTH | 当长度>4时转换为INTERVAL YEAR(4) TO MONTH | | INTERVAL DAY TO SECOND | INTERVAL DAY TO SECOND | 类型名称一致 | | INTERVAL DAY(n) TO SECOND(m) | INTERVAL DAY(n) TO SECOND(m) | 当长度<=6且精度<=6时保持原类型 | | INTERVAL DAY(n) TO SECOND(m) | INTERVAL DAY(6) TO SECOND(6) | 当长度>6或精度>6时转换为INTERVAL DAY(6) TO SECOND(6) | | **特殊类型** | | | | XMLTYPE | | 转换为Clob | | JSON | | 不兼容,抛出异常 | | ANYDATA | | 不兼容,抛出异常 | ## 5.2 索引类型转换 | Oracle | oGRAC | 备注 | | :------------------- | :-------------- | :----------------------------- | | **标准索引** | | | | B-tree Index | B-tree Index | 完全兼容 | | Unique Index | Unique Index | 完全兼容 | | Non-Unique Index | B-tree Index | 完全兼容 | | **特殊索引** | | | | Reverse Key Index | B-tree Index | 完全兼容 | | Function-based Index | Function Index | 部分兼容,仅支持特定函数 | | Composite Index | Composite Index | 完全兼容,复合索引最多支持16列 | | Bitmap Index | B-tree Index | 转为普通索引 | | **不支持的索引** | | | | Full-Text Index | - | 不兼容,Oracle Text索引 | | Domain Index | - | 不兼容,如CTXSYS.CONTEXT | | Spatial Index | Gist Index | 不兼容 | | XML Index | - | 不兼容 | | Filtered Index | Partial Index | 不兼容 | ### 5.2.1 函数索引支持的函数列表 oGRAC函数索引仅支持以下函数表达式: | 函数名 | 说明 | 示例 | | :------------ | :----------------- | :----------------------------------------------------- | | ABS | 绝对值 | ABS(num\_col) | | CHARTOROWID | 字符串转ROWID | CHARTOROWID(rowid\_str\_col) | | DECODE | 条件判断 | DECODE(int\_col, 0, 'ZERO', 1, 'ONE', 'OTHER') | | LOWER | 转小写 | LOWER(char\_col) | | NVL | 空值替换 | NVL(nullable\_col, 0) | | NVL2 | 空值条件替换 | NVL2(nullable\_col, 1, 0) | | REGEXP\_INSTR | 正则表达式匹配位置 | REGEXP\_INSTR(text\_col, 'word') | | REGEXP\_SUBSTR | 正则表达式提取子串 | REGEXP\_SUBSTR(text\_col, '\[a-zA-Z]+') | | REVERSE | 字符串反转 | REVERSE(char\_col) | | SUBSTR | 字符串截取 | SUBSTR(text\_col, 1, 20) | | SUBSTRB | 字节截取 | SUBSTRB(text\_col, 1, 20) | | TO\_CHAR | 转字符串 | TO\_CHAR(date\_col) | | TO\_DATE | 转日期 | TO\_DATE(TO\_CHAR(date\_col, 'yyyy-mm-dd'), 'yyyy-mm-dd') | | TO\_NUMBER | 转数字 | TO\_NUMBER(TO\_CHAR(num\_col)) | | TRIM | 去除空格 | TRIM(text\_col) | | TRUNC | 数字截断 | TRUNC(num\_col) | | TRUNC | 日期截断 | TRUNC(date\_col, 'yyyy') | | UPPER | 转大写 | UPPER(char\_col) | ### 5.2.2 函数索引不支持的函数列表 oGRAC函数索引不支持以下函数表达式用法: | 函数名 | 说明 | 原因 | | :-------------------- | :------------- | :--------------- | | `upper('constant')` | 常量转大写 | 不支持常量表达式 | | `nvl(c_text,c_test2)` | 多参数空值替换 | 暂不支持 | | `upper(c_json_lob)` | JSON LOB转大写 | 不支持LOB类型 | | `nvm(c_arr,c_arr)` | 数组空值替换 | 不支持数组类型 | ### 5.3 主键迁移说明 #### 5.3.1 普通主键迁移 普通主键(非自增主键)直接迁移到oGRAC数据库,保持原有的数据类型和约束定义。 #### 5.3.2 Oracle自增主键迁移 Oracle的自增主键(IDENTITY列)迁移到oGRAC时遵循以下规则: **数据类型转换:** * Oracle `NUMBER` 类型的自增列 → oGRAC `BIGINT` 类型 **IDENTITY模式转换:** | Oracle 定义 | oGRAC 转换结果 | 说明 | | ------------------------------------------------------------ | ---------------------------------------------------- | ---------------------------------- | | `colName NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY` | `colName BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY` | ALWAYS模式转换为AUTO\_INCREMENT | | `colName NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY` | `colName BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY` | BY DEFAULT模式转换为AUTO\_INCREMENT | **oGRAC自增键约束要求:** * 自增列必须为整数类型(INT/BIGINT) * 自增列必须定义为主键或唯一键 **类型对应关系:** * oGRAC `SERIAL PRIMARY KEY` / `AUTO_INCREMENT NOT NULL PRIMARY KEY` → 对应 Oracle `GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY` **注意事项:** * oGRAC自增类型不支持Oracle的IDENTITY列ALWAYS模式,统一转换为`AUTO_INCREMENT` * 自增列的起始值和步长等属性在迁移时会保留 ### 5.4 分区表迁移 分区表迁移时,分区及子分区对应表空间会根据表空间名称进行映射。如果目标端存在同名表空间,则使用该表空间;若不存在同名表空间,系统会自动去除 TABLESPACE 子句,采用当前用户的默认表空间,无需手动创建分区对应表空间。 ### 5.5 中文编码与乱码问题处理 #### 5.5.1 编码要求 为确保中文数据正确迁移,源端Oracle和目标端oGRAC数据库必须满足以下编码要求: | 数据库 | 编码要求 | 推荐字符集 | | ------ | ------------- | ------------- | | oGRAC | 必须为UTF-8 | UTF-8(默认) | | Oracle | 必须支持UTF-8 | AL32UTF8 | #### 5.5.2 检查Oracle数据库字符集 执行以下SQL检查Oracle数据库字符集: ```sql SELECT USERENV('language') FROM DUAL; ``` **预期输出**: ``` AMERICAN_AMERICA.AL32UTF8 ``` AL32UTF8 是 Oracle 完整的 UTF-8 实现,支持所有 Unicode 字符。 #### 5.5.3 乱码问题排查 **乱码常见原因**: 1. **客户端NLS\_LANG设置不正确**:客户端字符集与服务器不一致 2. **数据已损坏**:使用错误编码插入的数据可能已永久损坏 3. **JDBC连接编码未正确配置**:驱动连接参数encoding/nencoding设置不当 #### 5.5.4 验证数据是否损坏 运行以下命令检查数据是否真的损坏: ```sql SELECT DUMP(column_name, 1016) FROM table_name WHERE condition; ``` **判断结果**: * 如果返回 `3F`(问号 `?` 的ASCII码),说明数据已损坏,需要重新插入 * 如果返回合法的UTF-8字节(例如 `e4 b8 ad e6 96 87` 表示"中文"),说明数据完好,只是显示问题 #### 5.5.5 环境配置 **1. 设置Shell环境变量** ```bash export LANG=C.UTF-8 export LC_ALL=C.UTF-8 echo "export LANG=C.UTF-8" >> ~/.bashrc echo "export LC_ALL=C.UTF-8" >> ~/.bashrc ``` **2. 设置Oracle客户端NLS\_LANG** ```bash export NLS_LANG=AMERICAN_AMERICA.AL32UTF8 echo "export NLS_LANG=AMERICAN_AMERICA.AL32UTF8" >> ~/.bashrc ``` **验证环境**: ```sql SQL> SELECT '测试中文' FROM DUAL; '测试中文' ------------ 测试中文 ``` #### 5.5.6 注意事项 * 创建oGRAC目标数据库时,务必指定UTF-8编码 * 确保源端与目标端时区一致性 * DataX迁移工具默认使用UTF-8编码,但需确保JVM环境变量正确设置 * 如果数据已损坏(显示为问号`?`),需从原始数据源重新导入 # 7 迁移建议 ### 7.1 执行机器配置要求 为了确保迁移工具的正常运行和最佳性能,执行机器需要满足以下配置要求: #### 7.1.1 硬件配置 | 配置项 | 最低要求 | 推荐配置 | 说明 | | -------- | -------- | ----------- | ----------------------------------- | | CPU | 4核 | 8核及以上 | 并发处理能力,影响多表并行迁移速度 | | 内存 | 8GB | 16GB及以上 | 用于JVM运行和DataX处理 | | 磁盘空间 | 50GB | 100GB及以上 | 用于存放工具、DataX、临时文件和日志 | #### 7.1.2 内存大小约束 根据迁移数据量和表大小,执行机器需要足够的内存来支持JVM和DataX的运行: 1. **JVM内存约束**: * 工具本身需要至少2GB内存 * DataX根据表大小自动调整JVM参数,最大可能需要4GB内存 * 并发迁移多个大表时,内存需求会增加 2. **内存使用估算**: * 小数据量迁移(<100万行):8GB内存足够 * 中等数据量迁移(100万-1000万行):16GB内存推荐 * 大数据量迁移(>1000万行):32GB内存推荐 3. **内存配置建议**: * 执行迁移命令时,可通过 `-Xmx` 参数调整JVM最大内存 * 示例:`java -Xmx8g -jar openGauss-FullReplicate-7.0.0-RC3.jar --start datax_table --source oracle --config config.yml` * 确保执行机器有足够的物理内存,避免使用过多交换空间 #### 7.1.3 操作系统要求 * **操作系统**:Linux (推荐) 或 Windows * **文件系统**:建议使用SSD存储,提高临时文件读写速度 * **网络**:源数据库和目标数据库之间的网络带宽至少1Gbps,延迟<10ms ### 7.2 并发度配置 当前配置文件默认并发度为4个线程查询表和4个线程写表: * **查询表的线程数 (readerNum): 4** * **写表的线程数 (writerNum): 4** 这些配置决定了迁移过程中同时处理的表数量,影响整体迁移速度和系统资源占用。 ### 7.2 DataX配置策略 迁移工具使用 `GeneralDataXConfigStrategy` 作为DataX的配置策略,主要特点如下: #### 7.2.1 动态Channel配置 根据表大小自动调整DataX的Channel数量: | 表行数 | Channel数 | | ----------------- | -------------------------- | | ≤10,000 | 1 | | 10,000-100,000 | 2 | | 100,000-1,000,000 | 4 | | >1,000,000 | 最多8个,或CPU核心数的一半 | #### 7.2.2 JVM参数配置 根据表大小自动调整JVM参数: | 表行数 | JVM参数 | | -------------------- | ----------------- | | ≤10,000 | -Xms512m -Xmx512m | | 10,000-1,000,000 | -Xms1g -Xmx1g | | 1,000,000-10,000,000 | -Xms2g -Xmx2g | | >10,000,000 | -Xms4g -Xmx4g | #### 7.2.3 批处理大小配置 根据表大小自动调整批处理大小: | 表行数 | 批处理大小 | | -------------------- | ---------- | | ≤10,000 | 500 | | 10,000-1,000,000 | 1,000 | | 1,000,000-10,000,000 | 2,000 | | >10,000,000 | 4,000 | #### 7.2.4 分片策略 * **有单一主键的表**:使用主键作为分片键 * **无主键或多主键的表**:使用DataX-OracleReader的默认分片策略,根据表大小自动调整分片数量 #### 7.2.5 根据最大表与并发度评估迁移工具的内存占用 迁移工具预估内存大小计算 1. **基础内存需求** * 迁移工具本身:至少2GB内存 2. **DataX任务内存需求** * 根据并发度参数(writerNum: 4),最多同时运行4个DataX任务,每个任务的内存需求如下: | 表大小 | 单个DataX任务内存 | 4个任务最大内存 | | ---------------------- | ----------------- | --------------- | | ≤10,000行 | 512MB | 2GB | | 10,000-1,000,000行 | 1GB | 4GB | | 1,000,000-10,000,000行 | 2GB | 8GB | | >10,000,000行 | 4GB | 16GB | 3. **总内存需求** * **最小预估**:工具本身(2GB) + 4个小表(2GB) = 4GB * **中等预估**:工具本身(2GB) + 4个中等表(4GB) = 6GB * **最大预估**:工具本身(2GB) + 4个超大表(16GB) = 18GB 4. **实际建议** * **小数据量迁移**(主要是小表):8GB内存足够 * **中等数据量迁移**(包含中等表):16GB内存推荐 * **大数据量迁移**(包含大表或超大表):32GB内存推荐 这些预估基于迁移工具的配置参数,实际使用时应根据具体的表大小分布和服务器资源情况进行调整。 --- --- url: >- /en/docs/latest/resource_pooling/a_query_error_is_reported_due_to_predicate_pushdown.md --- # A Query Error Is Reported Due to Predicate Pushdown ## Symptom When a predicate is pushed down in a plan, an error should not be reported according to the query execution sequence in the SQL standard. However, an error occurs during the execution. ``` openGauss=# select * from tba; a --- -1 2 (2 rows) openGauss=# select * from tbb; b --- -1 1 (2 rows) openGauss=# select * from tba join tbb on a > b where b > 0 and sqrt(a) > 1; ERROR: cannot table square root of a negative number ``` Execute the SQL standard process. 1. Execute the FROM clause to ensure that all data meets the `a > b` condition. 2. Execute the WHERE clause with the `b > 0` condition. If the result is `true`, `a > 0` can be deduced and the execution continues. If the result is `false`, the subsequent conditions are short-circuited and will not be executed. 3. Execute the WHERE clause with the `sqrt(a) > 1` condition. However, an error is reported, indicating that the input parameter is a negative value. ## Cause Analysis ``` openGauss=# explain (costs off) select * from tba join tbb on a > b where b > 0 and sqrt(a) > 1; QUERY PLAN ---------------------------------- Nest loop Join Filter: (a > b) -> Seq Scan on public.tba Filter: (sqrt(a) > 1) -> Materialize -> Seq Scan on public.tbb Filter: (b > 0) (7 rows) ``` According to the analysis plan, the original `a > b`, `b > 0`, and `sqrt(a) > 1` conditions are split and pushed down to different operators. As a result, the conditions are not executed in sequence. In addition, the current equivalence class inference supports only equal sign (=) inference and cannot automatically supplement `a > 0`. As a result, an error is reported during the query. ## Procedure Predicate pushdown can greatly improve query performance, and this special short-circuit and derivation scenario is not considered in most database optimizers. Therefore, you are advised to modify the query statement and manually add `a > 0` under related conditions. ``` openGauss=# select * from tba join tbb on a > b where b > 0 and a > 0 and sqrt(a) > 1; a | b ---+--- 2 | 1 (1 row) openGauss=# explain (costs off) select * from tba join tbb on a > b where b > 0 and a > 0 and sqrt(a) > 1; QUERY PLAN -------------------------------------- Nest loop Join Filter: (a > b) -> Seq Scan on public.tba Filter: (a > 0 and sqrt(a) > 1) -> Materialize -> Seq Scan on public.tbb Filter: (b > 0) (7 rows) ``` --- --- url: /en/docs/latest-lite/sql_reference/abort.md --- # ABORT ## Function **ABORT** rolls back the current transaction and cancels the changes in the transaction. This command is equivalent to [ROLLBACK](rollback.md), and is present only for historical reasons. Now **ROLLBACK** is recommended. ## Precautions **ABORT** has no impact outside a transaction, but will throw a NOTICE message. ## Syntax ``` ABORT [ WORK | TRANSACTION ] ; ``` ## Parameter Description **WORK | TRANSACTION** Specifies an optional keyword, which has no effect except increasing readability. ## Examples ``` -- Create the customer_demographics_t1 table. openGauss=# CREATE TABLE customer_demographics_t1 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- Insert data. openGauss=# INSERT INTO customer_demographics_t1 VALUES(1920801,'M', 'U', 'DOCTOR DEGREE', 200, 'GOOD', 1, 0,0); -- Start a transaction. openGauss=# START TRANSACTION; -- Update the column. openGauss=# UPDATE customer_demographics_t1 SET cd_education_status= 'Unknown'; -- Abort the transaction. All updates are rolled back. openGauss=# ABORT; -- Query data. openGauss=# SELECT * FROM customer_demographics_t1 WHERE cd_demo_sk = 1920801; cd_demo_sk | cd_gender | cd_marital_status | cd_education_status | cd_purchase_estimate | cd_credit_rating | cd_dep_count | cd_dep_employed_count | cd_dep_college_count ------------+-----------+-------------------+----------------------+----------------------+------------------+--------------+-----------------------+---------------------- 1920801 | M | U | DOCTOR DEGREE | 200 | GOOD | 1 | 0 | 0 (1 row) -- Delete the table. openGauss=# DROP TABLE customer_demographics_t1; ``` ## Helpful Links [SET TRANSACTION](set_transaction.md), [COMMIT | END](commit_end.md), and [ROLLBACK](rollback.md) --- --- url: /en/docs/latest/sql_reference/abort.md --- # ABORT ## Function **ABORT** rolls back the current transaction and cancels the changes in the transaction. This command is equivalent to [ROLLBACK](rollback.md), and is present only for historical reasons. Now **ROLLBACK** is recommended. ## Precautions **ABORT** has no impact outside a transaction, but will throw a NOTICE message. ## Syntax ``` ABORT [ WORK | TRANSACTION ] ; ``` ## Parameter Description **WORK | TRANSACTION** Specifies an optional keyword, which has no effect except increasing readability. ## Examples ``` -- Create the customer_demographics_t1 table. openGauss=# CREATE TABLE customer_demographics_t1 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- Insert data. openGauss=# INSERT INTO customer_demographics_t1 VALUES(1920801,'M', 'U', 'DOCTOR DEGREE', 200, 'GOOD', 1, 0,0); -- Start a transaction. openGauss=# START TRANSACTION; -- Update the column. openGauss=# UPDATE customer_demographics_t1 SET cd_education_status= 'Unknown'; -- Abort the transaction. All updates are rolled back. openGauss=# ABORT; -- Query data. openGauss=# SELECT * FROM customer_demographics_t1 WHERE cd_demo_sk = 1920801; cd_demo_sk | cd_gender | cd_marital_status | cd_education_status | cd_purchase_estimate | cd_credit_rating | cd_dep_count | cd_dep_employed_count | cd_dep_college_count ------------+-----------+-------------------+----------------------+----------------------+------------------+--------------+-----------------------+---------------------- 1920801 | M | U | DOCTOR DEGREE | 200 | GOOD | 1 | 0 | 0 (1 row) -- Delete the table. openGauss=# DROP TABLE customer_demographics_t1; ``` ## Helpful Links [SET TRANSACTION](set_transaction.md), [COMMIT | END](commit_end.md), and [ROLLBACK](rollback.md) --- --- url: /zh/docs/latest-lite/sql_reference/abort.md --- # ABORT ## 功能描述 回滚当前事务并且撤销所有当前事务中所做的更改。 作用等同于[ROLLBACK](rollback.md),早期SQL有用ABORT,现在推荐使用ROLLBACK。 ## 注意事项 在事务外部执行ABORT语句不会影响事务的执行,但是会抛出一个NOTICE信息。 ## 语法格式 ``` ABORT [ WORK | TRANSACTION ] ; ``` ## 参数说明 **WORK | TRANSACTION** 可选关键字,除了增加可读性没有其他任何作用。 ## 示例 ``` --创建表customer_demographics_t1。 openGauss=# CREATE TABLE customer_demographics_t1 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; --插入记录。 openGauss=# INSERT INTO customer_demographics_t1 VALUES(1920801,'M', 'U', 'DOCTOR DEGREE', 200, 'GOOD', 1, 0,0); --开启事务。 openGauss=# START TRANSACTION; --更新字段值。 openGauss=# UPDATE customer_demographics_t1 SET cd_education_status= 'Unknown'; --终止事务,上面所执行的更新会被撤销掉。 openGauss=# ABORT; --查询数据。 openGauss=# SELECT * FROM customer_demographics_t1 WHERE cd_demo_sk = 1920801; cd_demo_sk | cd_gender | cd_marital_status | cd_education_status | cd_purchase_estimate | cd_credit_rating | cd_dep_count | cd_dep_employed_count | cd_dep_college_count ------------+-----------+-------------------+----------------------+----------------------+------------------+--------------+-----------------------+---------------------- 1920801 | M | U | DOCTOR DEGREE | 200 | GOOD | 1 | 0 | 0 (1 row) --删除表。 openGauss=# DROP TABLE customer_demographics_t1; ``` ## 相关链接 [SET TRANSACTION](set_transaction.md),[COMMIT | END](commit_end.md),[ROLLBACK](rollback.md) --- --- url: /zh/docs/latest/sql_reference/abort.md --- # ABORT ## 功能描述 回滚当前事务并且撤销所有当前事务中所做的更改。 作用等同于[ROLLBACK](rollback.md),早期SQL有用ABORT,现在推荐使用ROLLBACK。 ## 注意事项 在事务外部执行ABORT语句不会影响事务的执行,但是会抛出一个NOTICE信息。 ## 语法格式 ```sql ABORT [ WORK | TRANSACTION ] ; ``` ## 参数说明 **WORK | TRANSACTION** 可选关键字,除了增加可读性没有其他任何作用。 ## 示例 ``` --创建表customer_demographics_t1。 openGauss=# CREATE TABLE customer_demographics_t1 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; --插入记录。 openGauss=# INSERT INTO customer_demographics_t1 VALUES(1920801,'M', 'U', 'DOCTOR DEGREE', 200, 'GOOD', 1, 0,0); --开启事务。 openGauss=# START TRANSACTION; --更新字段值。 openGauss=# UPDATE customer_demographics_t1 SET cd_education_status= 'Unknown'; --终止事务,上面所执行的更新会被撤销掉。 openGauss=# ABORT; --查询数据。 openGauss=# SELECT * FROM customer_demographics_t1 WHERE cd_demo_sk = 1920801; cd_demo_sk | cd_gender | cd_marital_status | cd_education_status | cd_purchase_estimate | cd_credit_rating | cd_dep_count | cd_dep_employed_count | cd_dep_college_count ------------+-----------+-------------------+----------------------+----------------------+------------------+--------------+-----------------------+---------------------- 1920801 | M | U | DOCTOR DEGREE | 200 | GOOD | 1 | 0 | 0 (1 row) --删除表。 openGauss=# DROP TABLE customer_demographics_t1; ``` ## 相关链接 [SET TRANSACTION](set_transaction.md),[COMMIT | END](commit_end.md),[ROLLBACK](rollback.md) --- --- url: /en/docs/latest-lite/characteristic_description/access_control_model.md --- # Access Control Model ## Availability This feature is available since openGauss 1.1.0. ## Introduction The access control model can be used to manage users' access permissions and grant them the minimum permissions required for completing a task. ## Benefits You can create users and grant permissions to them as needed to minimize risks. ## Description The database provides a role-based access control model and an access control model based on the separation of duties. In the role-based access control model, database roles are classified into system administrator, monitoring administrator, O\&M administrator, security policy administrator, and common user. The security administrator creates roles or user groups and grant permissions to roles. The monitoring administrator views the monitoring views or functions in **dbe\_perf** mode. The security policy administrator creates resource labels, anonymization policies, and unified audit policies. A user who is assigned a role has the role's permissions. In the access control model based on the separation of duties, database roles are classified into system administrator, security administrator, audit administrator, monitoring administrator, O\&M administrator, security policy administrator, and common user. The security administrator creates users, the system administrator grants permissions to users, and the audit administrator audits all user behavior. By default, the role-based access control model is used. To switch to another mode, set the GUC parameter **enableSeparationOfDuty** to **on**. ## Enhancements None. ## Constraints The permissions of the system administrator are controlled by the GUC parameter **enableSeparationOfDuty**. The database needs to be restarted when the separation of duties is enabled, disabled or switched. In addition, improper user permissions in the new model cannot be automatically identified. The database administrator needs to manually identify and rectify the fault. ## Dependencies None. --- --- url: /en/docs/latest/characteristic_description/access_control_model.md --- # Access Control Model ## Availability This feature is available as of openGauss 1.1.0. ## Introduction The access control model can be used to manage users' access permissions and grant them the minimum permissions required for completing a task. ## Benefits You can create users and grant permissions to them as needed to minimize risks. ## Description The database provides a role-based access control model and an access control model based on the separation of duties. In the role-based access control model, database roles are classified into system administrator, monitoring administrator, O\&M administrator, security policy administrator, and common user. The security administrator creates roles or user groups and grant permissions to roles. The monitoring administrator views the monitoring views or functions in **dbe\_perf** mode. The O\&M administrator uses the Roach tool to back up and restore the database. The security policy administrator creates resource labels, anonymization policies, and unified audit policies. A user who is assigned a role has the role's permissions. In the access control model based on the separation of duties, database roles are classified into system administrator, security administrator, audit administrator, monitoring administrator, O\&M administrator, security policy administrator, and common user. The security administrator creates users, the system administrator grants permissions to users, and the audit administrator audits all user behavior. By default, the role-based access control model is used. To switch to another mode, set the GUC parameter **enableSeparationOfDuty** to **on**. ## Enhancements None ## Constraints The permissions of the system administrator are controlled by the GUC parameter **enableSeparationOfDuty**. The database needs to be restarted when the separation of duties is enabled, disabled or switched. In addition, improper user permissions in the new model cannot be automatically identified. The database administrator needs to manually identify and rectify the fault. ## Dependencies None --- --- url: /en/docs/latest-lite/characteristic_description/adaptive_compression.md --- # Adaptive Compression ## Availability This feature is available since openGauss 1.0.0. ## Introduction Data compression is the major technology used in current databases. Various compression algorithms are used for different data types. If pieces of data of the same type have different characteristics, their compression algorithms and results will also be different. Adaptive compression chooses the suitable compression algorithm for data based on the data type and characteristics, achieving high performance in compression ratio, import, and query. ## Benefits Importing and frequently querying a huge amount of data are the main application scenarios. When you import data, adaptive compression greatly reduces the data volume, increases I/O operation efficiency several times, and clusters data before storage, achieving fast data import. In this way, only a small number of I/O operations is required and data is quickly decompressed in a query. Data can be quickly retrieved and the query result is quickly returned. ## Description Currently, the database has implemented various compression algorithms on column store, including RLE, DELTA, BYTEPACK/BITPACK, LZ4, ZLIB, and LOCAL DICTIONARY. The following table lists data types and the compression algorithms suitable for them. ## Enhancements The compression level of compression algorithms can be adjusted. ## Constraints None. ## Dependencies It depends on LZ4 or ZLIB. --- --- url: /en/docs/latest/database_administration_guide/adaptive_compression.md --- # Adaptive Compression ## Availability This feature is available since openGauss 1.0.0. ## Introduction Data compression is the major technology used in current databases. Various compression algorithms are used for different data types. If pieces of data of the same type have different characteristics, their compression algorithms and results will also be different. Adaptive compression chooses the suitable compression algorithm for data based on the data type and characteristics, achieving high performance in compression ratio, import, and query. ## Benefits Importing and frequently querying a huge amount of data are the main application scenarios. When you import data, adaptive compression greatly reduces the data volume, increases I/O operation efficiency several times, and clusters data before storage, achieving fast data import. In this way, only a small number of I/O operations is required and data is quickly decompressed in a query. Data can be quickly retrieved and the query result is quickly returned. ## Description Currently, the database has implemented various compression algorithms on column store, including RLE, DELTA, BYTEPACK/BITPACK, LZ4, ZLIB, and LOCAL DICTIONARY. The following table lists data types and the compression algorithms suitable for them. ## Enhancements The compression level of compression algorithms can be adjusted. ## Constraints None ## Dependencies It depends on LZ4 or ZLIB. --- --- url: /en/docs/latest/characteristic_description/adaptive_plan_selection.md --- # Adaptive Plan Selection ## Availability This feature is available since openGauss 3.1.0. ## Introduction This feature triggers plan selection based on the base table condition selection rate, and provides cache multi-plan management and adaptive selection for queries that use partial indexes and offsets. In typical scenarios, the query throughput can be improved by several times. ## Benefits Users can maintain multiple cache plans to adapt to different query parameters, improving query execution performance. ## Description Adaptive plan selection applies to scenarios where a general cache plan is used for plan execution. Cache plan exploration is performed by using range linear expansion, and plan selection is performed by using range coverage matching. Adaptive plan selection makes up for the performance problem caused by the traditional single cache plan that cannot change according to the query condition parameter, and avoids frequent calling of query optimization. ## Enhancements None ## Constraints * Database services are running properly. * Users have logged in to the database. * Users have created a database and data table, and have imported data. ## Dependencies It depends on the plan cache function in the database. --- --- url: >- /en/docs/latest/characteristic_description/aifeature_guide/adaptive_plan_selection.md --- # Adaptive Plan Selection ## Overview Adaptive plan selection applies to scenarios where a general cache plan is used for plan execution. Cache plan exploration is performed by using range linear expansion, and plan selection is performed by using range coverage matching. Adaptive plan selection makes up for the performance problem caused by the traditional single cache plan that cannot change according to the query condition parameter, and avoids frequent calling of query optimization. ## Prerequisites The database is running properly. The GUC parameter **enable\_cachedplan\_mgr** is set to **on**, indicating that the adaptive plan selection function is enabled. ## Usage Guide On the live network, use hints to enable the plan adaptation management capability for queries with cache plan problems. ``` select /*+ choose_adaptive_gplan */ * from tab where c1 = xxx; ``` By default, the JDBC client converts the preceding SQL statements with hints to the PBE model and creates a query template. In addition to directly modifying SQL statements, hints can be added through SQL patches. In the gsql environment, you can manually create a query template. ``` prepare test_stmt as select /*+ choose_adaptive_gplan */ * from tab where c1 = $1; ``` ## Best Practice **Adaptive selection of multiple indexes is supported. The following is an example:** ``` create table t1(c1 int, c2 int, c3 int, c4 varchar(32), c5 text); create index t1_idx2 on t1(c1,c2,c3,c4); create index t1_idx1 on t1(c1,c2,c3); insert into t1( c1, c2, c3, c4, c5) SELECT (random()*(2*10^9))::integer , (random()*(2*10^9))::integer, (random()*(2*10^9))::integer, (random()*(2*10^9))::integer, repeat('abc', i%10) ::text from generate_series(1,1000000) i; insert into t1( c1, c2, c3, c4, c5) SELECT (random()*1)::integer, (random()*1)::integer, (random()*1)::integer, (random()*(2*10^9))::integer, repeat('abc', i%10) ::text from generate_series(1,1000000) i; ``` **Performance comparison:** Random parameters: c1~ random(1, 20); c2~ random(1, 20); c3~ random(1, 20); c4 ~ random(2, 10000) The number of threads is 50, the number of clients is 50, and the execution duration is 60s. ## Troubleshooting For complex slow queries, this feature may not be able to correctly select a plan due to feature range restrictions. You are advised to use CPLAN to generate a query plan. --- --- url: >- /en/docs/latest/characteristic_description/adding_or_deleting_a_standby_server.md --- # Adding or Deleting a Standby Node ## Availability This feature is available since openGauss 2.0.0. ## Introduction Standby nodes can be added and deleted. ## Benefits If the read pressure of the primary node is high or you want to improve the disaster recovery capability of the database, you need to add a standby node. If some standby nodes in a cluster are faulty and cannot be recovered within a short period of time, you can delete the faulty nodes to ensure that the cluster is running properly. ## Description openGauss can be scaled out from a single node or one primary and multiple standbys to one primary and eight standbys. Cascaded standby nodes can be added. Standby nodes can be added when a faulty standby node exists in the cluster. One primary and multiple standbys can be scaled in to a single node. A faulty standby node can be deleted. Standby nodes can be added or deleted online without affecting the primary node. ## Enhancements None. ## Constraints For adding a standby node: * Ensure that the openGauss image package exists on the primary node. * Ensure that the same users and user groups as those on the primary node have been created on the new standby node. * Ensure that the mutual trust of user **root** and the database management user has been established between the existing database nodes and the new nodes. * Ensure that the XML file has been properly configured and information about the standby node to be scaled has been added to the installed database configuration file. * Ensure that only user **root** is authorized to run the scale-out command. * Do not run the **gs\_dropnode** command on the primary node to delete other standby nodes at the same time. * Ensure that the environment variables of the primary node have been imported before the scale-out command is run. * Ensure that the operating system of the new standby node is the same as that of the primary node. * Do not perform an primary/standby switchover or failover on other standby nodes at the same time. For deleting a standby node: * Delete the standby node only on the primary node. * Do not perform an primary/standby switchover or failover on other standby nodes at the same time. * Do not run the **gs\_expansion** command on the primary node for scale-out at the same time. * Do not run the **gs\_dropnode** command twice at the same time. * Before deletion, ensure that the database management user trust relationship has been established between the primary and standby nodes. * Run this command as a database administrator. * Before running commands, run the **source** command to import environment variables of the primary node. ## Dependencies None. --- --- url: >- /en/docs/latest/database_administration_guide/adding_or_deleting_a_standby_server.md --- # Adding or Deleting a Standby Node ## Availability This feature is available since openGauss 2.0.0. ## Introduction Standby nodes can be added and deleted. ## Benefits If the read pressure of the primary node is high or you want to improve the disaster recovery capability of the database, you need to add a standby node. If some standby nodes in a cluster are faulty and cannot be recovered within a short period of time, you can delete the faulty nodes to ensure that the cluster is running properly. ## Description openGauss can be scaled out from a single node or one primary and multiple standbys to one primary and eight standbys. Cascaded standby nodes can be added. Standby nodes can be added when a faulty standby node exists in the cluster. One primary and multiple standbys can be scaled in to a single node. A faulty standby node can be deleted. Standby nodes can be added or deleted online without affecting the primary node. ## Enhancements None. ## Constraints For adding a standby node: * Ensure that the openGauss image package exists on the primary node. * Ensure that the same users and user groups as those on the primary node have been created on the new standby node. * Ensure that the mutual trust of user **root** and the database management user has been established between the existing database nodes and the new nodes. * Ensure that the XML file has been properly configured and information about the standby node to be scaled has been added to the installed database configuration file. * Ensure that only user **root** is authorized to run the scale-out command. * Do not run the **gs\_dropnode** command on the primary node to delete other standby nodes at the same time. * Ensure that the environment variables of the primary node have been imported before the scale-out command is run. * Ensure that the operating system of the new standby node is the same as that of the primary node. * Do not perform an primary/standby switchover or failover on other standby nodes at the same time. For deleting a standby node: * Delete the standby node only on the primary node. * Do not perform an primary/standby switchover or failover on other standby nodes at the same time. * Do not run the **gs\_expansion** command on the primary node for scale-out at the same time. * Do not run the **gs\_dropnode** command twice at the same time. * Before deletion, ensure that the database management user trust relationship has been established between the primary and standby nodes. * Run this command as a database administrator. * Before running commands, run the **source** command to import environment variables of the primary node. ## Dependencies None. --- --- url: /en/docs/latest-lite/database_administration_guide/administrator.md --- # Administrator ## Initial User The account automatically generated during database installation is called an initial user. The initial user has the highest-level permissions in the system and can perform all operations. If the initial username is not specified during installation, the username is the same as the name of the OS user who installs the database. If the password of the initial user is not specified during the installation, the password is empty after the installation. In this case, you need to change the password of the initial user on the gsql client before performing other operations. If the initial user password is empty, you cannot perform other SQL operations, such as upgrade and node replacement, except changing the password. An initial user bypasses all permission checks. You are advised to use an initial user as a database administrator only for database management other than service running. ## System Administrator A system administrator is an account with the **SYSADMIN** attribute. By default, a database system administrator has the same permissions as object owners but does not have the object permissions in **dbe\_perf** mode. To create a database administrator, connect to the database as an administrator and run the **[CREATE USER](../sql_reference/create_user.md)** or **[ALTER USER](../sql_reference/alter_user.md)** statement with **SYSADMIN** specified. ``` openGauss=# CREATE USER sysadmin WITH SYSADMIN password "xxxxxxxxx"; ``` Or ``` openGauss=# ALTER USER joe SYSADMIN; ``` To run the **ALTER USER** statement, the user must exist. ## Monitor Administrator A monitor administrator is an account with the **MONADMIN** attribute and has the permission to view views and functions in the **dbe\_perf** schema. The monitor administrator can also grant or revoke object permissions in the **dbe\_perf** schema. To create a monitor administrator, connect to the database as a system administrator and run the **[CREATE USER](../sql_reference/create_user.md)** or **[ALTER USER](../sql_reference/alter_user.md)** statement with **MONADMIN** specified. ``` openGauss=# CREATE USER monadmin WITH MONADMIN password "xxxxxxxxx"; ``` or ``` openGauss=# ALTER USER joe MONADMIN; ``` To run the **ALTER USER** statement, the user must exist. ## O\&M Administrator An O\&M administrator is an account with the **OPRADMIN** permission. To create an O\&M administrator, connect to the database as an initial user and run the **[CREATE USER](../sql_reference/create_user.md)** or **[ALTER USER](../sql_reference/alter_user.md)** statement with **OPRADMIN** specified. ``` openGauss=# CREATE USER opradmin WITH OPRADMIN password "xxxxxxxxx"; ``` or ``` openGauss=# ALTER USER joe OPRADMIN; ``` To run the **ALTER USER** statement, the user must exist. ## Security Policy Administrator A security policy administrator is an account with the **POLADMIN** attribute and has the permission to create resource tags, anonymization policies, and unified audit policies. To create a security policy administrator, connect to the database as an administrator and run the **[CREATE USER](../sql_reference/create_user.md)** or **[ALTER USER](../sql_reference/alter_user.md)** statement with **POLADMIN** specified. ``` openGauss=# CREATE USER poladmin WITH POLADMIN password "xxxxxxxxx"; ``` or ``` openGauss=# ALTER USER joe POLADMIN; ``` To run the **ALTER USER** statement, the user must exist. --- --- url: /en/docs/latest/database_administration_guide/administrators.md --- # Administrators ## Initial Users The account automatically generated during openGauss installation is called an initial user. An initial user is the system, monitoring, O\&M, and security policy administrator who has the highest-level permissions in the system and can perform all operations. This account has the same name as the OS user used for openGauss installation. You need to manually set the password during the installation. After the first login, change the initial user's password in time. An initial user bypasses all permission checks. You are advised to use an initial user as a database administrator only for database management other than service running. ## System Administrators A system administrator is an account with the **SYSADMIN** attribute. By default, a database system administrator has the same permissions as object owners but does not have the object permissions in **dbe\_perf** mode. To create a system administrator, connect to the database as the initial user or a system administrator and run the **[CREATE USER](../sql_reference/create_user.md)** or **[ALTER USER](../sql_reference/alter_user.md)** statement with **SYSADMIN** specified. ``` CREATE USER sysadmin WITH SYSADMIN password "xxxxxxxxx"; ``` or ``` ALTER USER joe SYSADMIN; ``` To run the **ALTER USER** statement, the user must exist. ## Monitor Administrator A monitor administrator is an account with the **MONADMIN** attribute and has the permission to view views and functions in the **dbe\_perf** schema. The monitor administrator can also grant or revoke object permissions in the **dbe\_perf** schema. To create a monitor administrator, connect to the database as a system administrator and run the **[CREATE USER](../sql_reference/create_user.md)** or **[ALTER USER](../sql_reference/alter_user.md)** statement with **MONADMIN** specified. ``` postgres=# CREATE USER monadmin WITH MONADMIN password "xxxxxxxxx"; ``` or ``` postgres=# ALTER USER joe MONADMIN; ``` To run the **ALTER USER** statement, the user must exist. ## O\&M Administrator An O\&M administrator is an account with the **OPRADMIN** attribute and has the permission to use Roach to perform backup and restoration. To create an O\&M administrator, connect to the database as an initial user and run the **[CREATE USER](../sql_reference/create_user.md)** or **[ALTER USER](../sql_reference/alter_user.md)** statement with **OPRADMIN** specified. ``` postgres=# CREATE USER opradmin WITH OPRADMIN password "xxxxxxxxx"; ``` or ``` postgres=# ALTER USER joe OPRADMIN; ``` To run the **ALTER USER** statement, the user must exist. ## Security Policy Administrator A security policy administrator is an account with the **POLADMIN** attribute and has the permission to create resource tags, anonymization policies, and unified audit policies. To create a security policy administrator, connect to the database as an administrator and run the **[CREATE USER](../sql_reference/create_user.md)** or **[ALTER USER](../sql_reference/alter_user.md)** statement with **POLADMIN** specified. ``` postgres=# CREATE USER poladmin WITH POLADMIN password "xxxxxxxxx"; ``` or ``` postgres=# ALTER USER joe POLADMIN; ``` To run the **ALTER USER** statement, the user must exist. --- --- url: /en/docs/latest-lite/brief_tutorial/advanced_data_management.md --- # Advanced Data Management * **[Constraints](constraints.md)** * **[JOIN](join.md)** * **[NULL](null.md)** * **[UNION Clause](union_clause.md)** * **[Aliases](aliases.md)** * **[Indexes](indexes.md)** * **[Batch Processing Mode](batch_processing_mode.md)** * **[Views](views.md)** * **[SCHEMA](schema.md)** * **[ALTER TABLE Statement](alter_table_statement.md)** * **[TRUNCATE TABLE Statement](truncate_table_statement.md)** * **[Transactions](transactions.md)** * **[Cursors](cursors.md)** * **[Partitioned Tables](partitioned_tables.md)** * **[Locks](locks.md)** * **[Anonymous Blocks](anonymous_blocks.md)** * **[Triggers](triggers.md)** * **[Stored Procedures](stored_procedures.md)** * **[Materialized Views](materialized_views.md)** * **[Subqueries](subqueries.md)** * **[Permissions](permissions.md)** * **[Functions](functions.md)** --- --- url: /en/docs/latest-lite/sql_reference/advisory_lock_functions.md --- # Advisory Lock Functions Advisory lock functions manage advisory locks. * pg\_advisory\_lock(key bigint) Description: Obtains an exclusive session-level advisory lock. Return type: void Note: **pg\_advisory\_lock** locks resources defined by an application. The resources can be identified using a 64-bit or two nonoverlapped 32-bit key values. If another session locks the resources, the function blocks the resources until they can be used. The lock is exclusive. Multiple locking requests are pushed into the stack. Therefore, if the same resource is locked three times, it must be unlocked three times so that it is released to another session. * pg\_advisory\_lock(key1 int, key2 int) Description: Obtains an exclusive session-level advisory lock. Return type: void Note: Only users with the **sysadmin** permission can add session-level exclusive advisory locks to the key-value pair (65535, 65535). * pg\_advisory\_lock(int4, int4, Name) Description: Obtains the exclusive advisory lock of a specified database. Return type: void * pg\_advisory\_lock\_shared(key bigint) Description: Obtains a shared session-level advisory lock. Return type: void * pg\_advisory\_lock\_shared(key1 int, key2 int) Description: Obtains a shared session-level advisory lock. Return type: void Note: **pg\_advisory\_lock\_shared** works in the same way as **pg\_advisory\_lock**, except the lock can be shared with other sessions requesting shared locks. Only would-be exclusive lockers are locked out. * pg\_advisory\_unlock(key bigint) Description: Releases an exclusive session-level advisory lock. Return type: Boolean * pg\_advisory\_unlock(key1 int, key2 int) Description: Releases an exclusive session-level advisory lock. Return type: Boolean Note: **pg\_advisory\_unlock** releases the obtained exclusive advisory lock. If the release is successful, the function returns **true**. If the lock was not held, it will return **false**. In addition, a SQL warning will be reported by the server. * pg\_advisory\_unlock(int4, int4, Name) Description: Releases the exclusive advisory lock of a specified database. Return type: Boolean Note: If the release is successful, **true** is returned. If no lock is held, **false** is returned. * pg\_advisory\_unlock\_shared(key bigint) Description: Releases a shared session-level advisory lock. Return type: Boolean * pg\_advisory\_unlock\_shared(key1 int, key2 int) Description: Releases a shared session-level advisory lock. Return type: Boolean Note: **pg\_advisory\_unlock\_shared** works in the same way as **pg\_advisory\_unlock**, except it releases a shared session-level advisory lock. * pg\_advisory\_unlock\_all() Description: Releases all advisory locks owned by the current session. Return type: void Note: **pg\_advisory\_unlock\_all** releases all advisory locks owned by the current session. The function is implicitly invoked when the session ends even if the client is abnormally disconnected. * pg\_advisory\_xact\_lock(key bigint) Description: Obtains an exclusive transaction-level advisory lock. Return type: void * pg\_advisory\_xact\_lock(key1 int, key2 int) Description: Obtains an exclusive transaction-level advisory lock. Return type: void Note: **pg\_advisory\_xact\_lock** works in the same way as **pg\_advisory\_lock**, except the lock is automatically released at the end of the current transaction and cannot be released explicitly. Only users with the **sysadmin** permission can add transaction-level exclusive advisory locks to the key-value pair (65535, 65535). * pg\_advisory\_xact\_lock\_shared(key bigint) Description: Obtains a shared transaction-level advisory lock. Return type: void * pg\_advisory\_xact\_lock\_shared(key1 int, key2 int) Description: Obtains a shared transaction-level advisory lock. Return type: void Note: **pg\_advisory\_xact\_lock\_shared** works in the same way as **pg\_advisory\_lock\_shared**, except the lock is automatically released at the end of the current transaction and cannot be released explicitly. * pg\_try\_advisory\_lock(key bigint) Description: Obtains an exclusive session-level advisory lock if available. Return type: Boolean Note: **pg\_try\_advisory\_lock** is similar to **pg\_advisory\_lock**, except **pg\_try\_advisory\_lock** does not block the resource until the resource is released. **pg\_try\_advisory\_lock** either immediately obtains the lock and returns **true** or returns **false**, which indicates the lock cannot be performed currently. * pg\_try\_advisory\_lock(key1 int, key2 int) Description: Obtains an exclusive session-level advisory lock if available. Return type: Boolean Note: Only users with the **sysadmin** permission can add session-level exclusive advisory locks to the key-value pair (65535, 65535). * pg\_try\_advisory\_lock\_shared(key bigint) Description: Obtains a shared session-level advisory lock if available. Return type: Boolean * pg\_try\_advisory\_lock\_shared(key1 int, key2 int) Description: Obtains a shared session-level advisory lock if available. Return type: Boolean Note: **pg\_try\_advisory\_lock\_shared** is similar to **pg\_try\_advisory\_lock**, except **pg\_try\_advisory\_lock\_shared** attempts to obtain a shared lock instead of an exclusive lock. * pg\_try\_advisory\_xact\_lock(key bigint) Description: Obtains an exclusive transaction-level advisory lock if available. Return type: Boolean * pg\_try\_advisory\_xact\_lock(key1 int, key2 int) Description: Obtains an exclusive transaction-level advisory lock if available. Return type: Boolean Note: **pg\_try\_advisory\_xact\_lock** works in the same way as **pg\_try\_advisory\_lock**, except the lock, if acquired, is automatically released at the end of the current transaction and cannot be released explicitly. Note: Only users with the **sysadmin** permission can add transaction-level exclusive advisory locks to the key-value pair (65535, 65535). * pg\_try\_advisory\_xact\_lock\_shared(key bigint) Description: Obtains a shared transaction-level advisory lock if available. Return type: Boolean * pg\_try\_advisory\_xact\_lock\_shared(key1 int, key2 int) Description: Obtains a shared transaction-level advisory lock if available. Return type: Boolean Note: **pg\_try\_advisory\_xact\_lock\_shared** works in the same way as **pg\_try\_advisory\_lock\_shared**, except the lock, if acquired, is automatically released at the end of the current transaction and cannot be released explicitly. * lock\_cluster\_ddl() Description: Attempts to obtain a session-level exclusive advisory lock for all active primary database nodes in openGauss. Return type: Boolean Note: Only users with the **sysadmin** permission can call this function. * unlock\_cluster\_ddl() Description: Attempts to add a session-level exclusive advisory lock on the primary database node. Return type: Boolean --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_advisory_lock_functions.md --- # Advisory Lock Functions Advisory lock functions manage advisory locks. * pg\_advisory\_lock(key bigint) Description: Obtains an exclusive session-level advisory lock. Return type: void Note: **pg\_advisory\_lock** locks resources defined by an application. The resources can be identified using a 64-bit or two unoverlapped 32-bit key values. If another session locks the resources, the function blocks the resources until they can be used. The lock is exclusive. Multiple locking requests are pushed into the stack. Therefore, if the same resource is locked three times, it must be unlocked three times so that it is released to another session. * pg\_advisory\_lock(key1 int, key2 int) Description: Obtains an exclusive session-level advisory lock. Return type: void Note: Only the sysadmin user is allowed to add a session-level exclusive advisory lock to the key-value pair (65535, 65535). Common users do not have the permission. * pg\_advisory\_lock(int4, int4, Name) Description: Obtains the exclusive advisory lock of a specified database. Return type: void * pg\_advisory\_lock\_shared(key bigint) Description: Obtains a shared session-level advisory lock. Return type: void * pg\_advisory\_lock\_shared(key1 int, key2 int) Description: Obtains a shared session-level advisory lock. Return type: void Note: pg\_advisory\_lock\_shared is similar to pg\_advisory\_lock. The only difference is that a shared lock session can share resources with other sessions that request a shared lock, except for exclusive locks. * pg\_advisory\_unlock(key bigint) Description: Releases an exclusive session-level advisory lock. Return type: Boolean * pg\_advisory\_unlock(key1 int, key2 int) Description: Releases an exclusive session-level advisory lock. Return type: Boolean Note: pg\_advisory\_unlock releases the obtained exclusive advisory lock. If the release is successful, the function returns **true**. If the lock was not held, it will return **false**. In addition, a SQL warning will be reported by the server. * pg\_advisory\_unlock(int4, int4, Name) Description: Releases the exclusive advisory lock of a specified database. Return type: Boolean Note: If the release is successful, **true** is returned. If no lock is held, **false** is returned. * pg\_advisory\_unlock\_shared(key bigint) Description: Releases a shared session level advisory lock. Return type: Boolean * pg\_advisory\_unlock\_shared(key1 int, key2 int) Description: Releases a shared session level advisory lock. Return type: Boolean Note: pg\_advisory\_unlock\_shared is similar to pg\_advisory\_unlock. The difference is that this function releases a shared advisory lock. * pg\_advisory\_unlock\_all() Description: Releases all advisory locks owned by the current session. Return type: void Note: **pg\_advisory\_unlock\_all** releases all advisory locks owned by the current session. The function is implicitly invoked when the session ends even if the client is abnormally disconnected. * pg\_advisory\_xact\_lock(key bigint) Description: Obtains an exclusive transaction-level advisory lock. Return type: void * pg\_advisory\_xact\_lock(key1 int, key2 int) Description: Obtains an exclusive transaction-level advisory lock. Return type: void Note: pg\_advisory\_xact\_lock is similar to pg\_advisory\_lock. The difference is that locks are automatically released at the end of the current transaction and cannot be explicitly released. Only the sysadmin user is allowed to add a transaction-level exclusive advisory lock to the key-value pair (65535, 65535). Common users do not have the permission. * pg\_advisory\_xact\_lock\_shared(key bigint) Description: Obtains a shared transaction-level advisory lock. Return type: void * pg\_advisory\_xact\_lock\_shared(key1 int, key2 int) Description: Obtains a shared transaction-level advisory lock. Return type: void Note: pg\_advisory\_xact\_lock\_shared is similar to pg\_advisory\_lock\_shared. The difference is that locks are automatically released at the end of the current transaction and cannot be explicitly released. * pg\_try\_advisory\_lock(key bigint) Description: Obtains exclusive session level advisory lock if available. Return type: Boolean Note: pg\_try\_advisory\_lock is similar to pg\_advisory\_lock. The difference is that this function is not blocked to wait for resource release. It either immediately obtains the lock and returns **true** or returns **false**, which indicates the lock cannot be performed currently. * pg\_try\_advisory\_lock(key1 int, key2 int) Description: Obtains exclusive session level advisory lock if available. Return type: Boolean Note: Only the sysadmin user is allowed to add a session-level exclusive advisory lock to the key-value pair (65535, 65535). Common users do not have the permission. * pg\_try\_advisory\_lock\_shared(key bigint) Description: Obtains a shared session-level advisory lock if available. Return type: Boolean * pg\_try\_advisory\_lock\_shared(key1 int, key2 int) Description: Obtains a shared session-level advisory lock if available. Return type: Boolean Note: pg\_try\_advisory\_lock\_shared is similar to pg\_try\_advisory\_lock. The difference is that pg\_try\_advisory\_lock\_shared attempts to obtain a shared lock instead of an exclusive lock. * pg\_try\_advisory\_xact\_lock(key bigint) Description: Obtains an exclusive transaction-level advisory lock if available. Return type: Boolean * pg\_try\_advisory\_xact\_lock(key1 int, key2 int) Description: Obtains exclusive transaction level advisory lock if available. Return type: Boolean Note: pg\_try\_advisory\_xact\_lock is similar to pg\_try\_advisory\_lock. The difference is that if a lock is obtained, it is automatically released at the end of the current transaction and cannot be explicitly released. Only the sysadmin user is allowed to add a transaction-level exclusive advisory lock to the key-value pair (65535, 65535). Common users do not have the permission. * pg\_try\_advisory\_xact\_lock\_shared(key bigint) Description: Obtains a shared transaction-level advisory lock if available. Return type: Boolean * pg\_try\_advisory\_xact\_lock\_shared(key1 int, key2 int) Description: Obtains a shared transaction-level advisory lock if available. Return type: Boolean Note: pg\_try\_advisory\_xact\_lock\_shared is similar to pg\_try\_advisory\_lock\_shared. The difference is that if a lock is obtained, it is automatically released at the end of the current transaction and cannot be explicitly released. * lock\_cluster\_ddl() Description: Attempts to obtain a session-level exclusive advisory lock for all active primary database nodes in openGauss. Return type: Boolean Note: Only the sysadmin user can call this function. Common users do not have the permission. * unlock\_cluster\_ddl() Description: Attempts to add a session-level exclusive advisory lock on the primary database node. Return type: Boolean * pg\_catalog.get\_lock(text,text) Description: Adds a user lock to the database with a specified character string. The second parameter is the lock waiting time. Return type: Int * pg\_catalog.get\_lock(text,double) Description: Adds a user lock to the database with a specified character string. The second parameter is the lock waiting time. Return type: Int * pg\_catalog.get\_lock(text) Description: Adds a user lock to the database with a specified character string. Return type: Int * pg\_catalog.release\_lock(text) Description: Releases a specified lock. If the lock is successfully released, **1** is returned. If the current session does not hold the specified lock, **0** is returned. If the current lock does not exist (the lock must be held), **NULL** is returned. Return type: Int * pg\_catalog.is\_free\_lock(text) Description: Checks whether a string is idle. If the string is not locked, **1** is returned. Otherwise, **0** is returned. If other errors occur during the check, **NULL** is returned. Return type: Int * pg\_catalog.is\_used\_lock(text) Description: Checks who holds the lock of a string and returns the session ID of the corresponding user. If the specified lock is not held, **NULL** is returned. Return type: Bigint * pg\_catalog.clear\_all\_invalid\_locks() Description: Clears information about invalid locks in the lockname hash table and returns the number of cleared locks. Return type: Bigint * pg\_catalog.release\_all\_locks() Description: Releases all locks held by the current session and returns the number of release times. If a single string holds multiple locks, the number of release times is calculated based on the corresponding number instead of only once. Return type: Bigint * pg\_catalog.get\_all\_locks() Description: Queries all user locks in the current database and returns the names and holders of all user locks in the form of records. Return type: Record --- --- url: /en/docs/latest/sql_reference/advisory_lock_functions.md --- # Advisory Lock Functions Advisory lock functions manage advisory locks. * pg\_advisory\_lock(key bigint) Description: Obtains an exclusive session-level advisory lock. Return type: void Note: **pg\_advisory\_lock** locks resources defined by an application. The resources can be identified using a 64-bit or two nonoverlapped 32-bit key values. If another session locks the resources, the function blocks the resources until they can be used. The lock is exclusive. Multiple locking requests are pushed into the stack. Therefore, if the same resource is locked three times, it must be unlocked three times so that it is released to another session. * pg\_advisory\_lock(key1 int, key2 int) Description: Obtains an exclusive session-level advisory lock. Return type: void Note: Only users with the **sysadmin** permission can add session-level exclusive advisory locks to the key-value pair (65535, 65535). * pg\_advisory\_lock(int4, int4, Name) Description: Obtains the exclusive advisory lock of a specified database. Return type: void * pg\_advisory\_lock\_shared(key bigint) Description: Obtains a shared session-level advisory lock. Return type: void * pg\_advisory\_lock\_shared(key1 int, key2 int) Description: Obtains a shared session-level advisory lock. Return type: void Note: **pg\_advisory\_lock\_shared** works in the same way as **pg\_advisory\_lock**, except the lock can be shared with other sessions requesting shared locks. Only would-be exclusive lockers are locked out. * pg\_advisory\_unlock(key bigint) Description: Releases an exclusive session-level advisory lock. Return type: Boolean * pg\_advisory\_unlock(key1 int, key2 int) Description: Releases an exclusive session-level advisory lock. Return type: Boolean Note: **pg\_advisory\_unlock** releases the obtained exclusive advisory lock. If the release is successful, the function returns **true**. If the lock was not held, it will return **false**. In addition, a SQL warning will be reported by the server. * pg\_advisory\_unlock(int4, int4, Name) Description: Releases the exclusive advisory lock of a specified database. Return type: Boolean Note: If the release is successful, **true** is returned. If no lock is held, **false** is returned. * pg\_advisory\_unlock\_shared(key bigint) Description: Releases a shared session-level advisory lock. Return type: Boolean * pg\_advisory\_unlock\_shared(key1 int, key2 int) Description: Releases a shared session-level advisory lock. Return type: Boolean Note: **pg\_advisory\_unlock\_shared** works in the same way as **pg\_advisory\_unlock**, except it releases a shared session-level advisory lock. * pg\_advisory\_unlock\_all() Description: Releases all advisory locks owned by the current session. Return type: void Note: **pg\_advisory\_unlock\_all** releases all advisory locks owned by the current session. The function is implicitly invoked when the session ends even if the client is abnormally disconnected. * pg\_advisory\_xact\_lock(key bigint) Description: Obtains an exclusive transaction-level advisory lock. Return type: void * pg\_advisory\_xact\_lock(key1 int, key2 int) Description: Obtains an exclusive transaction-level advisory lock. Return type: void Note: **pg\_advisory\_xact\_lock** works in the same way as **pg\_advisory\_lock**, except the lock is automatically released at the end of the current transaction and cannot be released explicitly. Only users with the **sysadmin** permission can add transaction-level exclusive advisory locks to the key-value pair (65535, 65535). * pg\_advisory\_xact\_lock\_shared(key bigint) Description: Obtains a shared transaction-level advisory lock. Return type: void * pg\_advisory\_xact\_lock\_shared(key1 int, key2 int) Description: Obtains a shared transaction-level advisory lock. Return type: void Note: **pg\_advisory\_xact\_lock\_shared** works in the same way as **pg\_advisory\_lock\_shared**, except the lock is automatically released at the end of the current transaction and cannot be released explicitly. * pg\_try\_advisory\_lock(key bigint) Description: Obtains an exclusive session-level advisory lock if available. Return type: Boolean Note: **pg\_try\_advisory\_lock** is similar to **pg\_advisory\_lock**, except **pg\_try\_advisory\_lock** does not block the resource until the resource is released. **pg\_try\_advisory\_lock** either immediately obtains the lock and returns **true** or returns **false**, which indicates the lock cannot be performed currently. * pg\_try\_advisory\_lock(key1 int, key2 int) Description: Obtains an exclusive session-level advisory lock if available. Return type: Boolean Note: Only users with the **sysadmin** permission can add session-level exclusive advisory locks to the key-value pair (65535, 65535). * pg\_try\_advisory\_lock\_shared(key bigint) Description: Obtains a shared session-level advisory lock if available. Return type: Boolean * pg\_try\_advisory\_lock\_shared(key1 int, key2 int) Description: Obtains a shared session-level advisory lock if available. Return type: Boolean Note: **pg\_try\_advisory\_lock\_shared** is similar to **pg\_try\_advisory\_lock**, except **pg\_try\_advisory\_lock\_shared** attempts to obtain a shared lock instead of an exclusive lock. * pg\_try\_advisory\_xact\_lock(key bigint) Description: Obtains an exclusive transaction-level advisory lock if available. Return type: Boolean * pg\_try\_advisory\_xact\_lock(key1 int, key2 int) Description: Obtains an exclusive transaction-level advisory lock if available. Return type: Boolean Note: **pg\_try\_advisory\_xact\_lock** works in the same way as **pg\_try\_advisory\_lock**, except the lock, if acquired, is automatically released at the end of the current transaction and cannot be released explicitly. Note: Only users with the **sysadmin** permission can add transaction-level exclusive advisory locks to the key-value pair (65535, 65535). * pg\_try\_advisory\_xact\_lock\_shared(key bigint) Description: Obtains a shared transaction-level advisory lock if available. Return type: Boolean * pg\_try\_advisory\_xact\_lock\_shared(key1 int, key2 int) Description: Obtains a shared transaction-level advisory lock if available. Return type: Boolean Note: **pg\_try\_advisory\_xact\_lock\_shared** works in the same way as **pg\_try\_advisory\_lock\_shared**, except the lock, if acquired, is automatically released at the end of the current transaction and cannot be released explicitly. * lock\_cluster\_ddl() Description: Attempts to obtain a session-level exclusive advisory lock for all active primary database nodes in openGauss. Return type: Boolean Note: Only users with the **sysadmin** permission can call this function. * unlock\_cluster\_ddl() Description: Attempts to add a session-level exclusive advisory lock on the primary database node. Return type: Boolean * get\_lock(text,text) Description: Adds a user lock to the database with a specified character string. The second parameter is the lock waiting time. Return type: Int * get\_lock(text,double) Description: Adds a user lock to the database with a specified character string. The second parameter is the lock waiting time. Return type: Int * get\_lock(text) Description: Adds a user lock to the database with a specified character string. Return type: Int * release\_lock(text) Description: Releases a specified lock. If the lock is successfully released, **1** is returned. If the current session does not hold the specified lock, **0** is returned. If the current lock does not exist (the lock must be held), **NULL** is returned. Return type: Int * is\_free\_lock(text) Description: Checks whether a string is idle. If the string is not locked, **1** is returned. Otherwise, **0** is returned. If other errors occur during the check, **NULL** is returned. Return type: Int * is\_used\_lock(text) Description: Checks who holds the lock of a string and returns the session ID of the corresponding user. If the specified lock is not held, **NULL** is returned. Return type: Bigint * clear\_all\_invalid\_locks() Description: Clears information about invalid locks in the lockname hash table and returns the number of cleared locks. Return type: Bigint * release\_all\_locks() Description: Releases all locks held by the current session and returns the number of release times. If a single string holds multiple locks, the number of release times is calculated based on the corresponding number instead of only once. Return type: Bigint * get\_all\_locks() Description: Queries all user locks in the current database and returns the names and holders of all user locks in the form of records. Return type: Record --- --- url: >- /en/docs/latest-lite/database_om_guide/after_you_run_the_du_command_to_query_data_file_size_in_the_xfs_file_system_the_query_result_is_grea.md --- # After You Run the du Command to Query Data File Size In the XFS File System, the Query Result Is Greater than the Actual File Size ## Symptom After you run the **du** command to query data file size in the database, the query result is probably greater than the actual file size. ``` du -sh file ``` ## Cause Analysis The XFS file system has a pre-assignment mechanism. The file size is determined by the **allocsize** parameter. The file size displayed by the **du** command includes the pre-assigned disk space. ## Procedure * Select the default value (64 KB) for the XFS file system mount parameter allocsize to eliminate the problem. * Add the **--apparent-size** parameter when using the **du** command to query the actual file size. ``` du -sh file --apparent-size ``` * If the XFS file system reclaims the pre-assigned space of a file, the **du** command displays the actual file size. --- --- url: >- /en/docs/latest/resource_pooling/after_you_run_the_du_command_to_query_data_file_size_in_the_xfs_file_system_the_query_result_is_grea.md --- # After You Run the du Command to Query Data File Size In the XFS File System, the Query Result Is Greater than the Actual File Size ## Symptom After you run the **du** command to query data file size in the cluster, the query result is probably greater than the actual file size. ``` du -sh file ``` ## Cause Analysis The XFS file system has a pre-assignment mechanism. The file size is determined by the **allocsize** parameter. The file size displayed by the **du** command includes the pre-assigned disk space. ## Procedure * Select the default value (64 KB) for the XFS file system mount parameter allocsize to eliminate the problem. * Add the **--apparent-size** parameter when using the **du** command to query the actual file size. ``` du -sh file --apparent-size ``` * If the XFS file system reclaims the pre-assigned space of a file, the **du** command displays the actual file size. --- --- url: /en/docs/latest-lite/brief_tutorial/aggregate_functions.md --- # Aggregate Functions * sum(expression) Description: Specifies the sum of expressions across all input values. Return type: Generally, it is the same as the argument data type. In the following cases, type conversion occurs: * **BIGINT** for **SMALLINT** or **INT** arguments * **NUMBER** for **BIGINT** arguments * **DOUBLE PRECISION** for floating-point arguments Example: ``` openGauss=# SELECT SUM(amount) FROM customer_t1; sum ------- 14200 (1 row) ``` * max(expression) Description: Specifies the maximum value of expressions across all input values. Parameter type: any array, numeric, string, or date/time type Return type: same as the argument data type Example: ``` openGauss=# SELECT MAX (c_customer_sk) FROM customer_t1; max ------ 9976 (1 row) ``` * min(expression) Description: Specifies the minimum value of expressions across all input values. Parameter type: any array, numeric, string, or date/time type Return type: same as the argument data type Example: ``` openGauss=# SELECT MIN (c_customer_sk) FROM customer_t1; min ------ 3869 (1 row) ``` * avg(expression) Description: Specifies the average (arithmetic mean) of all input values. Return type: **NUMBER** for any integer-type argument. **DOUBLE PRECISION** for floating-point arguments. Otherwise, it is the same as the argument data type. Example: ``` openGauss=# SELECT AVG(AMOUNT) FROM customer_t1; avg ----------------------- 2366.6666666666666667 (1 row) ``` * count(expression) Description: Specifies the number of input rows for which the value of the expression is **NULL**. Return type: BIGINT Example: ``` openGauss=# SELECT COUNT(c_customer_id) FROM customer_t1; count ------- 7 (1 row) ``` * count(\*) Description: Returns the number of input rows. Return type: BIGINT Example: ``` openGauss=# SELECT COUNT(*) FROM customer_t1; count ------- 8 (1 row) ``` * delta Description: Returns the difference between the current row and the previous row. Parameter: numeric Return type: numeric * mode() within group (order by value anyelement) Description: Returns the value with the highest occurrence frequency in a column. If multiple values have the same frequency, the smallest value is returned. The sorting mode is the same as the default sorting mode of the column type. **value** is an input parameter and can be of any type. Return type: same as the argument data type Example: ``` openGauss=# select mode() within group (order by value) from (values(1, 'a'), (2, 'b'), (2, 'c')) v(value, tag); mode ------ 2 (1 row) openGauss=# select mode() within group (order by tag) from (values(1, 'a'), (2, 'b'), (2, 'c')) v(value, tag); mode ------ a (1 row) ``` --- --- url: /en/docs/latest-lite/sql_reference/aggregate_functions.md --- # Aggregate Functions ## Aggregate Functions * sum(expression) Description: Specifies the sum of expressions across all input values. Return type: Generally, same as the argument data type. In the following cases, type conversion occurs: * **BIGINT** for **SMALLINT** or **INT** arguments * **NUMBER** for **BIGINT** arguments * **DOUBLE PRECISION** for floating-point arguments Example: ``` openGauss=# SELECT SUM(ss_ext_tax) FROM tpcds.STORE_SALES; sum -------------- 213267594.69 (1 row) ``` * max(expression) Description: Specifies the maximum value of expression across all input values. Parameter type: any array, numeric, string, or date/time type Return type: same as the argument type Example: ``` openGauss=# SELECT MAX(inv_quantity_on_hand) FROM tpcds.inventory; ``` * min(expression) Description: Specifies the minimum value of expression across all input values. Parameter type: any array, numeric, string, or date/time type Return type: same as the argument type Example: ``` openGauss=# SELECT MIN(inv_quantity_on_hand) FROM tpcds.inventory; min ----- 0 (1 row) ``` * avg(expression) Description: Specifies the average (arithmetic mean) of all input values. Return type: **NUMBER** for any integer-type argument. **DOUBLE PRECISION** for floating-point arguments. otherwise the same as the argument data type. Example: ``` openGauss=# SELECT AVG(inv_quantity_on_hand) FROM tpcds.inventory; avg ---------------------- 500.0387129084044604 (1 row) ``` * count(expression) Description: Specifies the number of input rows for which the value of the expression is not null. Return type: bigint Example: ``` openGauss=# SELECT COUNT(inv_quantity_on_hand) FROM tpcds.inventory; count ---------- 11158087 (1 row) ``` * count(\*) Description: Returns the number of input rows. Return type: bigint Example: ``` openGauss=# SELECT COUNT(*) FROM tpcds.inventory; count ---------- 11745000 (1 row) ``` * median(expression) \[over (query partition clause)] Description: Returns the median of an expression. **NULL** will be ignored by the median function during calculation. The **DISTINCT** keyword can be used to exclude duplicate records in an expression. The data type of the input expression can be numeric (including integer, double, and bigint) or interval. For other data types, the median cannot be calculated. Return type: double or interval Example: ``` select median(id) from (values(1), (2), (3), (4), (null)) test(id); median -------- 2.5 (1 row) ``` * array\_agg(expression) Description: Concatenates input values, including nulls, into an array. Return type: array of the argument type Example: ``` openGauss=# SELECT ARRAY_AGG(sr_fee) FROM tpcds.store_returns WHERE sr_customer_sk = 2; array_agg --------------- {22.18,63.21} (1 row) ``` * string\_agg(expression, delimiter) Description: Concatenates input values into a string, separated by delimiter. Return type: same as the argument type Example: ``` openGauss=# SELECT string_agg(sr_item_sk, ',') FROM tpcds.store_returns where sr_item_sk < 3; string_agg --------------------------------------------------------------------------------- ------------------------------ 1,2,1,2,2,1,1,2,2,1,2,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,2,1,1,1,1,1,1,1,1,1,2, 2,1,1,1,1,1,1,2,2,1,1,2,1,1,1 (1 row) ``` * listagg(expression \[, delimiter]) WITHIN GROUP(ORDER BY order-list) Description: Sorts aggregation column data according to the mode specified by **WITHIN GROUP** and concatenates the data to a string using the specified delimiter. * **expression**: Mandatory. It specifies an aggregation column name or a column-based valid expression. It does not support the **DISTINCT** keyword and the **VARIADIC** parameter. * **delimiter**: Optional. It specifies a delimiter, which can be a string constant or a deterministic expression based on a group of columns. The default value is empty. * **order-list**: Mandatory. It specifies the sorting mode in a group. Return type: text Example: The aggregation column is of the text character set type. ``` openGauss=# SELECT deptno, listagg(ename, ',') WITHIN GROUP(ORDER BY ename) AS employees FROM emp GROUP BY deptno; deptno | employees --------+-------------------------------------- 10 | CLARK,KING,MILLER 20 | ADAMS,FORD,JONES,SCOTT,SMITH 30 | ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD (3 rows) ``` The aggregation column is of the integer type. ``` openGauss=# SELECT deptno, listagg(mgrno, ',') WITHIN GROUP(ORDER BY mgrno NULLS FIRST) AS mgrnos FROM emp GROUP BY deptno; deptno | mgrnos --------+------------------------------- 10 | 7782,7839 20 | 7566,7566,7788,7839,7902 30 | 7698,7698,7698,7698,7698,7839 (3 rows) ``` The aggregation column is of the floating point type. ``` openGauss=# SELECT job, listagg(bonus, '($); ') WITHIN GROUP(ORDER BY bonus DESC) || '($)' AS bonus FROM emp GROUP BY job; job | bonus ------------+------------------------------------------------- CLERK | 10234.21($); 2000.80($); 1100.00($); 1000.22($) PRESIDENT | 23011.88($) ANALYST | 2002.12($); 1001.01($) MANAGER | 10000.01($); 2399.50($); 999.10($) SALESMAN | 1000.01($); 899.00($); 99.99($); 9.00($) (5 rows) ``` The aggregation column is of the time type. ``` openGauss=# SELECT deptno, listagg(hiredate, ', ') WITHIN GROUP(ORDER BY hiredate DESC) AS hiredates FROM emp GROUP BY deptno; deptno | hiredates --------+------------------------------------------------------------------------------------------------------------------------------ 10 | 1982-01-23 00:00:00, 1981-11-17 00:00:00, 1981-06-09 00:00:00 20 | 2001-04-02 00:00:00, 1999-12-17 00:00:00, 1987-05-23 00:00:00, 1987-04-19 00:00:00, 1981-12-03 00:00:00 30 | 2015-02-20 00:00:00, 2010-02-22 00:00:00, 1997-09-28 00:00:00, 1981-12-03 00:00:00, 1981-09-08 00:00:00, 1981-05-01 00:00:00 (3 rows) ``` The aggregation column is of the time interval type. ``` openGauss=# SELECT deptno, listagg(vacationTime, '; ') WITHIN GROUP(ORDER BY vacationTime DESC) AS vacationTime FROM emp GROUP BY deptno; deptno | vacationtime --------+------------------------------------------------------------------------------------ 10 | 1 year 30 days; 40 days; 10 days 20 | 70 days; 36 days; 9 days; 5 days 30 | 1 year 1 mon; 2 mons 10 days; 30 days; 12 days 12:00:00; 4 days 06:00:00; 24:00:00 (3 rows) ``` By default, the delimiter is empty. ``` openGauss=# SELECT deptno, listagg(job) WITHIN GROUP(ORDER BY job) AS jobs FROM emp GROUP BY deptno; deptno | jobs --------+---------------------------------------------- 10 | CLERKMANAGERPRESIDENT 20 | ANALYSTANALYSTCLERKCLERKMANAGER 30 | CLERKMANAGERSALESMANSALESMANSALESMANSALESMAN (3 rows) ``` When **listagg** is used as a window function, the **OVER** clause does not support the window sorting of **ORDER BY**, and the **listagg** column is an ordered aggregation of the corresponding groups. ``` openGauss=# SELECT deptno, mgrno, bonus, listagg(ename,'; ') WITHIN GROUP(ORDER BY hiredate) OVER(PARTITION BY deptno) AS employees FROM emp; deptno | mgrno | bonus | employees --------+-------+----------+------------------------------------------- 10 | 7839 | 10000.01 | CLARK; KING; MILLER 10 | | 23011.88 | CLARK; KING; MILLER 10 | 7782 | 10234.21 | CLARK; KING; MILLER 20 | 7566 | 2002.12 | FORD; SCOTT; ADAMS; SMITH; JONES 20 | 7566 | 1001.01 | FORD; SCOTT; ADAMS; SMITH; JONES 20 | 7788 | 1100.00 | FORD; SCOTT; ADAMS; SMITH; JONES 20 | 7902 | 2000.80 | FORD; SCOTT; ADAMS; SMITH; JONES 20 | 7839 | 999.10 | FORD; SCOTT; ADAMS; SMITH; JONES 30 | 7839 | 2399.50 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 9.00 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 1000.22 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 99.99 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 1000.01 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 899.00 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN (14 rows) ``` * group\_concat(\[DISTINCT | ALL] expression \[,expression ...] \[ORDER BY { expression \[ \[ ASC | DESC | USING operator ] | nlssort\_expression\_clause ] \[ NULLS { FIRST | LAST } ] } \[,...]] \[SEPARATOR str\_val]) Description: (Available only in B-compatible mode) The number of parameters is not fixed. Multiple columns can be concatenated. Aggregation column data is sorted based on the value of **ORDER BY** and concatenated into a character string using the separator. This function cannot be used as a window function. * **DISTINCT**: Optional. It deduplicates the result after each row is concatenated. * **expression**: Mandatory. It specifies the aggregation column name or a valid column-based expression. * **ORDER BY**: Optional. It is followed by a variable expression and sorting rule. The group\_concat function does not support the (ORDER BY + number) format. * **SEPARATOR**: Optional. It is followed by a CONST character (string). This separator is used to concatenate the expression results of two adjacent lines in a group. If this parameter is not specified, **','** is used by default. * When both DISTINCT and ORDER BY are specified, all ORDER BY expressions of openGauss must be in DISTINCT expressions. Otherwise, an error is reported. Return type: text Example: Set **separator** to **';'**. ``` test=# select id, group_concat(v separator ';') from t group by id order by id asc; id | group_concat ----+-------------- 1 | A;C;A 2 | B;D;B (2 rows) ``` By default, the separator is ','. ``` test=# select id, group_concat(id,v) from t group by id order by id asc; id | group_concat ----+-------------- 1 | 1A,1C,1A 2 | 2B,2D,2B (2 rows) ``` The aggregation column is of the text character set type. ``` test=# select id, group_concat(v) from t group by id order by id asc; id | group_concat ----+-------------- 1 | A,C,A 2 | B,D,B (2 rows) ``` The aggregation column is of the integer type. ``` test=# select id, group_concat(v separator ';') from t group by id order by id asc; id | group_concat ----+-------------- 1 | 50;99 2 | 20;100 (2 rows) ``` The aggregation column is of the floating point type. ``` test=# select id, group_concat(v separator ';') from t group by id order by id asc; id | group_concat ----+-------------- 1 | 50.11;99.33 2 | 20.22;100.44 (2 rows) ``` The aggregation column is of the time type. ``` test=# select id, group_concat(hiredate separator ';') from t group by id order by id asc; id | group_concat ----+------------------------------------------------------- 1 | 2022-08-22 10:51:29.374948;2022-08-22 10:51:29.374948 2 | 2022-08-22 10:51:29.374948;2022-08-22 10:51:29.374948 (2 rows) ``` The aggregation column is of the binary type. ``` test=# select id, group_concat(v separator ';') from t group by id order by id asc; id | group_concat ----+-------------- 1 | 19;1B 2 | 1A;1C (2 rows) ``` The aggregation column is of the time interval type. ``` test=# select id, group_concat(vacationt separator ';') from t group by id order by id asc; id | group_concat ----+----------------------------------------------------- 1 | 8785 days 11:04:01.510189;8783 days 11:04:01.510189 2 | 8784 days 11:04:01.510189;8782 days 11:04:01.510189 (2 rows) ``` Use DISTINCT to deduplicate data. ``` test=# select id, group_concat(distinct v) from t group by id order by id asc; id | group_concat ----+-------------- 1 | A,C 2 | B,D (2 rows) ``` Use ORDER BY to sort data. ``` test=# select id, group_concat(v order by v desc) from t group by id order by id asc; id | group_concat ----+-------------- 1 | C,A,A 2 | D,B,B (2 rows) ``` * covar\_pop(Y, X) Description: Specifies the overall covariance. Return type: double precision Example: ``` openGauss=# SELECT COVAR_POP(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; covar_pop ------------------ 829.749627587403 (1 row) ``` * covar\_samp(Y, X) Description: Specifies the sample covariance. Return type: double precision Example: ``` openGauss=# SELECT COVAR_SAMP(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; covar_samp ------------------ 830.052235037289 (1 row) ``` * stddev\_pop(expression) Description: Specifies the overall standard deviation. Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT STDDEV_POP(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; stddev_pop ------------------ 289.224294957556 (1 row) ``` * stddev\_samp(expression) Description: Specifies the sample standard deviation of the input values. Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT STDDEV_SAMP(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; stddev_samp ------------------ 289.224359757315 (1 row) ``` * var\_pop(expression) Description: Specifies the population variance of the input values (square of the population standard deviation). Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT VAR_POP(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; var_pop -------------------- 83650.692793695475 (1 row) ``` * var\_samp(expression) Description: Specifies the sample variance of the input values (square of the sample standard deviation). Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT VAR_SAMP(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; var_samp -------------------- 83650.730277028768 (1 row) ``` * bit\_and(expression) Description: bitwise AND of all non-null input values, or null if none Return type: same as the argument type Example: ``` openGauss=# SELECT BIT_AND(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; bit_and --------- 0 (1 row) ``` * bit\_or(expression) Description: bitwise OR of all non-null input values, or null if none Return type: same as the argument type Example: ``` openGauss=# SELECT BIT_OR(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; bit_or -------- 1023 (1 row) ``` * bool\_and(expression) Description: Its value is **true** if all input values are **true**, otherwise **false**. Return type: Boolean Example: ``` openGauss=# SELECT bool_and(100 <2500); bool_and ---------- t (1 row) ``` * bool\_or(expression) Description: Its value is **true** if at least one input value is **true**, otherwise **false**. Return type: Boolean Example: ``` openGauss=# SELECT bool_or(100 <2500); bool_or ---------- t (1 row) ``` * corr(Y, X) Description: Specifies the correlation coefficient. Return type: double precision Example: ``` openGauss=# SELECT CORR(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; corr ------------------- .0381383624904186 (1 row) ``` * corr\_s(expr1, expr2, return\_mode) Description:Spearman correlation coefficient Return type:double precision Return Value: The `return_mode` parameter is optional; if not specified, the function returns the Spearman's rank correlation coefficient (the return value is the same as when `return_mode=COEFFICIENT`). If specified, the value of `return_mode` must be one of the following five options. Example: ``` openGauss=# CREATE TABLE corr_t1(a int, b int); CREATE TABLE openGauss=# INSERT INTO corr_t1 VALUES (NULL,11),(1,2),(1,3),(2,4),(2,5),(3,6); INSERT 0 6 openGauss=# SELECT CORR_S(a,b) FROM corr_t1; corr_s ------------------ .948683298050514 (1 row) openGauss=# SELECT CORR_S(a,b,'COEFFICIENT') FROM corr_t1; corr_s ------------------ .948683298050514 (1 row) openGauss=# SELECT CORR_S(a,b,'ONE_SIDED_SIG') FROM corr_t1; corr_s -------------------- .00692341649442951 (1 row) ``` * corr\_k(expr1, expr2, return\_mode) Description: Kendall's tau-b correlation coefficient Return type:double precision Return Value: The `return_mode` parameter is optional; if not specified, the function returns Kendall's tau-b correlation coefficient (the return value is the same as when `return_mode=COEFFICIENT`). If specified, the description of the return value is the same as that for the `corr_s` function mentioned above. Example: ``` openGauss=# SELECT CORR_K(a,b) FROM corr_t1; corr_k ------------------ .894427190999916 (1 row) openGauss=# SELECT CORR_K(a,b,'COEFFICIENT') FROM corr_t1; corr_k ------------------ .894427190999916 (1 row) openGauss=# SELECT CORR_K(a,b,'ONE_SIDED_SIG') FROM corr_t1; corr_k ------------------- .0142298684581553 (1 row) ``` * every(expression) Description: Equivalent to **bool\_and** Return type: Boolean Example: ``` openGauss=# SELECT every(100 <2500); every ------- t (1 row) ``` * regr\_avgx(Y, X) Description: Specifies the average of the independent variable (**sum(X)/N**). Return type: double precision Example: ``` openGauss=# SELECT REGR_AVGX(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_avgx ------------------ 578.606576740795 (1 row) ``` * regr\_avgy(Y, X) Description: Specifies the average of the dependent variable (**sum(Y)/N**). Return type: double precision Example: ``` openGauss=# SELECT REGR_AVGY(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_avgy ------------------ 50.0136711629602 (1 row) ``` * regr\_count(Y, X) Description: Specifies the number of input rows in which both expressions are non-null. Return type: bigint Example: ``` openGauss=# SELECT REGR_COUNT(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_count ------------ 2743 (1 row) ``` * regr\_intercept(Y, X) Description: Specifies the y-intercept of the least-squares-fit linear equation determined by the (X, Y) pairs. Return type: double precision Example: ``` openGauss=# SELECT REGR_INTERCEPT(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_intercept ------------------ 49.2040847848607 (1 row) ``` * regr\_r2(Y, X) Description: Specifies the square of the correlation coefficient. Return type: double precision Example: ``` openGauss=# SELECT REGR_R2(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_r2 -------------------- .00145453469345058 (1 row) ``` * regr\_slope(Y, X) Description: Specifies the slope of the least-squares-fit linear equation determined by the (X, Y) pairs. Return type: double precision Example: ``` openGauss=# SELECT REGR_SLOPE(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_slope -------------------- .00139920009665259 (1 row) ``` * regr\_sxx(Y, X) Description: **sum(X^2) - sum(X)^2/N**(sum of squares of the independent variables) Return type: double precision Example: ``` openGauss=# SELECT REGR_SXX(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_sxx ------------------ 1626645991.46135 (1 row) ``` * regr\_sxy(Y, X) Description: **sum(X\*Y) - sum(X) \* sum(Y)/N** ("sum of products" of independent times dependent variable) Return type: double precision Example: ``` openGauss=# SELECT REGR_SXY(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_sxy ------------------ 2276003.22847225 (1 row) ``` * regr\_syy(Y, X) Description: **sum(Y^2) - sum(Y)^2/N** ("sum of squares" of the dependent variable) Return type: double precision Example: ``` openGauss=# SELECT REGR_SYY(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_syy ----------------- 2189417.6547314 (1 row) ``` * stddev(expression) Description: Specifies the alias of **stddev\_samp**. Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT STDDEV(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; stddev ------------------ 289.224359757315 (1 row) ``` * variance(expexpression,ression) Description: Specifies the alias of **var\_samp**. Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT VARIANCE(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; variance -------------------- 83650.730277028768 (1 row) ``` * delta Description: Returns the difference between the current row and the previous row. Parameter: numeric Return type: numeric * checksum(expression) Description: Returns the **CHECKSUM** value of all input values. This function can be used to check whether the data in the tables is the same before and after the backup, restoration, or migration of the openGauss database (databases other than openGauss are not supported). Before and after database backup, database restoration, or data migration, you need to manually run SQL commands to obtain the execution results. Compare the obtained execution results to check whether the data in the tables before and after the backup or migration is the same. > \[!NOTE]NOTE > > * For large tables, the execution of the **CHECKSUM** function may take a long time. > * If the **CHECKSUM** values of two tables are different, it indicates that the contents of the two tables are different. Using the hash function in the **CHECKSUM** function may incur conflicts. There is low possibility that two tables with different contents may have the same **CHECKSUM** value. The same problem may occur when **CHECKSUM** is used for columns. > * If the time type is timestamp, timestamptz, or smalldatetime, ensure that the time zone settings are the same when calculating the **CHECKSUM** value. * If the **CHECKSUM** value of a column is calculated and the column type can be changed to TEXT by default, set *expression* to the column name. * If the **CHECKSUM** value of a column is calculated and the column type cannot be converted to TEXT by default, set *expression* to *Column name*\*\*::TEXT\*\*. * If the **CHECKSUM** value of all columns is calculated, set *expression* to *Table name*\*\*::TEXT\*\*. The following types of data can be converted into TEXT types by default: char, name, int8, int2, int1, int4, raw, pg\_node\_tree, float4, float8, bpchar, varchar, nvarchar, nvarchar2, date, timestamp, timestamptz, numeric, and smalldatetime. Other types need to be forcibly converted to TEXT. Return type: numeric Example: The following shows the **CHECKSUM** value of a column that can be converted to the TEXT type by default: ``` openGauss=# SELECT CHECKSUM(inv_quantity_on_hand) FROM tpcds.inventory; checksum ------------------- 24417258945265247 (1 row) ``` The following shows the **CHECKSUM** value of a column that cannot be converted to the TEXT type by default. Note that the **CHECKSUM** parameter is set to *Column name*\*\*::TEXT\*\*. ``` openGauss=# SELECT CHECKSUM(inv_quantity_on_hand::TEXT) FROM tpcds.inventory; checksum ------------------- 24417258945265247 (1 row) ``` The following shows the **CHECKSUM** value of all columns in a table. Note that the **CHECKSUM** parameter is set to *Table name*\*\*::TEXT\*\*. The table name is not modified by its schema. ``` openGauss=# SELECT CHECKSUM(inventory::TEXT) FROM tpcds.inventory; checksum ------------------- 25223696246875800 (1 row) ``` * first(anyelement) Description: Returns the first non-null input. Return type: anyelement ``` openGauss=# select * from tba; name ----- A A D (4 rows) openGauss=# select first(name) from tba; first ----- A (1 rows) ``` * last(anyelement) Description: Returns the last non-null input. Return type: anyelement ``` openGauss=# select * from tba; name ----- A A D (4 rows) openGauss=# select last(name) from tba; last ----- D (1 rows) ``` * mode() within group (order by value anyelement) Description: Returns the value with the highest occurrence frequency in a column. If multiple values have the same frequency, the smallest value is returned. The sorting mode is the same as the default sorting mode of the column type. **value** is an input parameter and can be of any type. Return type: same as the input parameter type Example: ``` openGauss=# select mode() within group (order by value) from (values(1, 'a'), (2, 'b'), (2, 'c')) v(value, tag); mode ------ 2 (1 row) openGauss=# select mode() within group (order by tag) from (values(1, 'a'), (2, 'b'), (2, 'c')) v(value, tag); mode ------ a (1 row) ``` * json\_agg(any) Description: Aggregates values into a JSON array. Return type: array-json Example: ``` openGauss=# select * from classes; name | score -----+------- A | 2 A | 3 D | 5 D | (4 rows) ``` ``` openGauss=# select name, json_agg(score) score from classes group by name order by name; name | score -----+----------------- A | [2, 3] D | [5, null] | [null] (3 rows) ``` * json\_object\_agg(any, any) Description: Aggregates values into a JSON object. Return type: object-json Example: ``` openGauss=# select * from classes; name | score -----+------- A | 2 A | 3 D | 5 D | (4 rows) ``` ``` openGauss=# select json_object_agg(name, score) from classes group by name order by name; json_object_agg ------------------------- { "A" : 2, "A" : 3 } { "D" : 5, "D" : null } (2 rows) ``` * cume\_dist(expression \[,expression] ) WITHIN GROUP (ORDER BY { order-list \[ ASC | DESC ] \[ NULLS { FIRST | LAST } ] } \[,...]) Description: Calculate the cumulative distribution of the assumed rows and corresponding sorting criteria identified by the parameters of the function in the aggregated group rows. in other words, The proportion of the total number of rows in the sorting partition where the value of expression is the same as the value of the last row after sorting * **expression**: Mandatory. specify the rows to be inserted into a set of rows. This expression must return a value of a built-in data type. The expression must be a constant or variable of a constant or variable. Multiple parameters can be entered. The number of parameters must be consistent with the order list and the number of parameters. * **order-list**: Mandatory. The sorting key can be a column name or a sorting key expression. Return type: float Example: Insert the input 4 into a column sorted by c1, with 4 placed at position 8. Therefore, the function returns a value of 8/14. ``` openGauss=# create table aggregates_hypothetical(c1 int, c2 NUMBER(8,2), c3 varchar(20), c4 timestamp); CREATE TABLE openGauss=# insert into aggregates_hypothetical values openGauss-# (1,0.1,'1','2024-09-01 09:22:00'), openGauss-# (2,0.2,'2','2024-09-02 09:22:00'), openGauss-# (3,0.1,'3','2024-09-03 09:22:00'), openGauss-# (3,0.2,'3','2024-09-04 09:22:00'), openGauss-# (3,0.3,'3','2024-09-05 09:22:00'), openGauss-# (3,0.3,'3','2024-09-05 09:22:00'), openGauss-# (4,0.2,'4','2024-09-06 09:22:00'), openGauss-# (5,0.2,'5','2024-09-07 09:22:00'), openGauss-# (6,0.2,'6','2024-09-08 09:22:00'), openGauss-# (7,0.2,'7','2024-09-09 09:22:00'), openGauss-# (8,0.2,'8','2024-09-10 09:22:00'), openGauss-# (9,0.2,'9','2024-09-11 09:22:00'), openGauss-# (10,0.2,'10','2024-09-12 09:22:00'); INSERT 0 13 openGauss=# select cume_dist(4) within group (order by c1) from aggregates_hypothetical; cume_dist ------------------ .571428571428571 (1 row) ``` Example: Insert the input (3,0.2) into the column sorted by c1 and c2, and place it in the 5th position. Therefore, the function returns a value of 5/14 ``` openGauss=# select cume_dist(3,0.2) within group (order by c1,c2) from aggregates_hypothetical; cume_dist ------------------ .357142857142857 (1 row) ``` Example: Insert the input string into a column sorted by c1, perform type conversion, and then perform calculations ``` select cume_dist('1') within group (order by c1) from test_aggregate; cume_dist ------------------ .142857142857143 (1 row) ``` * rank( expression \[,expression] ) WITHIN GROUP (ORDER BY { order-list \[ ASC | DESC ] \[ NULLS { FIRST | LAST } ] } \[,...]) Description: Calculate the ranking of a hypothetical row identified by the parameters of a function relative to a given sorting criterion. The ranking values of the rank function are not continuous. * **expression**: Mandatory. specify the rows to be inserted into a set of rows. This expression must return a value of a built-in data type. The expression must be a constant or variable of a constant or variable. Multiple parameters can be entered. The number of parameters must be consistent with the order list and the number of parameters. * **order-list**:Mandatory.The sorting key can be a column name or a sorting key expression. Return type: int Example Using c1 as the sorting column, calculate the ranking value of the input parameter in the sorting column. Duplicate columns are also included in the ranking, so the ranking is discontinuous ``` openGauss=# select rank(3) within group (order by c1) from aggregates_hypothetical; rank ------ 3 (1 row) openGauss=# select rank(4) within group (order by c1) from aggregates_hypothetical; rank ------ 7 (1 row) ``` Example Column sorted by c1, c2 ``` openGauss=# select rank(4,0.2) within group (order by c1,c2) from aggregates_hypothetical; rank ------ 7 (1 row) ``` * dense\_rank( expression \[,expression] ) WITHIN GROUP (ORDER BY { order-list \[ ASC | DESC ] \[ NULLS { FIRST | LAST } ] } \[,...]) Description: Calculate the ranking of a hypothetical row identified by the parameters of a function relative to a given sorting criterion. The ranking value of the dense\_rank function is continuous * **expression**: Mandatory. specify the rows to be inserted into a set of rows. This expression must return a value of a built-in data type. The expression must be a constant or variable of a constant or variable. Multiple parameters can be entered. The number of parameters must be consistent with the order list and the number of parameters. * **order-list**:Mandatory.The sorting key can be a column name or a sorting key expression. Return type: int Example Using c1 as the sorting column, calculate the ranking value of the input parameter in the sorting column. Duplicate columns are not included in the ranking, so the ranking is continuous ``` openGauss=# select dense_rank(3) within group (order by c1) from aggregates_hypothetical; dense_rank ------------ 3 (1 row) openGauss=# select dense_rank(4) within group (order by c1) from aggregates_hypothetical; dense_rank ------------ 4 (1 row) ``` Example Column sorted by c1, c2 ``` openGauss=# select dense_rank(4,0.2) within group (order by c1,c2) from aggregates_hypothetical;; dense_rank ------------ 6 (1 row) ``` * percent\_rank( expression \[,expression] ) WITHIN GROUP (ORDER BY { order-list \[ ASC | DESC ] \[ NULLS { FIRST | LAST } ] } \[,...]) Description: Calculate the percentage of the relative position of the assumed rows identified by the parameters of the function with respect to a given sorting criterion. The calculation formula is (rank -1)/(totals -1). * **expression**: Mandatory. specify the rows to be inserted into a set of rows. This expression must return a value of a built-in data type. The expression must be a constant or variable of a constant or variable. Multiple parameters can be entered. The number of parameters must be consistent with the order list and the number of parameters. * **order-list**:Mandatory.The sorting key can be a column name or a sorting key expression. Return type: float Example The percentage of the input value in the position of the current ranking column sorted by c1 ``` openGauss=# select percent_rank(4) within group (order by c1) from aggregates_hypothetical; percent_rank ------------------- 0.461538461538462 (1 row) ``` Example Column sorted by c1, c2 ``` openGauss=# select percent_rank(3,0.2) within group (order by c1,c2) from aggregates_hypothetical; percent_rank ------------------- 0.230769230769231 (1 row) ``` --- --- url: /en/docs/latest/sql_reference/aggregate_functions.md --- # Aggregate Functions ## Aggregate Functions * sum(expression) Description: Specifies the sum of expressions across all input values. Return type: Generally, same as the argument data type. In the following cases, type conversion occurs: * **BIGINT** for **SMALLINT** or **INT** arguments * **NUMBER** for **BIGINT** arguments * **DOUBLE PRECISION** for floating-point arguments Example: ``` openGauss=# SELECT SUM(ss_ext_tax) FROM tpcds.STORE_SALES; sum -------------- 213267594.69 (1 row) ``` * max(expression) Description: Specifies the maximum value of expression across all input values. Parameter type: any array, numeric, string, date/time type, or IPv4 and IPv6 addresses (INET and CIDR data types) Return type: same as the argument type Example: ``` openGauss=# SELECT MAX(inv_quantity_on_hand) FROM tpcds.inventory; ``` * min(expression) Description: Specifies the minimum value of expression across all input values. Parameter type: any array, numeric, string, date/time type, or IPv4 and IPv6 addresses (INET and CIDR data types) Return type: same as the argument type Example: ``` openGauss=# SELECT MIN(inv_quantity_on_hand) FROM tpcds.inventory; min ----- 0 (1 row) ``` * avg(expression) Description: Specifies the average (arithmetic mean) of all input values. Return type: **NUMBER** for any integer-type argument. **DOUBLE PRECISION** for floating-point arguments. otherwise the same as the argument data type. Example: ``` openGauss=# SELECT AVG(inv_quantity_on_hand) FROM tpcds.inventory; avg ---------------------- 500.0387129084044604 (1 row) ``` * count(expression) Description: Specifies the number of input rows for which the value of the expression is not null. Return type: bigint Example: ``` openGauss=# SELECT COUNT(inv_quantity_on_hand) FROM tpcds.inventory; count ---------- 11158087 (1 row) ``` * count(\*) Description: Returns the number of input rows. Return type: bigint Example: ``` openGauss=# SELECT COUNT(*) FROM tpcds.inventory; count ---------- 11745000 (1 row) ``` * median(expression) \[over (query partition clause)] Description: Returns the median of an expression. **NULL** will be ignored by the median function during calculation. The **DISTINCT** keyword can be used to exclude duplicate records in an expression. The data type of the input expression can be numeric (including integer, double, and bigint) or interval. For other data types, the median cannot be calculated. Return type: double or interval Example: ``` select median(id) from (values(1), (2), (3), (4), (null)) test(id); median -------- 2.5 (1 row) ``` * array\_agg(expression) Description: Concatenates input values, including nulls, into an array. Return type: array of the argument type Example: ``` openGauss=# SELECT ARRAY_AGG(sr_fee) FROM tpcds.store_returns WHERE sr_customer_sk = 2; array_agg --------------- {22.18,63.21} (1 row) ``` * string\_agg(expression, delimiter) Description: Concatenates input values into a string, separated by delimiter. Return type: same as the argument type Example: ``` openGauss=# SELECT string_agg(sr_item_sk, ',') FROM tpcds.store_returns where sr_item_sk < 3; string_agg --------------------------------------------------------------------------------- ------------------------------ 1,2,1,2,2,1,1,2,2,1,2,1,2,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,2,1,1,1,1,1,1,1,1,1,2, 2,1,1,1,1,1,1,2,2,1,1,2,1,1,1 (1 row) ``` * listagg(expression \[, delimiter]) WITHIN GROUP(ORDER BY order-list) Description: Sorts aggregation column data according to the mode specified by **WITHIN GROUP** and concatenates the data to a string using the specified delimiter. * **expression**: Mandatory. It specifies an aggregation column name or a column-based valid expression. It does not support the **DISTINCT** keyword and the **VARIADIC** parameter. * **delimiter**: Optional. It specifies a delimiter, which can be a string constant or a deterministic expression based on a group of columns. The default value is empty. * **order-list**: Mandatory. It specifies the sorting mode in a group. Return type: text Example: The aggregation column is of the text character set type. ``` openGauss=# SELECT deptno, listagg(ename, ',') WITHIN GROUP(ORDER BY ename) AS employees FROM emp GROUP BY deptno; deptno | employees --------+-------------------------------------- 10 | CLARK,KING,MILLER 20 | ADAMS,FORD,JONES,SCOTT,SMITH 30 | ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD (3 rows) ``` The aggregation column is of the integer type. ``` openGauss=# SELECT deptno, listagg(mgrno, ',') WITHIN GROUP(ORDER BY mgrno NULLS FIRST) AS mgrnos FROM emp GROUP BY deptno; deptno | mgrnos --------+------------------------------- 10 | 7782,7839 20 | 7566,7566,7788,7839,7902 30 | 7698,7698,7698,7698,7698,7839 (3 rows) ``` The aggregation column is of the floating point type. ``` openGauss=# SELECT job, listagg(bonus, '($); ') WITHIN GROUP(ORDER BY bonus DESC) || '($)' AS bonus FROM emp GROUP BY job; job | bonus ------------+------------------------------------------------- CLERK | 10234.21($); 2000.80($); 1100.00($); 1000.22($) PRESIDENT | 23011.88($) ANALYST | 2002.12($); 1001.01($) MANAGER | 10000.01($); 2399.50($); 999.10($) SALESMAN | 1000.01($); 899.00($); 99.99($); 9.00($) (5 rows) ``` The aggregation column is of the time type. ``` openGauss=# SELECT deptno, listagg(hiredate, ', ') WITHIN GROUP(ORDER BY hiredate DESC) AS hiredates FROM emp GROUP BY deptno; deptno | hiredates --------+------------------------------------------------------------------------------------------------------------------------------ 10 | 1982-01-23 00:00:00, 1981-11-17 00:00:00, 1981-06-09 00:00:00 20 | 2001-04-02 00:00:00, 1999-12-17 00:00:00, 1987-05-23 00:00:00, 1987-04-19 00:00:00, 1981-12-03 00:00:00 30 | 2015-02-20 00:00:00, 2010-02-22 00:00:00, 1997-09-28 00:00:00, 1981-12-03 00:00:00, 1981-09-08 00:00:00, 1981-05-01 00:00:00 (3 rows) ``` The aggregation column is of the time interval type. ``` openGauss=# SELECT deptno, listagg(vacationTime, '; ') WITHIN GROUP(ORDER BY vacationTime DESC) AS vacationTime FROM emp GROUP BY deptno; deptno | vacationtime --------+------------------------------------------------------------------------------------ 10 | 1 year 30 days; 40 days; 10 days 20 | 70 days; 36 days; 9 days; 5 days 30 | 1 year 1 mon; 2 mons 10 days; 30 days; 12 days 12:00:00; 4 days 06:00:00; 24:00:00 (3 rows) ``` By default, the delimiter is empty. ``` openGauss=# SELECT deptno, listagg(job) WITHIN GROUP(ORDER BY job) AS jobs FROM emp GROUP BY deptno; deptno | jobs --------+---------------------------------------------- 10 | CLERKMANAGERPRESIDENT 20 | ANALYSTANALYSTCLERKCLERKMANAGER 30 | CLERKMANAGERSALESMANSALESMANSALESMANSALESMAN (3 rows) ``` When **listagg** is used as a window function, the **OVER** clause does not support the window sorting of **ORDER BY**, and the **listagg** column is an ordered aggregation of the corresponding groups. ``` openGauss=# SELECT deptno, mgrno, bonus, listagg(ename,'; ') WITHIN GROUP(ORDER BY hiredate) OVER(PARTITION BY deptno) AS employees FROM emp; deptno | mgrno | bonus | employees --------+-------+----------+------------------------------------------- 10 | 7839 | 10000.01 | CLARK; KING; MILLER 10 | | 23011.88 | CLARK; KING; MILLER 10 | 7782 | 10234.21 | CLARK; KING; MILLER 20 | 7566 | 2002.12 | FORD; SCOTT; ADAMS; SMITH; JONES 20 | 7566 | 1001.01 | FORD; SCOTT; ADAMS; SMITH; JONES 20 | 7788 | 1100.00 | FORD; SCOTT; ADAMS; SMITH; JONES 20 | 7902 | 2000.80 | FORD; SCOTT; ADAMS; SMITH; JONES 20 | 7839 | 999.10 | FORD; SCOTT; ADAMS; SMITH; JONES 30 | 7839 | 2399.50 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 9.00 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 1000.22 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 99.99 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 1000.01 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN 30 | 7698 | 899.00 | BLAKE; TURNER; JAMES; MARTIN; WARD; ALLEN (14 rows) ``` * group\_concat(\[DISTINCT | ALL] expression \[,expression ...] \[ORDER BY { expression \[ \[ ASC | DESC | USING operator ] | nlssort\_expression\_clause ] \[ NULLS { FIRST | LAST } ] } \[,...]] \[SEPARATOR str\_val]) Description: (Available only in B-compatible mode) The number of parameters is not fixed. Multiple columns can be concatenated. Aggregation column data is sorted based on the value of **ORDER BY** and concatenated into a character string using the separator. This function cannot be used as a window function. * **DISTINCT**: Optional. It deduplicates the result after each row is concatenated. * **expression**: Mandatory. It specifies the aggregation column name or a valid column-based expression. * **ORDER BY**: Optional. It is followed by a variable expression and sorting rule. The group\_concat function does not support the (ORDER BY + number) format. * **SEPARATOR**: Optional. It is followed by a CONST character (string). This separator is used to concatenate the expression results of two adjacent lines in a group. If this parameter is not specified, **','** is used by default. * When both DISTINCT and ORDER BY are specified, all ORDER BY expressions of openGauss must be in DISTINCT expressions. Otherwise, an error is reported. Return type: text Example: Set **separator** to **';'**. ``` test=# select id, group_concat(v separator ';') from t group by id order by id asc; id | group_concat ----+-------------- 1 | A;C;A 2 | B;D;B (2 rows) ``` By default, the separator is **','**. ``` test=# select id, group_concat(id,v) from t group by id order by id asc; id | group_concat ----+-------------- 1 | 1A,1C,1A 2 | 2B,2D,2B (2 rows) ``` The aggregation column is of the text character set type. ``` test=# select id, group_concat(v) from t group by id order by id asc; id | group_concat ----+-------------- 1 | A,C,A 2 | B,D,B (2 rows) ``` The aggregation column is of the integer type. ``` test=# select id, group_concat(v separator ';') from t group by id order by id asc; id | group_concat ----+-------------- 1 | 50;99 2 | 20;100 (2 rows) ``` The aggregation column is of the floating point type. ``` test=# select id, group_concat(v separator ';') from t group by id order by id asc; id | group_concat ----+-------------- 1 | 50.11;99.33 2 | 20.22;100.44 (2 rows) ``` The aggregation column is of the time type. ``` test=# select id, group_concat(hiredate separator ';') from t group by id order by id asc; id | group_concat ----+------------------------------------------------------- 1 | 2022-08-22 10:51:29.374948;2022-08-22 10:51:29.374948 2 | 2022-08-22 10:51:29.374948;2022-08-22 10:51:29.374948 (2 rows) ``` The aggregation column is of the binary type. ``` test=# select id, group_concat(v separator ';') from t group by id order by id asc; id | group_concat ----+-------------- 1 | 19;1B 2 | 1A;1C (2 rows) ``` The aggregation column is of the time interval type. ``` test=# select id, group_concat(vacationt separator ';') from t group by id order by id asc; id | group_concat ----+----------------------------------------------------- 1 | 8785 days 11:04:01.510189;8783 days 11:04:01.510189 2 | 8784 days 11:04:01.510189;8782 days 11:04:01.510189 (2 rows) ``` Use DISTINCT to deduplicate data. ``` test=# select id, group_concat(distinct v) from t group by id order by id asc; id | group_concat ----+-------------- 1 | A,C 2 | B,D (2 rows) ``` Use ORDER BY to sort data. ``` test=# select id, group_concat(v order by v desc) from t group by id order by id asc; id | group_concat ----+-------------- 1 | C,A,A 2 | D,B,B (2 rows) ``` * covar\_pop(Y, X) Description: Specifies the overall covariance. Return type: double precision Example: ``` openGauss=# SELECT COVAR_POP(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; covar_pop ------------------ 829.749627587403 (1 row) ``` * covar\_samp(Y, X) Description: Specifies the sample covariance. Return type: double precision Example: ``` openGauss=# SELECT COVAR_SAMP(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; covar_samp ------------------ 830.052235037289 (1 row) ``` * stddev\_pop(expression) Description: Specifies the overall standard deviation. Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT STDDEV_POP(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; stddev_pop ------------------ 289.224294957556 (1 row) ``` * stddev\_samp(expression) Description: Specifies the sample standard deviation of the input values. Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT STDDEV_SAMP(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; stddev_samp ------------------ 289.224359757315 (1 row) ``` * var\_pop(expression) Description: Specifies the population variance of the input values (square of the population standard deviation). Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT VAR_POP(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; var_pop -------------------- 83650.692793695475 (1 row) ``` * var\_samp(expression) Description: Specifies the sample variance of the input values (square of the sample standard deviation). Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT VAR_SAMP(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; var_samp -------------------- 83650.730277028768 (1 row) ``` * bit\_and(expression) Description: bitwise AND of all non-null input values, or null if none Return type: same as the argument type Example: ``` openGauss=# SELECT BIT_AND(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; bit_and --------- 0 (1 row) ``` * bit\_or(expression) Description: bitwise OR of all non-null input values, or null if none Return type: same as the argument type Example: ``` openGauss=# SELECT BIT_OR(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; bit_or -------- 1023 (1 row) ``` * bool\_and(expression) Description: Its value is **true** if all input values are **true**, otherwise **false**. Return type: Boolean Example: ``` openGauss=# SELECT bool_and(100 <2500); bool_and ---------- t (1 row) ``` * bool\_or(expression) Description: Its value is **true** if at least one input value is **true**, otherwise **false**. Return type: Boolean Example: ``` openGauss=# SELECT bool_or(100 <2500); bool_or ---------- t (1 row) ``` * corr(Y, X) Description: Specifies the correlation coefficient. Return type: double precision Example: ``` openGauss=# SELECT CORR(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; corr ------------------- .0381383624904186 (1 row) ``` * corr\_s(expr1, expr2, return\_mode) Description:Spearman correlation coefficient Return type:double precision Return Value: The `return_mode` parameter is optional; if not specified, the function returns the Spearman's rank correlation coefficient (the return value is the same as when `return_mode=COEFFICIENT`). If specified, the value of `return_mode` must be one of the following five options. Example: ``` openGauss=# CREATE TABLE corr_t1(a int, b int); CREATE TABLE openGauss=# INSERT INTO corr_t1 VALUES (NULL,11),(1,2),(1,3),(2,4),(2,5),(3,6); INSERT 0 6 openGauss=# SELECT CORR_S(a,b) FROM corr_t1; corr_s ------------------ .948683298050514 (1 row) openGauss=# SELECT CORR_S(a,b,'COEFFICIENT') FROM corr_t1; corr_s ------------------ .948683298050514 (1 row) openGauss=# SELECT CORR_S(a,b,'ONE_SIDED_SIG') FROM corr_t1; corr_s -------------------- .00692341649442951 (1 row) ``` * corr\_k(expr1, expr2, return\_mode) Description: Kendall's tau-b correlation coefficient Return type:double precision Return Value: The `return_mode` parameter is optional; if not specified, the function returns Kendall's tau-b correlation coefficient (the return value is the same as when `return_mode=COEFFICIENT`). If specified, the description of the return value is the same as that for the `corr_s` function mentioned above. Example: ``` openGauss=# SELECT CORR_K(a,b) FROM corr_t1; corr_k ------------------ .894427190999916 (1 row) openGauss=# SELECT CORR_K(a,b,'COEFFICIENT') FROM corr_t1; corr_k ------------------ .894427190999916 (1 row) openGauss=# SELECT CORR_K(a,b,'ONE_SIDED_SIG') FROM corr_t1; corr_k ------------------- .0142298684581553 (1 row) ``` * every(expression) Description: Equivalent to **bool\_and** Return type: Boolean Example: ``` openGauss=# SELECT every(100 <2500); every ------- t (1 row) ``` * regr\_avgx(Y, X) Description: Specifies the average of the independent variable (**sum(X)/N**). Return type: double precision Example: ``` openGauss=# SELECT REGR_AVGX(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_avgx ------------------ 578.606576740795 (1 row) ``` * regr\_avgy(Y, X) Description: Specifies the average of the dependent variable (**sum(Y)/N**). Return type: double precision Example: ``` openGauss=# SELECT REGR_AVGY(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_avgy ------------------ 50.0136711629602 (1 row) ``` * regr\_count(Y, X) Description: Specifies the number of input rows in which both expressions are non-null. Return type: bigint Example: ``` openGauss=# SELECT REGR_COUNT(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_count ------------ 2743 (1 row) ``` * regr\_intercept(Y, X) Description: Specifies the y-intercept of the least-squares-fit linear equation determined by the (X, Y) pairs. Return type: double precision Example: ``` openGauss=# SELECT REGR_INTERCEPT(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_intercept ------------------ 49.2040847848607 (1 row) ``` * regr\_r2(Y, X) Description: Specifies the square of the correlation coefficient. Return type: double precision Example: ``` openGauss=# SELECT REGR_R2(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_r2 -------------------- .00145453469345058 (1 row) ``` * regr\_slope(Y, X) Description: Specifies the slope of the least-squares-fit linear equation determined by the (X, Y) pairs. Return type: double precision Example: ``` openGauss=# SELECT REGR_SLOPE(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_slope -------------------- .00139920009665259 (1 row) ``` * regr\_sxx(Y, X) Description: **sum(X^2) - sum(X)^2/N**(sum of squares of the independent variables) Return type: double precision Example: ``` openGauss=# SELECT REGR_SXX(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_sxx ------------------ 1626645991.46135 (1 row) ``` * regr\_sxy(Y, X) Description: **sum(X\*Y) - sum(X) \* sum(Y)/N** ("sum of products" of independent times dependent variable) Return type: double precision Example: ``` openGauss=# SELECT REGR_SXY(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_sxy ------------------ 2276003.22847225 (1 row) ``` * regr\_syy(Y, X) Description: **sum(Y^2) - sum(Y)^2/N** ("sum of squares" of the dependent variable) Return type: double precision Example: ``` openGauss=# SELECT REGR_SYY(sr_fee, sr_net_loss) FROM tpcds.store_returns WHERE sr_customer_sk < 1000; regr_syy ----------------- 2189417.6547314 (1 row) ``` * stddev(expression) Description: Specifies the alias of **stddev\_samp**. Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT STDDEV(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; stddev ------------------ 289.224359757315 (1 row) ``` * variance(expexpression,ression) Description: Specifies the alias of **var\_samp**. Return type: **double precision** for floating-point arguments, otherwise **numeric** Example: ``` openGauss=# SELECT VARIANCE(inv_quantity_on_hand) FROM tpcds.inventory WHERE inv_warehouse_sk = 1; variance -------------------- 83650.730277028768 (1 row) ``` * delta Description: Returns the difference between the current row and the previous row. Parameter: numeric Return type: numeric * checksum(expression) Description: Returns the **CHECKSUM** value of all input values. This function can be used to check whether the data in the tables is the same before and after the backup, restoration, or migration of the openGauss database (databases other than openGauss are not supported). Before and after database backup, database restoration, or data migration, you need to manually run SQL commands to obtain the execution results. Compare the obtained execution results to check whether the data in the tables before and after the backup or migration is the same. > \[!NOTE]NOTE > > * For large tables, the execution of the **CHECKSUM** function may take a long time. > * If the **CHECKSUM** values of two tables are different, it indicates that the contents of the two tables are different. Using the hash function in the **CHECKSUM** function may incur conflicts. There is low possibility that two tables with different contents may have the same **CHECKSUM** value. The same problem may occur when **CHECKSUM** is used for columns. > * If the time type is timestamp, timestamptz, or smalldatetime, ensure that the time zone settings are the same when calculating the **CHECKSUM** value. * If the **CHECKSUM** value of a column is calculated and the column type can be changed to TEXT by default, set *expression* to the column name. * If the **CHECKSUM** value of a column is calculated and the column type cannot be converted to TEXT by default, set *expression* to *Column name*\*\*::TEXT\*\*. * If the **CHECKSUM** value of all columns is calculated, set *expression* to *Table name*\*\*::TEXT\*\*. The following types of data can be converted into TEXT types by default: char, name, int8, int2, int1, int4, raw, pg\_node\_tree, float4, float8, bpchar, varchar, nvarchar, nvarchar2, date, timestamp, timestamptz, numeric, and smalldatetime. Other types need to be forcibly converted to TEXT. Return type: numeric Example: The following shows the **CHECKSUM** value of a column that can be converted to the TEXT type by default: ``` openGauss=# SELECT CHECKSUM(inv_quantity_on_hand) FROM tpcds.inventory; checksum ------------------- 24417258945265247 (1 row) ``` The following shows the **CHECKSUM** value of a column that cannot be converted to the TEXT type by default. Note that the **CHECKSUM** parameter is set to *Column name*\*\*::TEXT\*\*. ``` openGauss=# SELECT CHECKSUM(inv_quantity_on_hand::TEXT) FROM tpcds.inventory; checksum ------------------- 24417258945265247 (1 row) ``` The following shows the **CHECKSUM** value of all columns in a table. Note that the **CHECKSUM** parameter is set to *Table name*\*\*::TEXT\*\*. The table name is not modified by its schema. ``` openGauss=# SELECT CHECKSUM(inventory::TEXT) FROM tpcds.inventory; checksum ------------------- 25223696246875800 (1 row) ``` * first(anyelement) Description: Returns the first non-null input. Return type: anyelement ``` openGauss=# select * from tba; name ----- A A D (4 rows) openGauss=# select first(name) from tba; first ----- A (1 rows) ``` * last(anyelement) Description: Returns the last non-null input. Return type: anyelement ``` openGauss=# select * from tba; name ----- A A D (4 rows) openGauss=# select last(name) from tba; last ----- D (1 rows) ``` * mode() within group (order by value anyelement) Description: Returns the value with the highest occurrence frequency in a column. If multiple values have the same frequency, the smallest value is returned. The sorting mode is the same as the default sorting mode of the column type. **value** is an input parameter and can be of any type. Return type: same as the input parameter type Example: ``` openGauss=# select mode() within group (order by value) from (values(1, 'a'), (2, 'b'), (2, 'c')) v(value, tag); mode ------ 2 (1 row) openGauss=# select mode() within group (order by tag) from (values(1, 'a'), (2, 'b'), (2, 'c')) v(value, tag); mode ------ a (1 row) ``` * json\_agg(any) Description: Aggregates values into a JSON array. Return type: array-json Example: ``` openGauss=# select * from classes; name | score -----+------- A | 2 A | 3 D | 5 D | (4 rows) ``` ``` openGauss=# select name, json_agg(score) score from classes group by name order by name; name | score -----+----------------- A | [2, 3] D | [5, null] | [null] (3 rows) ``` * json\_object\_agg(any, any) Description: Aggregates values into a JSON object. Return type: object-json Example: ``` openGauss=# select * from classes; name | score -----+------- A | 2 A | 3 D | 5 D | (4 rows) ``` ``` openGauss=# select json_object_agg(name, score) from classes group by name order by name; json_object_agg ------------------------- { "A" : 2, "A" : 3 } { "D" : 5, "D" : null } (2 rows) ``` * cume\_dist(expression \[,expression] ) WITHIN GROUP (ORDER BY { order-list \[ ASC | DESC ] \[ NULLS { FIRST | LAST } ] } \[,...]) Description: Calculate the cumulative distribution of the assumed rows and corresponding sorting criteria identified by the parameters of the function in the aggregated group rows. in other words, The proportion of the total number of rows in the sorting partition where the value of expression is the same as the value of the last row after sorting * **expression**: Mandatory. specify the rows to be inserted into a set of rows. This expression must return a value of a built-in data type. The expression must be a constant or variable of a constant or variable. Multiple parameters can be entered. The number of parameters must be consistent with the order list and the number of parameters. * **order-list**: Mandatory. The sorting key can be a column name or a sorting key expression. Return type: float Example: Insert the input 4 into a column sorted by c1, with 4 placed at position 8. Therefore, the function returns a value of 8/14. ``` openGauss=# create table aggregates_hypothetical(c1 int, c2 NUMBER(8,2), c3 varchar(20), c4 timestamp); CREATE TABLE openGauss=# insert into aggregates_hypothetical values openGauss-# (1,0.1,'1','2024-09-01 09:22:00'), openGauss-# (2,0.2,'2','2024-09-02 09:22:00'), openGauss-# (3,0.1,'3','2024-09-03 09:22:00'), openGauss-# (3,0.2,'3','2024-09-04 09:22:00'), openGauss-# (3,0.3,'3','2024-09-05 09:22:00'), openGauss-# (3,0.3,'3','2024-09-05 09:22:00'), openGauss-# (4,0.2,'4','2024-09-06 09:22:00'), openGauss-# (5,0.2,'5','2024-09-07 09:22:00'), openGauss-# (6,0.2,'6','2024-09-08 09:22:00'), openGauss-# (7,0.2,'7','2024-09-09 09:22:00'), openGauss-# (8,0.2,'8','2024-09-10 09:22:00'), openGauss-# (9,0.2,'9','2024-09-11 09:22:00'), openGauss-# (10,0.2,'10','2024-09-12 09:22:00'); INSERT 0 13 openGauss=# select cume_dist(4) within group (order by c1) from aggregates_hypothetical; cume_dist ------------------ .571428571428571 (1 row) ``` Example: Insert the input (3,0.2) into the column sorted by c1 and c2, and place it in the 5th position. Therefore, the function returns a value of 5/14 ``` openGauss=# select cume_dist(3,0.2) within group (order by c1,c2) from aggregates_hypothetical; cume_dist ------------------ .357142857142857 (1 row) ``` Example: Insert the input string into a column sorted by c1, perform type conversion, and then perform calculations ``` select cume_dist('1') within group (order by c1) from test_aggregate; cume_dist ------------------ .142857142857143 (1 row) ``` * rank( expression \[,expression] ) WITHIN GROUP (ORDER BY { order-list \[ ASC | DESC ] \[ NULLS { FIRST | LAST } ] } \[,...]) Description: Calculate the ranking of a hypothetical row identified by the parameters of a function relative to a given sorting criterion. The ranking values of the rank function are not continuous. * **expression**: Mandatory. specify the rows to be inserted into a set of rows. This expression must return a value of a built-in data type. The expression must be a constant or variable of a constant or variable. Multiple parameters can be entered. The number of parameters must be consistent with the order list and the number of parameters. * **order-list**:Mandatory.The sorting key can be a column name or a sorting key expression. Return type: int Example Using c1 as the sorting column, calculate the ranking value of the input parameter in the sorting column. Duplicate columns are also included in the ranking, so the ranking is discontinuous ``` openGauss=# select rank(3) within group (order by c1) from aggregates_hypothetical; rank ------ 3 (1 row) openGauss=# select rank(4) within group (order by c1) from aggregates_hypothetical; rank ------ 7 (1 row) ``` Example Column sorted by c1, c2 ``` openGauss=# select rank(4,0.2) within group (order by c1,c2) from aggregates_hypothetical; rank ------ 7 (1 row) ``` * dense\_rank( expression \[,expression] ) WITHIN GROUP (ORDER BY { order-list \[ ASC | DESC ] \[ NULLS { FIRST | LAST } ] } \[,...]) Description: Calculate the ranking of a hypothetical row identified by the parameters of a function relative to a given sorting criterion. The ranking value of the dense\_rank function is continuous * **expression**: Mandatory. specify the rows to be inserted into a set of rows. This expression must return a value of a built-in data type. The expression must be a constant or variable of a constant or variable. Multiple parameters can be entered. The number of parameters must be consistent with the order list and the number of parameters. * **order-list**:Mandatory.The sorting key can be a column name or a sorting key expression. Return type: int Example Using c1 as the sorting column, calculate the ranking value of the input parameter in the sorting column. Duplicate columns are not included in the ranking, so the ranking is continuous ``` openGauss=# select dense_rank(3) within group (order by c1) from aggregates_hypothetical; dense_rank ------------ 3 (1 row) openGauss=# select dense_rank(4) within group (order by c1) from aggregates_hypothetical; dense_rank ------------ 4 (1 row) ``` Example Column sorted by c1, c2 ``` openGauss=# select dense_rank(4,0.2) within group (order by c1,c2) from aggregates_hypothetical;; dense_rank ------------ 6 (1 row) ``` * percent\_rank( expression \[,expression] ) WITHIN GROUP (ORDER BY { order-list \[ ASC | DESC ] \[ NULLS { FIRST | LAST } ] } \[,...]) Description: Calculate the percentage of the relative position of the assumed rows identified by the parameters of the function with respect to a given sorting criterion. The calculation formula is (rank -1)/(totals -1). * **expression**: Mandatory. specify the rows to be inserted into a set of rows. This expression must return a value of a built-in data type. The expression must be a constant or variable of a constant or variable. Multiple parameters can be entered. The number of parameters must be consistent with the order list and the number of parameters. * **order-list**:Mandatory.The sorting key can be a column name or a sorting key expression. Return type: float Example The percentage of the input value in the position of the current ranking column sorted by c1 ``` openGauss=# select percent_rank(4) within group (order by c1) from aggregates_hypothetical; percent_rank ------------------- 0.461538461538462 (1 row) ``` Example Column sorted by c1, c2 ``` openGauss=# select percent_rank(3,0.2) within group (order by c1,c2) from aggregates_hypothetical; percent_rank ------------------- 0.230769230769231 (1 row) ``` --- --- url: /en/docs/latest/sql_reference/brief_tutorial/aggregate-functions.md --- # Aggregate Functions * sum(expression) Description: Specifies the sum of expressions across all input values. Return type: Generally, it is the same as the argument data type. In the following cases, type conversion occurs: * **BIGINT** for **SMALLINT** or **INT** arguments * **NUMBER** for **BIGINT** arguments * **DOUBLE PRECISION** for floating-point arguments Example: ``` openGauss=# SELECT SUM(amount) FROM customer_t1; sum ------- 14200 (1 row) ``` * max(expression) Description: Specifies the maximum value of expressions across all input values. Parameter type: any array, numeric, string, date/time type, or IPv4 and IPv6 addresses (INET and CIDR data types) Return type: same as the argument data type Example: ``` openGauss=# SELECT MAX (c_customer_sk) FROM customer_t1; max ------ 9976 (1 row) ``` * min(expression) Description: Specifies the minimum value of expressions across all input values. Parameter type: any array, numeric, string, date/time type, or IPv4 and IPv6 addresses (INET and CIDR data types) Return type: same as the argument data type Example: ``` openGauss=# SELECT MIN (c_customer_sk) FROM customer_t1; min ------ 3869 (1 row) ``` * avg(expression) Description: Specifies the average (arithmetic mean) of all input values. Return type: **NUMBER** for any integer-type argument. **DOUBLE PRECISION** for floating-point arguments. Otherwise, it is the same as the argument data type. Example: ``` openGauss=# SELECT AVG(AMOUNT) FROM customer_t1; avg ----------------------- 2366.6666666666666667 (1 row) ``` * count(expression) Description: Specifies the number of input rows for which the value of the expression is **NULL**. Return type: BIGINT Example: ``` openGauss=# SELECT COUNT(c_customer_id) FROM customer_t1; count ------- 7 (1 row) ``` * count(\*) Description: Returns the number of input rows. Return type: BIGINT Example: ``` openGauss=# SELECT COUNT(*) FROM customer_t1; count ------- 8 (1 row) ``` * delta Description: Returns the difference between the current row and the previous row. Parameter: numeric Return type: numeric * mode() within group (order by value anyelement) Description: Returns the value with the highest occurrence frequency in a column. If multiple values have the same frequency, the smallest value is returned. The sorting mode is the same as the default sorting mode of the column type. **value** is an input parameter and can be of any type. Return type: same as the argument data type Example: ``` openGauss=# select mode() within group (order by value) from (values(1, 'a'), (2, 'b'), (2, 'c')) v(value, tag); mode ------ 2 (1 row) openGauss=# select mode() within group (order by tag) from (values(1, 'a'), (2, 'b'), (2, 'c')) v(value, tag); mode ------ a (1 row) ``` --- --- url: /en/docs/latest-lite/characteristic_description/ai_capabilities.md --- # AI Capabilities The history of artificial intelligence (AI) can be dated back to as early as the 1950s, even longer than the history of the database development. However, the AI technology has not been applied on a large scale for a long time due to various objective factors, and even experienced several obvious troughs. With the further development of information technologies in recent years, factors that restrict the AI development have been gradually weakened, and the AI, big data, and cloud computing (ABC) technologies are born. The combination of AI and databases has been a trending research topic in the industry in recent years. openGauss has participated in the exploration of this domain earlier and achieved phased achievements. An AI submodule DBMind is provided for the database. Compared with other functions, it is more independent. This module can be divided into AI4DB, DB4AI, and AI in DB. * AI4DB uses AI technologies to optimize database execution performance as well as achieve autonomy and O\&M free. It includes self-tuning, self-diagnosis, self-security, self-O\&M, and self-healing. * DB4AI streamlines the E2E process from databases to AI applications, drives AI tasks through databases, and unifies the AI technology stack to achieve out-of-the-box, high performance, and cost saving. For example, SQL-like statements are used to implement functions such as recommendation system, image retrieval, and time series forecast. The advantages of high parallelism and column store of databases can be fully utilized to avoid the cost of data and fragmented storage and avoid security risks caused by information leakage. * AI in DB modifies the database kernel to implement functions that cannot be implemented in the original database architecture. For example, AI algorithms are used to improve the database optimizer to implement more accurate cost estimation. The functions described in this section are stored in the **bin/dbmind** directory of the database installation directory (*$GAUSSHOME*). The sub-functions are stored in the **components** subdirectory of **bin/dbmind**. To invoke DBMind, you can run the **gs\_dbmind** command. In addition, the built-in AI functions (such as DB4AI) of the database are presented in the form of SQL syntaxes and system functions. * **[AI4DB: Autonomous Database O\&M](database_metric_collection_forecast_and_exception_detection.md)** * **[DB4AI: Database-driven AI](db4ai_database_driven_ai.md)** * **[AI in DB](predictor_ai_query_time_forecasting.md)** --- --- url: /en/docs/latest/characteristic_description/ai_capabilities.md --- # AI Capabilities * **[Predictor: AI Query Time Forecasting](predictor_ai_query_time_forecasting.md)** * **[X-Tuner: Parameter Optimization and Diagnosis](x_tuner_parameter_optimization_and_diagnosis.md)** * **[SQLdiag: Slow SQL Discovery](sqldiag_slow_sql_discovery.md)** * **[Anomaly-detection: Database Indicator Collection, Forecasting, and Exception Monitoring](anomaly_detection_database_indicator_collection_forecasting_and_exception_monitoring.md)** * **[Index-advisor: Index Recommendation](index_advisor_index_recommendation.md)** * **[DeepSQL: AI Algorithm in the Library](deepsql_ai_algorithm_in_the_library.md)** --- --- url: /en/docs/latest-lite/sql_reference/ai_feature_functions.md --- # AI Feature Functions > \[!NOTE]NOTE > In the Lite scenario, openGauss provides the following APIs, but the AI capabilities are unavailable. * gs\_index\_advise(text) Description: Recommends an index for a single query statement. Parameter: SQL statement string Return type: record * hypopg\_create\_index(text) Description: Creates a virtual index. Parameter: character string of the statement for creating an index Return type: record * hypopg\_display\_index() Description: Displays information about all created virtual indexes. Parameter: none Return type: record * hypopg\_drop\_index(oid) Description: Deletes a specified virtual index. Parameter: OID of the index Return type: Boolean * hypopg\_reset\_index() Description: Clears all virtual indexes. Parameter: none Return type: none * hypopg\_estimate\_size(oid) Description: Estimates the space required for creating a specified index. Parameter: OID of the index Return type: int8 * check\_engine\_status(ip text, port text) Description: Tests whether a predictor engine provides services on a specified IP address and port. Parameter: IP address and port number of the predictor engine. Return type: text * encode\_plan\_node(optname text, orientation text, strategy text, options text, dop int8, quals text, projection text) Description: Encodes the plan operator information in the input parameters. Parameter: plan operator information Return type: text > \[!NOTE]NOTE > This function is an internal function. * model\_train\_opt(template text, model text) Description: Trains a given query performance prediction model. Parameters: template name and model name of the performance prediction model Return type: tartup\_time\_accuracy FLOAT8, total\_time\_accuracy FLOAT8, rows\_accuracy FLOAT8, peak\_memory\_accuracy FLOAT8 * track\_model\_train\_opt(ip text, port text) Description: Returns the training log address of the specified IP address and port predictor engine. Parameter: IP address and port number of the predictor engine Return type: text * encode\_feature\_perf\_hist(datname text) Description: Encodes historical plan operators collected in the target database. Parameter: database name Return type: queryid bigint, plan\_node\_id int, parent\_node\_id int, left\_child\_id int, right\_child\_id int, encode text, startup\_time bigint, total\_time bigint, rows bigint, and peak\_memory int * gather\_encoding\_info(datname text) Description: Invokes **encode\_feature\_perf\_hist** to save the encoded data persistently. Parameter: database name Return type: int * db4ai\_predict\_by\_bool (text, VARIADIC "any") Description: Obtains a model whose return value is of the Boolean type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: Boolean * db4ai\_predict\_by\_float4(text, VARIADIC "any") Description: Obtains a model whose return value is of the float4 type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: float * db4ai\_predict\_by\_float8(text, VARIADIC "any") Description: Obtains a model whose return value is of the float8 type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: float * db4ai\_predict\_by\_int32(text, VARIADIC "any") Description: Obtains a model whose return value is of the int32 type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: int * db4ai\_predict\_by\_int64(text, VARIADIC "any") Description: Obtains a model whose return value is of the int64 type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: int * db4ai\_predict\_by\_numeric(text, VARIADIC "any") Description: Obtains a model whose return value is of the numeric type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: numeric * db4ai\_predict\_by\_text(text, VARIADIC "any") Description: Obtains a model whose return value is of the character type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: text * db4ai\_predict\_by\_float8\_array(text, VARIADIC "any") Description: Obtains a model whose return value is of the character type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: text * gs\_explain\_model(text) Description: Obtains the model whose return value is of the character type for text-based model parsing. Parameter: model name. Return type: text --- --- url: /en/docs/latest/sql_reference/ai_feature_functions.md --- # AI Feature Functions * gs\_index\_advise(text) Description: Recommends an index for a single query statement. Parameter: SQL statement string Return type: record [Single-query Index Recommendation](../characteristic_description/aifeature_guide/ai4db_autonomous_database_o_m.md) describes the examples. * hypopg\_create\_index(text) Description: Creates a virtual index. Parameter: character string of the statement for creating an index Return type: record [Virtual Index](../characteristic_description/aifeature_guide/ai4db_autonomous_database_o_m.md) describes the examples. * hypopg\_display\_index() Description: Displays information about all created virtual indexes. Parameter: none Return type: record [Virtual Index](../characteristic_description/aifeature_guide/ai4db_autonomous_database_o_m.md) describes the examples. * hypopg\_drop\_index(oid) Description: Deletes a specified virtual index. Parameter: OID of the index Return type: Boolean [Virtual Index](../characteristic_description/aifeature_guide/ai4db_autonomous_database_o_m.md) describes the examples. * hypopg\_reset\_index() Description: Clears all virtual indexes. Parameter: none Return type: none [Virtual Index](../characteristic_description/aifeature_guide/ai4db_autonomous_database_o_m.md) describes the examples. * hypopg\_estimate\_size(oid) Description: Estimates the space required for creating a specified index. Parameter: OID of the index Return type: int8 [Virtual Index](../characteristic_description/aifeature_guide/ai4db_autonomous_database_o_m.md) describes the examples. * check\_engine\_status(ip text, port text) Description: Tests whether a predictor engine provides services on a specified IP address and port. Parameter: IP address and port number of the predictor engine. Return type: text * encode\_plan\_node(optname text, orientation text, strategy text, options text, dop int8, quals text, projection text) Description: Encodes the plan operator information in the input parameters. Parameter: plan operator information Return type: text > \[!NOTE]NOTE > This function is an internal function. You are not advised to use it directly. * model\_train\_opt(template text, model text) Description: Trains a given query performance prediction model. Parameters: template name and model name of the performance prediction model Return type: tartup\_time\_accuracy FLOAT8, total\_time\_accuracy FLOAT8, rows\_accuracy FLOAT8, peak\_memory\_accuracy FLOAT8 * track\_model\_train\_opt(ip text, port text) Description: Returns the training log address of the specified IP address and port predictor engine. Parameter: IP address and port number of the predictor engine Return type: text * encode\_feature\_perf\_hist(datname text) Description: Encodes historical plan operators collected in the target database. Parameter: database name Return type: queryid bigint, plan\_node\_id int, parent\_node\_id int, left\_child\_id int, right\_child\_id int, encode text, startup\_time bigint, total\_time bigint, rows bigint, and peak\_memory int * gather\_encoding\_info(datname text) Description: Invokes **encode\_feature\_perf\_hist** to save the encoded data persistently. Parameter: database name Return type: int * db4ai\_predict\_by\_bool (text, VARIADIC "any") Description: Obtains a model whose return value is of the Boolean type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: Boolean * db4ai\_predict\_by\_float4(text, VARIADIC "any") Description: Obtains a model whose return value is of the float4 type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: float * db4ai\_predict\_by\_float8(text, VARIADIC "any") Description: Obtains a model whose return value is of the float8 type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: float * db4ai\_predict\_by\_int32(text, VARIADIC "any") Description: Obtains a model whose return value is of the int32 type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: int * db4ai\_predict\_by\_int64(text, VARIADIC "any") Description: Obtains a model whose return value is of the int64 type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: int * db4ai\_predict\_by\_numeric(text, VARIADIC "any") Description: Obtains a model whose return value is of the numeric type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: numeric * db4ai\_predict\_by\_text(text, VARIADIC "any") Description: Obtains a model whose return value is of the character type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: text * db4ai\_predict\_by\_float8\_array(text, VARIADIC "any") Description: Obtains a model whose return value is of the character type for model inference. This function is an internal function. You are advised to use the **PREDICT BY** syntax for inference. Parameter: model name and input column name of the inference task Return type: text * gs\_explain\_model(text) Description: Obtains the model whose return value is of the character type for text-based model parsing. Parameter: model name Return type: text --- --- url: /en/docs/latest-lite/database_reference/ai_features.md --- # AI Features > \[!NOTE]NOTE > In the Lite scenario, the AI capabilities of openGauss are unavailable. ## enable\_hypo\_index **Parameter description**: Specifies whether the database optimizer considers the created virtual index when executing the **EXPLAIN** statement. By executing **EXPLAIN** on a specific query statement, you can evaluate whether the index can improve the execution efficiency of the query statement based on the execution plan provided by the optimizer. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that a virtual index is created during **EXPLAIN** execution. * **off** indicates that no virtual index is created during **EXPLAIN** execution. **Default value**: **off** ## db4ai\_snapshot\_mode **Parameter description**: There are two snapshot modes: MSS (materialized mode, storing data entities) and CSS (computing mode, storing incremental information). This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string, which can be **MSS** or **CSS** * **MSS** indicates the materialized mode. The DB4AI stores data entities when snapshots are created. * **CSS** indicates the computing mode. The DB4AI stores incremental information when creating snapshots. **Default value:** **MSS** ## db4ai\_snapshot\_version\_delimiter **Parameter description**: Specifies the delimiter for the snapshot version of a data table. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string, consisting of one or more characters. **Default value**: **@** ## db4ai\_snapshot\_version\_separator **Parameter description**: Specifies the subversion delimiter of a data table snapshot. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string, consisting of one or more characters. **Default value**: . ## unix\_socket\_directory **Parameter description:** Specifies the path for storing files in the unix\_socket communication mode. You can set this parameter only in the configuration file **postgresql.conf**. Before enabling the fenced mode, you need to set this GUC parameter. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string of 0 or more characters **Default value:** **''** --- --- url: /en/docs/latest/characteristic_description/aifeature_guide/ai_feature_guide.md --- # AI Features The history of artificial intelligence (AI) can be traced back to the 1950s, even predating the development of database systems. However, due to various objective constraints, AI technology was not applied on a large scale for quite some time and even experienced several significant downturns. In recent years, with the advancement of information technology, many of the factors that previously hindered AI development have gradually diminished, giving rise to the so-called ABC technologies—AI, Big Data, and Cloud Computing. The integration of AI and databases has become a major research focus in recent years. openGauss was an early participant in this exploration and has achieved notable progress. The AI features are encapsulated in a submodule called DBMind, which is more independent compared to other database functions. It is broadly divided into two parts: AI4DB and DB4AI. * AI4DB refers to the use of AI technologies to optimize database performance, thereby achieving better execution. It also enables autonomy and O\&M-free capabilities through AI. The key areas include self-tuning, self-diagnosis, self-security, self-O\&M, and self-healing. * DB4AI refers to streamlining the end-to-end process from databases to AI applications, driving AI tasks through the database, and unifying the AI technology stack to achieve out-of-the-box functionality, high performance, and cost savings. For example, SQL-like statements can be used to implement functions such as recommendation systems, image retrieval, and time series prediction. This takes full advantage of the high parallelism and columnar storage of databases, avoiding the costs associated with fragmented data storage and minimizing security risks related to information leakage. The features discussed in this section are located in the **bin/dbmind** directory of the database installation path (*$GAUSSHOME*). Each sub-function resides in the **components** subdirectory within **bin/dbmind**. The **gs\_dbmind** command is available for users to invoke these features. Meanwhile, built-in AI functions (such as DB4AI) are presented through SQL syntax and system functions. * **[AI4DB: Autonomous Database O\&M](ai4db_autonomous_database_o_m.md)** * **[DB4AI: Database\_driven AI](db4ai_database_driven_ai.md)** --- --- url: /en/docs/latest/database_reference/ai_features.md --- # AI Features ## enable\_hypo\_index **Parameter description**: Specifies whether the database optimizer considers the created virtual index when executing the **EXPLAIN** statement. By executing **EXPLAIN** on a specific query statement, you can evaluate whether the index can improve the execution efficiency of the query statement based on the execution plan provided by the optimizer. This parameter is a **USERSET** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that a virtual index is created during **EXPLAIN** execution. * **off** indicates that no virtual index is created during **EXPLAIN** execution. **Default value**: **off** ## db4ai\_snapshot\_mode **Parameter description**: There are two snapshot modes: MSS (materialized mode, storing data entities) and CSS (computing mode, storing incremental information). This parameter is a **USERSET** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string, which can be **MSS** or **CSS** * **MSS** indicates the materialized mode. The DB4AI stores data entities when snapshots are created. * **CSS** indicates the computing mode. The DB4AI stores incremental information when creating snapshots. **Default value:** **MSS** ## db4ai\_snapshot\_version\_delimiter **Parameter description**: Specifies the delimiter for the snapshot version of a data table. This parameter is a **USERSET** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string, consisting of one or more characters. **Default value**: **@** ## db4ai\_snapshot\_version\_separator **Parameter description**: Specifies the subversion delimiter of a data table snapshot. This parameter is a **USERSET** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string, consisting of one or more characters. **Default value**: . ## unix\_socket\_directory **Parameter description:** Specifies the path for storing files in the unix\_socket communication mode. You can set this parameter only in the configuration file **postgresql.conf**. Before enabling the fenced mode, you need to set this GUC parameter. This parameter is a **POSTMASTER** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string of 0 or more characters **Default value:** **''** --- --- url: /en/docs/latest/characteristic_description/ai_in_db.md --- # AI in DB * **[Predictor: AI Query Time Forecasting](predictor_ai_query_time_forecasting.md)** --- --- url: >- /en/docs/latest/characteristic_description/aifeature_guide/ai_sub_functions_of_the_dbmind.md --- # AI Sub\_functions of the DBMind You can run the **component** subcommand of **gs\_dbmind** to enable the corresponding AI sub\_functions. The following sections describe the AI functions in detail. * **[X\_Tuner: Parameter Tuning and Diagnosis](x_tuner_parameter_tuning_and_diagnosis.md)** * **[Index\_advisor: Index Recommendation](index_advisor_index_recommendation.md)** * **[Slow\_query\_diagnosis: Root Cause Analysis for Slow SQL Statements](slow_query_diagnosis_root_cause_analysis_for_slow_sql_statements.md)** * **[Forecast: Trend Prediction](forecast.md)** * **[SQLdiag: Slow SQL Discovery](sqldiag_slow_sql_discovery.md)** * **[SQL Rewriter: SQL Statement Rewriting](sql_rewriter_sql_statement_rewriting.md)** * **[Anomaly Detection](anomaly_detection.md)** * **[Anomaly\_analysis: Multi\_Metric Correlation Analysis](anomaly_analysis_multi_metric_correlation_analysis.md)** --- --- url: >- /en/docs/latest/characteristic_description/aifeature_guide/ai4db_autonomous_database_o_m.md --- # AI4DB: Autonomous Database O\&M As mentioned above, AI4DB is primarily used for autonomous O\&M and management of databases, helping database administrators reduce their workload. In practice, the AI4DB framework in DBMind is monitoring- and service-oriented. It also provides an instant AI toolkit, offering out-of-the-box AI O\&M features (such as index recommendation). AI4DB mainly uses the open-source Prometheus for monitoring, with DBMind providing an exporter to produce monitoring data, which integrates with the Prometheus platform. The following figure illustrates the AI4DB service architecture in DBMind. **Figure 1** AI4DB service architecture of DBMind\ ![](figures/ai4db-service-architecture-of-dbmind.png "ai4db-service-architecture-of-dbmind") Description of key components in the figure: * DBMind Service: The background service of DBMind, used for periodic offline computations, including slow SQL root cause analysis and time series forecasting. * Prometheus-server: The server responsible for storing Prometheus monitoring metrics. * metadatabase: After offline computations are complete, DBMind stores the results here. Supported databases include openGauss, SQLite, and others. * client: The client used to retrieve offline computation results from DBMind, currently only available as a command-line interface (CLI) client. If databases like openGauss are used to store DBMind's computation results, users can configure visualization tools like Grafana for result visualization. * openGauss-exporter: Collects monitoring metrics from openGauss database nodes for use by DBMind's calculations. * node-exporter: An exporter provided by Prometheus to monitor system metrics of a node, such as CPU and memory usage. * reprocessing-exporter: Processes the metrics collected by Prometheus, for example, calculating CPU utilization. ## Environment Setup DBMind's external AI functions require Python version 3.6 or later. The required third-party dependencies are recorded in the **requirements.txt** file (including **requirements-x86.txt** and **requirements-arrch64.txt**, depending on your platform type) located in the root directory of the AI function (*$GAUSSHOME***/bin/dbmind**). You can install the dependencies using the **pip install** command, for example: ``` pip install requirements-x86.txt ``` If you haven't installed all the necessary dependencies, the system will prompt you to install them when you execute the **gs\_dbmind** command. Note that the file lists the third-party dependencies required by DBMind, and if there are conflicts with third-party packages in your environment, you should handle them based on your specific situation. * **[DBMind Mode Explanation](dbmind_mode.md)** * **[Supporting Components of DBMind](prometheus_exporter_overview.md)** * **[DBMind AI Sub\_functions](ai_sub_functions_of_the_dbmind.md)** --- --- url: >- /zh/docs/latest/characteristic_description/aifeature_guide/ai4db_autonomous_database_o_m.md --- # AI4DB: 数据库自治运维 如上文所述,AI4DB主要用于对数据库进行自治运维和管理,从而帮助数据库运维人员减少运维工作量。在实现上,DBMind的AI4DB框架具有监控和服务化的性质,同时也提供即时AI工具包,提供开箱即用的AI运维功能(如索引推荐)。AI4DB的监控平台以开源的Prometheus为主,DBMind提供监控数据生产者exporter, 可与Prometheus平台完成对接。DBMind的AI4DB服务架构如下图所示: **图 1** DBMind AI4DB服务架构\ ![](figures/DBMind-AI4DB-Service-Architecture.png) 图中各关键组件说明: * DBMind Service: DBMind后台服务,可用于定期离线计算,包括慢SQL根因分析、时序预测等; * Prometheus-server: Prometheus 监控指标存储的服务器; * metadatabase: DBMind在离线计算结束后,将计算结果存储在此处,支持openGauss、SQLite等数据库; * client: 用户读取DBMind离线计算结果的客户端,目前仅实现命令行客户端;若采用openGauss等数据库存储计算DBMind计算结果,则用户可以自行配置Grafana等可视化工具对该结果进行可视化; * openGauss-exporter: 用户从openGauss数据库节点上采集监控指标,供DBMind服务进行计算; * node-exporter: Prometheus官方提供的exporter, 可用于监控该节点的系统指标,如CPU和内存使用情况; * reprocessing-exporter: 用于对Prometheus采集到的指标进行二次加工处理,例如计算CPU使用率等。 * **[DBMind模式说明](dbmind_mode.md)** * **[DBMind的支持组件](prometheus_exporter_overview.md)** * **[DBMind的AI子功能](ai_sub_functions_of_the_dbmind.md)** --- --- url: /zh/docs/latest-lite/database_reference/ai_feature.md --- # AI特性 > \[!NOTE]说明 > 轻量版场景下,openGauss中AI能力不可用。 ## enable\_hypo\_index **参数说明**: 该参数控制数据库的优化器进行EXPLAIN时是否考虑创建的虚拟索引。通过对特定的查询语句执行explain,用户可根据优化器给出的执行计划评估该索引是否能够提升该查询语句的执行效率。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 布尔型 * on表示在进行EXPLAIN时创建虚拟索引。 * off表示在进行EXPLAIN时不创建虚拟索引。 **默认值**: off ## db4ai\_snapshot\_mode **参数说明**: snapshot有2种模式:MSS(物化模式,存储数据实体)和CSS(计算模式,存储增量信息)。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 字符串,MSS/CSS * MSS表示物化模式,db4ai在创建快照的时候存储数据实体。 * CSS表示计算模式,db4ai在创建快照的时候存储增量信息。 **默认值**: MSS ## db4ai\_snapshot\_version\_delimiter **参数说明**: 该参数为数据表快照版本分隔符。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 字符串,长度等于1 **默认值**: @ ## db4ai\_snapshot\_version\_separator **参数说明**: 该参数用于指定数据表快照子版本分隔符。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 字符串,长度等于1 **默认值**: . ## enable\_ai\_stats **参数说明**: 该参数用于指定是否创建或者使用智能统计信息。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 布尔型 **默认值**: on ## enable\_cachedplan\_mgr **参数说明**: 该参数用于指定是否开启自适应计划选择功能。 该参数属于POSTMASTER类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 布尔型 **默认值**: off ## multi\_stats\_type **参数说明**: 该参数用于指定在参数enable\_ai\_stats为on状态下创建的统计信息类别。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 枚举类型,有效值为"BAYESNET"、"MCV"、"ALL"。 "BAYESNET":只创建智能统计信息。 "MCV":只创建传统统计信息。 "ALL":同时创建传统统计信息和智能统计信息。 **默认值**: "BAYESNET" ## unix\_socket\_directory **参数说明**: 用于指定unix\_socket通信方式中,文件存放的路径。此参数只能在配置文件postgresql.conf中指定。再启动fenced模式前需要设定该GUC参数。 该参数属于POSTMASTER类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 字符串,长度大于等于0 **默认值**: '' --- --- url: /zh/docs/latest/database_reference/ai_features.md --- # AI特性 ## enable\_hypo\_index **参数说明**: 该参数控制数据库的优化器进行EXPLAIN时是否考虑创建虚拟索引。通过对特定的查询语句执行explain,用户可根据优化器给出的执行计划评估该索引是否能够提升该查询语句的执行效率。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 布尔型 * on表示在进行EXPLAIN时创建虚拟索引。 * off表示在进行EXPLAIN时不创建虚拟索引。 **默认值**: off ## db4ai\_snapshot\_mode **参数说明**: snapshot有2种模式:MSS(物化模式,存储数据实体)和CSS(计算模式,存储增量信息)。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 字符串,MSS/CSS * MSS表示物化模式,db4ai在创建快照的时候存储数据实体。 * CSS表示计算模式,db4ai在创建快照的时候存储增量信息。 **默认值**: MSS ## db4ai\_snapshot\_version\_delimiter **参数说明**: 该参数为数据表快照版本分隔符。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 字符串,长度等于1 **默认值**: @ ## db4ai\_snapshot\_version\_separator **参数说明**: 该参数用于指定数据表快照子版本分隔符。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 字符串,长度等于1 **默认值**: . ## enable\_ai\_stats **参数说明**: 该参数用于指定是否创建或者使用智能统计信息。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 布尔型 **默认值**: on ## enable\_cachedplan\_mgr **参数说明**: 该参数用于指定是否开启自适应计划选择功能。 该参数属于POSTMASTER类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 布尔型 **默认值**: on ## multi\_stats\_type **参数说明**: 该参数用于指定在参数enable\_ai\_stats为on状态下创建的统计信息类别。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 枚举类型,有效值为"BAYESNET"、"MCV"、"ALL"。 "BAYESNET":只创建智能统计信息。 "MCV":只创建传统统计信息。 "ALL":同时创建传统统计信息和智能统计信息。 **默认值**: "BAYESNET" ## unix\_socket\_directory **参数说明**: 用于指定unix\_socket通信方式中,文件存放的路径。此参数只能在配置文件postgresql.conf中指定。再启动fenced模式前需要设定该GUC参数。 该参数属于POSTMASTER类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 字符串,长度大于等于0 **默认值**: '' --- --- url: /zh/docs/latest-lite/sql_reference/ai_feature_functions.md --- # AI特性函数 > \[!NOTE]说明 > 轻量版场景下,openGauss提供下述接口,但AI能力不可用。 * gs\_index\_advise(text) 描述:针对单条查询语句推荐索引。 参数:SQL语句字符串 返回值类型:record * hypopg\_create\_index(text) 描述:创建虚拟索引。 参数:创建索引语句的字符串 返回值类型:record * hypopg\_display\_index() 描述:显示所有创建的虚拟索引信息。 参数:无 返回值类型:record * hypopg\_drop\_index(oid) 描述:删除指定的虚拟索引。 参数:索引的oid 返回值类型:bool * hypopg\_reset\_index() 描述:清除所有虚拟索引。 参数:无 返回值类型:无 * hypopg\_estimate\_size(oid) 描述:估计指定索引创建所需的空间大小。 参数:索引的oid 返回值类型:int8 * check\_engine\_status(ip text, port text) 描述:测试给定的ip和port上是否有predictor engine提供服务。 参数:predictor engine的ip地址和端口号。 返回值类型:text * encode\_plan\_node(optname text, orientation text, strategy text, options text, dop int8, quals text, projection text) 描述:对入参的计划算子信息进行编码。 参数:计划算子信息。 返回值类型:text。 > \[!NOTE]说明 > 该函数为内部功能调用函数。 * model\_train\_opt(template text, model text) 描述:训练给定的查询性能预测模型。 参数:性能预测模型的模板名和模型名。 返回值类型:tartup\_time\_accuracy FLOAT8, total\_time\_accuracy FLOAT8, rows\_accuracy FLOAT8, peak\_memory\_accuracy FLOAT8 * track\_model\_train\_opt(ip text, port text) 描述:返回给定ip和port predictor engine的训练日志地址。 参数:predictor engine的ip地址和端口号。 返回值类型:text * encode\_feature\_perf\_hist(datname text) 描述:将目标数据库已收集的历史计划算子进行编码。 参数:数据库名。 返回值类型:queryid bigint, plan\_node\_id int, parent\_node\_id int, left\_child\_id int, right\_child\_id int, encode text, startup\_time bigint, total\_time bigint, rows bigint, peak\_memory int * gather\_encoding\_info(datname text) 描述:调用encode\_feature\_perf\_hist,将编码好的数据进行持久化保存。 参数:数据库名。 返回值类型:int * db4ai\_predict\_by\_bool (text, VARIADIC "any") 描述:获取返回值为布尔型的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法PREDICT BY进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:bool * db4ai\_predict\_by\_float4(text, VARIADIC "any") 描述:获取返回值为float4的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法PREDICT BY进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:float * db4ai\_predict\_by\_float8(text, VARIADIC "any") 描述:获取返回值为float8的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法PREDICT BY进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:float * db4ai\_predict\_by\_int32(text, VARIADIC "any") 描述:获取返回值为int32的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法PREDICT BY进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:int * db4ai\_predict\_by\_int64(text, VARIADIC "any") 描述:获取返回值为int64的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法PREDICT BY进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:int * db4ai\_predict\_by\_numeric(text, VARIADIC "any") 描述:获取返回值为numeric的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法PREDICT BY进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:numeric * db4ai\_predict\_by\_text(text, VARIADIC "any") 描述:获取返回值为字符型的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法PREDICT BY进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:text * db4ai\_predict\_by\_float8\_array(text, VARIADIC "any") 描述:获取返回值为字符型的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法PREDICT BY进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:text * gs\_explain\_model(text) 描述:获取返回值为字符型的模型进行模型解析文本化任务。 参数:模型名称。 返回值类型:text --- --- url: /zh/docs/latest/sql_reference/ai_feature_functions.md --- # AI特性函数 * gs\_index\_advise(text) 描述:针对单条查询语句推荐索引。 参数:SQL语句字符串 返回值类型:record 示例请参见[单query索引推荐](../characteristic_description/advanced_features/index_recommendation.md)。 * hypopg\_create\_index(text) 描述:创建虚拟索引。 参数:创建索引语句的字符串 返回值类型:record 示例请参见[虚拟索引](../characteristic_description/advanced_features/index_recommendation.md)。 * hypopg\_display\_index() 描述:显示所有创建的虚拟索引信息。 参数:无 返回值类型:record 示例请参见[虚拟索引](../characteristic_description/advanced_features/index_recommendation.md)。 * hypopg\_drop\_index(oid) 描述:删除指定的虚拟索引。 参数:索引的oid 返回值类型:bool 示例请参见[虚拟索引](../characteristic_description/advanced_features/index_recommendation.md)。 * hypopg\_reset\_index() 描述:清除所有虚拟索引。 参数:无 返回值类型:无 示例请参见[虚拟索引](../characteristic_description/advanced_features/index_recommendation.md)。 * hypopg\_estimate\_size(oid) 描述:估计指定索引创建所需的空间大小。 参数:索引的oid 返回值类型:int8 示例请参见[虚拟索引](../characteristic_description/advanced_features/index_recommendation.md)。 * check\_engine\_status(ip text, port text) 描述:测试给定的ip和port上是否有predictor engine提供服务。 参数:predictor engine的ip地址和端口号。 返回值类型:text > \[!NOTE]说明 > > 该函数当前版本不可用。 * encode\_plan\_node(optname text, orientation text, strategy text, options text, dop int8, quals text, projection text) 描述:对入参的计划算子信息进行编码。 参数:计划算子信息。 返回值类型:text。 > \[!NOTE]说明 > > 该函数为内部功能调用函数,不建议用户直接使用。 * model\_train\_opt(template text, model text) 描述:训练给定的查询性能预测模型。 参数:性能预测模型的模板名和模型名。 返回值类型:tartup\_time\_accuracy FLOAT8、 total\_time\_accuracy FLOAT8、 rows\_accuracy FLOAT8、 peak\_memory\_accuracy FLOAT8 > \[!NOTE]说明 > > 该函数当前版本不可用。 * track\_model\_train\_opt(ip text, port text) 描述:返回给定ip和port predictor engine的训练日志地址。 参数:predictor engine的ip地址和端口号。 返回值类型:text > \[!NOTE]说明 > > 该函数当前版本不可用。 * encode\_feature\_perf\_hist(datname text) 描述:将目标数据库已收集的历史计划算子进行编码。 参数:数据库名。 返回值类型:queryid bigint、 plan\_node\_id int、 parent\_node\_id int、 left\_child\_id int、 right\_child\_id int, encode text、 startup\_time bigint、 total\_time bigint、 rows bigint、 peak\_memory int > \[!NOTE]说明 > > 该函数当前版本不可用。 * gather\_encoding\_info(datname text) 描述:调用encode\_feature\_perf\_hist,将编码好的数据进行持久化保存。 参数:数据库名。 返回值类型:int \>\[!NOTE]说明 > 该函数当前版本不可用。 * db4ai\_predict\_by\_bool (text, VARIADIC "any") 描述:获取返回值为布尔型的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法[PREDICT BY](predict_by.md)进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:bool * db4ai\_predict\_by\_float4(text, VARIADIC "any") 描述:获取返回值为float4的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法[PREDICT BY](predict_by.md)进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:float * db4ai\_predict\_by\_float8(text, VARIADIC "any") 描述:获取返回值为float8的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法[PREDICT BY](predict_by.md)进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:float * db4ai\_predict\_by\_int32(text, VARIADIC "any") 描述:获取返回值为int32的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法[PREDICT BY](predict_by.md)进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:int * db4ai\_predict\_by\_int64(text, VARIADIC "any") 描述:获取返回值为int64的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法[PREDICT BY](predict_by.md)进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:int * db4ai\_predict\_by\_numeric(text, VARIADIC "any") 描述:获取返回值为numeric的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法[PREDICT BY](predict_by.md)进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:numeric * db4ai\_predict\_by\_text(text, VARIADIC "any") 描述:获取返回值为字符型的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法[PREDICT BY](predict_by.md)进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:text * db4ai\_predict\_by\_float8\_array(text, VARIADIC "any") 描述:获取返回值为字符型的模型进行模型推断任务。此函数为内部调用函数,建议直接使用语法[PREDICT BY](predict_by.md)进行推断任务。 参数:模型名称和推断任务的输入列。 返回值类型:text * gs\_explain\_model(text) 描述:获取返回值为字符型的模型进行模型解析文本化任务。 参数:模型名称。 返回值类型:text 示例请参见[CREATE MODEL](create_model.md)。 --- --- url: /zh/docs/latest-lite/characteristic_description/ai_capabilities.md --- # AI能力 人工智能技术最早可以追溯到上世纪50年代,甚至比数据库系统的发展历史还要悠久。但是,由于各种各样客观因素的制约,在很长的一段时间内,人工智能技术并没有得到大规模的应用,甚至还经历了几次明显的低谷期。到了近些年,随着信息技术的进一步发展,从前限制人工智能发展的因素已经逐渐减弱,所谓的ABC(AI、Big data、Cloud computing)技术也随之而诞生。 AI与数据库结合是近些年的行业研究热点,openGauss较早地参与了该领域的探索,并取得了阶段性的成果。AI特性子模块名为DBMind,相对数据库其他功能更为独立,大致可分为AI4DB和DB4AI两个部分。 * AI4DB就是指用人工智能技术优化数据库的性能,从而获得更好地执行表现;也可以通过人工智能的手段实现自治、免运维等。主要包括自调优、自诊断、自安全、自运维、自愈等子领域; * DB4AI就是指打通数据库到人工智能应用的端到端流程,通过数据库来驱动AI任务,统一人工智能技术栈,达到开箱即用、高性能、节约成本等目的。例如通过SQL-like语句实现推荐系统、图像检索、时序预测等功能,充分发挥数据库的高并行、列存储等优势,既可以避免数据和碎片化存储的代价,又可以避免因信息泄漏造成的安全风险; * AI in DB 就是对数据库内核进行修改,实现原有数据库架构模式下无法实现的功能,如利用AI算法改进数据库的优化器,实现更精确的代价估计等。 本章节所涉及的功能独立存在于数据库安装目录($**GAUSSHOME**)的bin/dbmind目录中,各个子功能存在于dbmind的子目录components中。提供gs\_dbmind命令行供用户调用。与此同时,对于数据库内置AI的功能(如DB4AI),以SQL语法和系统函数的形式呈现。 * **[AI4DB: 数据库自治运维](database_metric_collection_forecast_and_exception_detection.md)** * **[DB4AI: 数据库驱动AI](db4ai_database_driven_ai.md)** --- --- url: /zh/docs/latest/characteristic_description/ai_capabilities.md --- # AI能力 人工智能技术最早可以追溯到上世纪50年代,甚至比数据库系统的发展历史还要悠久。但是,由于各种各样客观因素的制约,在很长的一段时间内,人工智能技术并没有得到大规模的应用,甚至还经历了几次明显的低谷期。到了近些年,随着信息技术的进一步发展,从前限制人工智能发展的因素已经逐渐减弱,所谓的ABC(AI、Big data、Cloud computing)技术也随之而诞生。 AI与数据库结合是近些年的行业研究热点,openGauss较早地参与了该领域的探索,并取得了阶段性的成果。AI特性子模块名为DBMind,相对数据库其他功能更为独立,大致可分为AI4DB、DB4AI和ABO优化器三个部分。 * AI4DB就是指用人工智能技术优化数据库的性能,从而获得更好地执行表现;也可以通过人工智能的手段实现自治、免运维等。主要包括自调优、自诊断、自安全、自运维、自愈等子领域; * DB4AI就是指打通数据库到人工智能应用的端到端流程,通过数据库来驱动AI任务,统一人工智能技术栈,达到开箱即用、高性能、节约成本等目的。例如通过SQL-like语句实现推荐系统、图像检索、时序预测等功能,充分发挥数据库的高并行、列存储等优势,既可以避免数据和碎片化存储的代价,又可以避免因信息泄漏造成的安全风险; 本章节所涉及的功能独立存在于数据库安装目录($**GAUSSHOME**)的bin/dbmind目录中,各个子功能存在于dbmind的子目录components中。提供gs\_dbmind命令行供用户调用。与此同时,对于数据库内置AI的功能(如DB4AI),以SQL语法和系统函数的形式呈现。 * **[AI4DB: 数据库自治运维](./aifeature_guide/ai4db_autonomous_database_o_m.md)** * **[DB4AI: 数据库驱动AI](db4ai_database_driven_ai.md)** * **[ABO优化器](./aifeature_guide/intelligent_cardinality_estimation.md)** --- --- url: /en/docs/latest-lite/database_reference/alarm_detection.md --- # Alarm Detection During the running of openGauss, error scenarios can be detected so that users are informed of the errors in time. You can view the **system\_alarm** log written by the alarm in the *$GAUSSLOG***/cm** directory. ## enable\_alarm **Parameter description**: Specifies whether to enable the alarm detection thread to detect fault scenarios that may occur in the database. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that the alarm detection thread is enabled. * **off** indicates that the alarm detection thread is disabled. **Default value**: **on** > \[!NOTE]NOTE > This parameter takes effect only on DNs. ## connection\_alarm\_rate **Parameter description**: Specifies the ratio restriction on the maximum number of allowed parallel connections to the database. The maximum number of concurrent connections to the database is [max\_connections](connection_settings.md#en-us_topic_0283136886_en-us_topic_0237124695_en-us_topic_0059777636_sa723b719fa70453bb7ec27f323d41c79) x **connection\_alarm\_rate**. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** a floating point number ranging from 0.0 to 1.0 **Default value**: **0.9** ## alarm\_report\_interval **Parameter description**: specifies the interval at which an alarm is reported. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer. The unit is s. **Default value:** **10** ## alarm\_component **Parameter description**: Certain alarms are suppressed during alarm reporting. That is, the same alarm will not be repeatedly reported by an instance within the period specified by **alarm\_report\_interval**. Its default value is **10s**. In this case, the parameter specifies the location of the alarm component that is used to process alarm information. Only the sysadmin user can access this parameter. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string * If **--alarm-type** in the **gs\_preinstall** script is set to **5**, no third-party component is connected and alarms are written into the **system\_alarm** log. In this case, the value of **alarm\_component** is **/opt/huawei/snas/bin/snas\_cm\_cmd**. * If **--alarm-type** in the **gs\_preinstall** script is set to **1**, a third-party component is connected. In this case, the value of **alarm\_component** is the absolute path of the executable program of the third-party component. **Default value**: **/opt/huawei/snas/bin/snas\_cm\_cmd** ## table\_skewness\_warning\_threshold **Parameter description**: Specifies the threshold for triggering a table skew alarm. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a floating point number ranging from 0 to 1 **Default value**: **1** ## table\_skewness\_warning\_rows **Parameter description**: Specifies the number of rows for triggering a table skew alarm. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to *INT\_MAX* **Default value**: **100000** --- --- url: /en/docs/latest/database_reference/alarm_detection.md --- # Alarm Detection During the running of openGauss, error scenarios can be detected so that users are informed of the errors in time. You can view the **system\_alarm** log written by the alarm in the *$GAUSSLOG***/cm** directory. ## enable\_alarm **Parameter description**: Specifies whether to enable the alarm detection thread to detect fault scenarios that may occur in the database. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that the alarm detection thread is enabled. * **off** indicates that the alarm detection thread is disabled. **Default value**: **on** > \[!NOTE]NOTE > This parameter takes effect only on DNs. ## connection\_alarm\_rate **Parameter description**: Specifies the ratio restriction on the maximum number of allowed parallel connections to the database. The maximum number of concurrent connections to the database is [max\_connections](connection_settings.md#en-us_topic_0283136886_en-us_topic_0237124695_en-us_topic_0059777636_sa723b719fa70453bb7ec27f323d41c79) x **connection\_alarm\_rate**. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** a floating point number ranging from 0.0 to 1.0 **Default value**: **0.9** ## alarm\_report\_interval **Parameter description**: specifies the interval at which an alarm is reported. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer. The unit is s. **Default value:** **10** ## alarm\_component **Parameter description**: Certain alarms are suppressed during alarm reporting. That is, the same alarm will not be repeatedly reported by an instance within the period specified by **alarm\_report\_interval**. Its default value is **10s**. In this case, the parameter specifies the location of the alarm component that is used to process alarm information. Only the sysadmin user can access this parameter. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string * If **--alarm-type** in the **gs\_preinstall** script is set to **5**, no third-party component is connected and alarms are written into the **system\_alarm** log. In this case, the value of **alarm\_component** is **/opt/huawei/snas/bin/snas\_cm\_cmd**. * If **--alarm-type** in the **gs\_preinstall** script is set to **1**, a third-party component is connected. In this case, the value of **alarm\_component** is the absolute path of the executable program of the third-party component. **Default value**: **/opt/huawei/snas/bin/snas\_cm\_cmd** ## table\_skewness\_warning\_threshold **Parameter description**: Specifies the threshold for triggering a table skew alarm. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a floating point number ranging from 0 to 1 **Default value**: **1** ## table\_skewness\_warning\_rows **Parameter description**: Specifies the number of rows for triggering a table skew alarm. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to *INT\_MAX* **Default value**: **100000** --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark_ALIAS.md --- # ALIAS ## d\_format\_behavior\_compat\_options **功能描述** 实现等号别名语法,当开启参数disable\_target\_alias后,等号按照之前的语法解析。默认不开启参数,按照别名语法解析。 **注意事项** * 本功能未对openGauss的语法做任何修改,是在语义分析时做的转换。 * 别名不支持单引号包裹,可使用更通用的双引号或方括号包裹。 **语法格式** ```sql set d_format_behavior_compat_options = ''; --等号按照别名语法解析 set d_format_behavior_compat_options= 'disable_target_alias'; --等号按照原始等号语法解析 ``` **示例** ```sql openGauss=# CREATE TABLE test(a int, b int); CREATE TABLE openGauss=# INSERT INTO test VALUES (1,1), (2,3); INSERT 0 2 openGauss=# SET d_format_behavior_compat_options = ''; SET openGauss=# SELECT a = 1; a --- 1 (1 row) openGauss=# SELECT a = b FROM test; a --- 1 3 (2 rows) openGauss=# SET d_format_behavior_compat_options = 'disable_target_alias'; SET openGauss=# SELECT a = 1; ERROR: column "a" does not exist LINE 1: SELECT a = 1; ^ openGauss=# SELECT a = b FROM test; ?column? ---------- t f (2 rows) ``` --- --- url: /zh/docs/latest/extension_reference/extension_reference/server/shark_ALIAS.md --- # ALIAS ## d\_format\_behavior\_compat\_options **功能描述** 实现等号别名语法,当开启参数disable\_target\_alias后,等号按照之前的语法解析。默认不开启参数,按照别名语法解析。 **注意事项** * 本功能未对openGauss的语法做任何修改,是在语义分析时做的转换。 * 别名不支持单引号包裹,可使用更通用的双引号或方括号包裹。 **语法格式** ```sql set d_format_behavior_compat_options = ''; --等号按照别名语法解析 set d_format_behavior_compat_options= 'disable_target_alias'; --等号按照原始等号语法解析 ``` **示例** ```sql openGauss=# CREATE TABLE test(a int, b int); CREATE TABLE openGauss=# INSERT INTO test VALUES (1,1), (2,3); INSERT 0 2 openGauss=# SET d_format_behavior_compat_options = ''; SET openGauss=# SELECT a = 1; a --- 1 (1 row) openGauss=# SELECT a = b FROM test; a --- 1 3 (2 rows) openGauss=# SET d_format_behavior_compat_options = 'disable_target_alias'; SET openGauss=# SELECT a = 1; ERROR: column "a" does not exist LINE 1: SELECT a = 1; ^ openGauss=# SELECT a = b FROM test; ?column? ---------- t f (2 rows) ``` --- --- url: /en/docs/latest-lite/brief_tutorial/aliases.md --- # Aliases SQL can rename a table or a column. The name is the alias of the table or the column. Aliases are created to improve the readability of table names or column names. In SQL, **AS** is used to create an alias. ## Syntax * Column alias syntax ``` SELECT { * | [column [ AS ] output_name, ...] } [ FROM from_item [, ...] ] [ WHERE condition ]; ``` * Table alias syntax ``` SELECT column1, column2.... FROM table_name AS output_name WHERE [condition]; ``` ## Parameter Description * **output\_name** You may use the **AS output\_name** clause to give an alias for an output column. The alias is used for displaying the output column. The **name**, **value**, and **type** keywords can be used as column aliases. ## Examples Use **C** to indicate the alias of the **customer\_t1** table to query data in the table. ``` openGauss=# SELECT c.c_first_name,c.amount FROM customer_t1 AS c; c_first_name | amount --------------+-------- Grace | 1000 Grace | | Joes | 2200 James | 5000 Local | 3000 Lily | 1000 Lily | 2000 (8 rows) ``` --- --- url: /en/docs/latest-lite/sql_reference/aliases.md --- # Aliases SQL can rename a table or a column. The name is the alias of the table or the column. Aliases are created to improve the readability of table names or column names. In SQL, **AS** is used to create an alias. ## Syntax * Column alias syntax ``` SELECT { * | [column [ AS ] output_name, ...] } [ FROM from_item [, ...] ] [ WHERE condition ]; ``` * Table alias syntax ``` SELECT column1, column2.... FROM table_name AS output_name WHERE [condition]; ``` ## Parameter Description * **output\_name** You may use the **AS output\_name** clause to give an alias for an output column. The alias is used for displaying the output column. The **name**, **value**, and **type** keywords can be used as column aliases. ## Examples Use **C** to indicate the alias of the **customer\_t1** table to query data in the table. ``` openGauss=# SELECT c.c_first_name,c.amount FROM customer_t1 AS c; c_first_name | amount --------------+-------- Grace | 1000 Grace | | Joes | 2200 James | 5000 Local | 3000 Lily | 1000 Lily | 2000 (8 rows) ``` --- --- url: /en/docs/latest/sql_reference/aliases.md --- # Aliases SQL can rename a table or a column. The name is the alias of the table or the column. Aliases are created to improve the readability of table names or column names. In SQL, **AS** is used to create an alias. ## Syntax * Column alias syntax ``` SELECT { * | [column [ AS ] output_name, ...] } [ FROM from_item [, ...] ] [ WHERE condition ]; ``` * Table alias syntax ``` SELECT column1, column2.... FROM table_name AS output_name WHERE [condition]; ``` ## Parameter Description * **output\_name** You may use the **AS output\_name** clause to give an alias for an output column. The alias is used for displaying the output column. The **name**, **value**, and **type** keywords can be used as column aliases. ## Examples Use **C** to indicate the alias of the **customer\_t1** table to query data in the table. ``` openGauss=# SELECT c.c_first_name,c.amount FROM customer_t1 AS c; c_first_name | amount --------------+-------- Grace | 1000 Grace | | Joes | 2200 James | 5000 Local | 3000 Lily | 1000 Lily | 2000 (8 rows) ``` --- --- url: /en/docs/latest/sql_reference/brief_tutorial/aliases.md --- # Aliases SQL can rename a table or a column. The name is the alias of the table or the column. Aliases are created to improve the readability of table names or column names. In SQL, **AS** is used to create an alias. ## Syntax * Column alias syntax ``` SELECT { * | [column [ AS ] output_name, ...] } [ FROM from_item [, ...] ] [ WHERE condition ]; ``` * Table alias syntax ``` SELECT column1, column2.... FROM table_name AS output_name WHERE [condition]; ``` ## Parameter Description * **output\_name** You may use the **AS output\_name** clause to give an alias for an output column. The alias is used for displaying the output column. The **name**, **value**, and **type** keywords can be used as column aliases. ## Examples Use **C** to indicate the alias of the **customer\_t1** table to query data in the table. ``` openGauss=# SELECT c.c_first_name,c.amount FROM customer_t1 AS c; c_first_name | amount --------------+-------- Grace | 1000 Grace | | Joes | 2200 James | 5000 Local | 3000 Lily | 1000 Lily | 2000 (8 rows) ``` --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-ALL_COLUMNS.md --- # ALL\_COLUMNS 用户定义对象和系统对象的所有列的集合。 **表1** ALL\_COLUMNS --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-ALL_COLUMNS.md --- # ALL\_COLUMNS 用户定义对象和系统对象的所有列的集合。 **表1** ALL\_COLUMNS --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-ALL_OBJECTS.md --- # ALL\_OBJECTS 所有架构范围内的用户定义对象和系统对象的集合。 **表1** ALL\_OBJECTS 所有架构范围内的用户定义对象和系统对象的集合。 **表1** ALL\_OBJECTS --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-ALL_OBJECTS.md --- # ALL\_OBJECTS 所有架构范围内的用户定义对象和系统对象的集合。 **表1** ALL\_OBJECTS --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-ALL_VIEWS.md --- # ALL\_VIEWS 返回所有系统视图和用户视图相关的信息。 **表1** ALL\_VIEWS --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-ALL_VIEWS.md --- # ALL\_VIEWS 返回所有系统视图和用户视图相关的信息。 **表1** ALL\_VIEWS --- --- url: /en/docs/latest-lite/sql_reference/alter_aggregate.md --- # ALTER AGGREGATE ## Function **ALTER AGGREGATE** modifies the definition of an aggregate function. ## Precautions To use **ALTER AGGREGATE**, you must be the owner of the aggregate function. To change the schema of an aggregate function, you must have the **CREATE** permission on the new schema. To change the owner, you must be a direct or indirect member of the new role, and the role must have the **CREATE** permission on the aggregate function's schema. (This restricts the owner from doing anything except for deleting and recreating aggregate functions. However, a user with the SYSADMIN permission can change the ownership of an aggregate function in any way.) ## Syntax ``` ALTER AGGREGATE name ( argtype [ , ... ] ) RENAME TO new_name ALTER AGGREGATE name ( argtype [ , ... ] ) OWNER TO new_owner ALTER AGGREGATE name ( argtype [ , ... ] ) SET SCHEMA new_schema ``` ## Parameter Description * **name** Name (optionally schema-qualified) of an existing aggregate function. * **argtype** Input data type of the aggregate function. To reference a zero-parameter aggregate function, you can write an asterisk (\*) instead of a list of input data types. * **new\_name** New name of the aggregate function. * **new\_owner** New owner of the aggregate function. * **new\_schema** New schema of the aggregate function. ## Examples Rename the aggregate function **myavg** that accepts integer-type parameters to **my\_average**. ``` ALTER AGGREGATE myavg(integer) RENAME TO my_average; ``` Change the owner of the aggregate function **myavg** that accepts integer-type parameters to **joe**. ``` ALTER AGGREGATE myavg(integer) OWNER TO joe; ``` Move the aggregate function **myavg** that accepts integer-type parameters to **myschema**. ``` ALTER AGGREGATE myavg(integer) SET SCHEMA myschema; ``` ## Compatibility The SQL standard does not contain the **ALTER AGGREGATE** statement. --- --- url: /en/docs/latest/sql_reference/alter_aggregate.md --- # ALTER AGGREGATE ## Function **ALTER AGGREGATE** modifies the definition of an aggregate function. ## Precautions To use **ALTER AGGREGATE**, you must be the owner of the aggregate function. To change the schema of an aggregate function, you must have the **CREATE** permission on the new schema. To change the owner, you must be a direct or indirect member of the new role, and the role must have the **CREATE** permission on the aggregate function's schema. (This restricts the owner from doing anything except for deleting and recreating aggregate functions. However, a user with the SYSADMIN permission can change the ownership of an aggregate function in any way.) ## Syntax ``` ALTER AGGREGATE name ( argtype [ , ... ] ) RENAME TO new_name ALTER AGGREGATE name ( argtype [ , ... ] ) OWNER TO new_owner ALTER AGGREGATE name ( argtype [ , ... ] ) SET SCHEMA new_schema ``` ## Parameter Description * **name** Name (optionally schema-qualified) of an existing aggregate function. * **argtype** Input data type of the aggregate function. To reference a zero-parameter aggregate function, you can write an asterisk (\*) instead of a list of input data types. * **new\_name** New name of the aggregate function. * **new\_owner** New owner of the aggregate function. * **new\_schema** New schema of the aggregate function. ## Examples Rename the aggregate function **myavg** that accepts integer-type parameters to **my\_average**. ``` ALTER AGGREGATE myavg(integer) RENAME TO my_average; ``` Change the owner of the aggregate function **myavg** that accepts integer-type parameters to **joe**. ``` ALTER AGGREGATE myavg(integer) OWNER TO joe; ``` Move the aggregate function **myavg** that accepts integer-type parameters to **myschema**. ``` ALTER AGGREGATE myavg(integer) SET SCHEMA myschema; ``` ## Compatibility The SQL standard does not contain the **ALTER AGGREGATE** statement. --- --- url: /zh/docs/latest-lite/sql_reference/alter_aggregate.md --- # ALTER AGGREGATE ## 功能描述 修改一个聚合函数的定义。 ## 注意事项 要使用 ALTER AGGREGATE ,你必须是该聚合函数的所有者。 要改变一个聚合函数的模式,你必须在新模式上有 CREATE 权限。 要改变所有者,你必须是新所有角色的一个直接或间接成员,并且该角色必须在聚合函数的模式上有 CREATE 权限。(这些限制强制了修改该所有者不会做任何通过删除和重建聚合函数不能做的事情。不过,具有SYSADMIN权限用户可以用任何方法任意更改聚合函数的所属关系)。 ## 语法格式 ``` ALTER AGGREGATE name ( argtype [ , ... ] ) RENAME TO new_name ALTER AGGREGATE name ( argtype [ , ... ] ) OWNER TO new_owner ALTER AGGREGATE name ( argtype [ , ... ] ) SET SCHEMA new_schema ``` ## 参数说明 * **name** 现有的聚合函数的名称(可以有模式修饰)。 * **argtype** 聚合函数操作的输入数据类型。要引用一个零参数聚合函数,可以写入\*代替输入数据类型列表。 * **new\_name** 聚合函数的新名字。 * **new\_owner** 聚合函数的新所有者。 * **new\_schema** 聚合函数的新模式。 ## 示例 把一个接受integer 类型参数的聚合函数myavg重命名为 my\_average : ``` ALTER AGGREGATE myavg(integer) RENAME TO my_average; ``` 把一个接受integer 类型参数的聚合函数myavg的所有者改为joe : ``` ALTER AGGREGATE myavg(integer) OWNER TO joe; ``` 把一个接受integer 类型参数的聚合函数myavg移动到模式myschema里: ``` ALTER AGGREGATE myavg(integer) SET SCHEMA myschema; ``` ## 兼容性 SQL标准里没有ALTER AGGREGATE语句。 --- --- url: /zh/docs/latest/sql_reference/alter_aggregate.md --- # ALTER AGGREGATE ## 功能描述 修改一个聚合函数的定义。 ## 注意事项 要使用 ALTER AGGREGATE ,你必须是该聚合函数的所有者。 要改变一个聚合函数的模式,你必须在新模式上有 CREATE 权限。要改变所有者,你必须是新所有角色的一个直接或间接成员,并且该角色必须在聚合函数的模式上有 CREATE 权限。(这些限制强制了修改该所有者不会做任何通过删除和重建聚合函数不能做的事情。不过,具有SYSADMIN权限用户可以用任何方法任意更改聚合函数的所属关系)。 ## 语法格式 ``` ALTER AGGREGATE name ( argtype [ , ... ] ) RENAME TO new_name ALTER AGGREGATE name ( argtype [ , ... ] ) OWNER TO new_owner ALTER AGGREGATE name ( argtype [ , ... ] ) SET SCHEMA new_schema ``` ## 参数说明 * **name** 现有的聚合函数的名称(可以有模式修饰)。 * **argtype** 聚合函数操作的输入数据类型。要引用一个零参数聚合函数,可以写入\*代替输入数据类型列表。 * **new\_name** 聚合函数的新名字。 * **new\_owner** 聚合函数的新所有者。 * **new\_schema** 聚合函数的新模式。 ## 示例 把一个接受integer 类型参数的聚合函数myavg重命名为 my\_average : ``` ALTER AGGREGATE myavg(integer) RENAME TO my_average; ``` 把一个接受integer 类型参数的聚合函数myavg的所有者改为joe : ``` ALTER AGGREGATE myavg(integer) OWNER TO joe; ``` 把一个接受integer 类型参数的聚合函数myavg移动到模式myschema里: ``` ALTER AGGREGATE myavg(integer) SET SCHEMA myschema; ``` ## 兼容性 SQL标准里没有ALTER AGGREGATE语句。 --- --- url: /en/docs/latest-lite/sql_reference/alter_audit_policy.md --- # ALTER AUDIT POLICY ## Function **ALTER AUDIT POLICY** modifies the unified audit policy. ## Precautions * Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. * The unified audit policy takes effect only after **enable\_security\_policy** is set to **on**. ## Syntax ``` ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ADD | REMOVE } { [ privilege_audit_clause ] [ access_audit_clause ] }; ALTER AUDIT POLICY [ IF EXISTS ] policy_name MODIFY ( filter_group_clause ); ALTER AUDIT POLICY [ IF EXISTS ] policy_name DROP FILTER; ALTER AUDIT POLICY [ IF EXISTS ] policy_name COMMENTS policy_comments; ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ENABLE | DISABLE }; ``` * privilege\_audit\_clause ``` PRIVILEGES { DDL | ALL } ``` * access\_audit\_clause ``` ACCESS { DML | ALL } ``` * filter\_group\_clause ``` FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## Parameter Description * **policy\_name** Specifies the audit policy name, which must be unique. Value range: a string. It must comply with the identifier naming convention. * **DDL** Specifies the operations that are audited in the database: **CREATE**, **ALTER**, **DROP**, **ANALYZE**, **COMMENT**, **GRANT**, **REVOKE**, **SET**, **SHOW**, **LOGIN\_ANY**, **LOGIN\_FAILURE**, **LOGIN\_SUCCESS**, and **LOGOUT**. * **ALL** Specifies all operations supported by the specified DDL statements in the database. * **DML** Specifies the operations that are audited in the database: **SELECT**, **COPY**, **DEALLOCATE**, **DELETE**, **EXECUTE**, **INSERT**, **PREPARE**, **REINDEX**, **TRUNCATE**, and **UPDATE**. * **FILTER\_TYPE** Specifies the types of information to be filtered by the policy: **IP**, **ROLES**, and **APP**. * **filter\_value** Specifies the detailed information to be filtered. * **policy\_comments** Records description information of the audit policy. * **ENABLE|DISABLE** Enables or disables the unified audit policy. If **ENABLE|DISABLE** is not specified, **ENABLE** is used by default. ## Examples See [Examples](create_audit_policy.md#section7854941155112) in **CREATE AUDIT POLICY**. ## Helpful Links [CREATE AUDIT POLICY](create_audit_policy.md) and [DROP AUDIT POLICY](drop_audit_policy.md) --- --- url: /en/docs/latest/sql_reference/alter_audit_policy.md --- # ALTER AUDIT POLICY ## Function **ALTER AUDIT POLICY** modifies the unified audit policy. ## Precautions * Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. * The unified audit policy takes effect only after **enable\_security\_policy** is set to **on**. ## Syntax ``` ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ADD | REMOVE } { [ privilege_audit_clause ] [ access_audit_clause ] }; ALTER AUDIT POLICY [ IF EXISTS ] policy_name MODIFY ( filter_group_clause ); ALTER AUDIT POLICY [ IF EXISTS ] policy_name DROP FILTER; ALTER AUDIT POLICY [ IF EXISTS ] policy_name COMMENTS policy_comments; ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ENABLE | DISABLE }; ``` * privilege\_audit\_clause ``` PRIVILEGES { DDL | ALL } ``` * access\_audit\_clause ``` ACCESS { DML | ALL } ``` * filter\_group\_clause ``` FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## Parameter Description * **policy\_name** Specifies the audit policy name, which must be unique. Value range: a string. It must comply with the identifier naming convention. * **DDL** Specifies the operations that are audited in the database: **CREATE**, **ALTER**, **DROP**, **ANALYZE**, **COMMENT**, **GRANT**, **REVOKE**, **SET**, **SHOW**, **LOGIN\_ANY**, **LOGIN\_FAILURE**, **LOGIN\_SUCCESS**, and **LOGOUT**. * **ALL** Specifies all operations supported by the specified DDL statements in the database. * **DML** Specifies the operations that are audited in the database: **SELECT**, **COPY**, **DEALLOCATE**, **DELETE**, **EXECUTE**, **INSERT**, **PREPARE**, **REINDEX**, **TRUNCATE**, and **UPDATE**. * **FILTER\_TYPE** Specifies the types of information to be filtered by the policy: **IP**, **ROLES**, and **APP**. * **filter\_value** Specifies the detailed information to be filtered. * **policy\_comments** Records description information of the audit policy. * **ENABLE|DISABLE** Enables or disables the unified audit policy. If **ENABLE|DISABLE** is not specified, **ENABLE** is used by default. ## Examples See [Examples](create_audit_policy.md#section7854941155112) in **CREATE AUDIT POLICY**. ## Helpful Links [CREATE AUDIT POLICY](create_audit_policy.md) and [DROP AUDIT POLICY](drop_audit_policy.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_audit_policy.md --- # ALTER AUDIT POLICY ## 功能描述 修改统一审计策略。 ## 注意事项 * 只有poladmin,sysadmin或初始用户用户才能进行此操作。 * 需要打开enable\_security\_policy开关统一审计策略才可以生效。 ## 语法格式 ``` ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ADD | REMOVE } { [ privilege_audit_clause ] [ access_audit_clause ] }; ALTER AUDIT POLICY [ IF EXISTS ] policy_name MODIFY ( filter_group_clause ); ALTER AUDIT POLICY [ IF EXISTS ] policy_name DROP FILTER; ALTER AUDIT POLICY [ IF EXISTS ] policy_name COMMENTS policy_comments; ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ENABLE | DISABLE }; ``` * privilege\_audit\_clause: ``` PRIVILEGES { DDL | ALL } ``` * access\_audit\_clause: ``` ACCESS { DML | ALL } ``` * filter\_group\_clause ``` FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## 参数说明 * **policy\_name** 审计策略名称,需要唯一,不可重复。 取值范围:字符串,要符合标识符的命名规范。 * **DDL** 指的是针对数据库执行如下操作时进行审计,目前支持:CREATE、ALTER、DROP、ANALYZE、COMMENT、GRANT、REVOKE、SET、SHOW。 * **ALL** 指的是上述DDL支持的所有对数据库的操作。 * **DML** 指的是针对数据库执行如下操作时进行审计,目前支持:SELECT、COPY、DEALLOCATE、DELETE、EXECUTE、INSERT、PREPARE、REINDEX、TRUNCATE、UPDATE。 * **FILTER\_TYPE** 指定审计策略的过滤信息,过滤类型包括:IP、ROLES、APP。 * **filter\_value** 指具体过滤信息内容。 * **policy\_comments** 用于记录策略相关的描述信息。 * **ENABLE|DISABLE** 可以打开或关闭统一审计策略。若不指定ENABLE|DISABLE,语句默认为ENABLE。 ## 示例 请参考CREATE AUDIT POLICY的[示例](create_audit_policy.md#section7854941155112)。 ## 相关链接 [CREATE AUDIT POLICY](create_audit_policy.md),[DROP AUDIT POLICY](drop_audit_policy.md)。 --- --- url: /zh/docs/latest/sql_reference/alter_audit_policy.md --- # ALTER AUDIT POLICY ## 功能描述 修改统一审计策略。 ## 注意事项 * 只有poladmin、sysadmin或初始用户用户才能进行此操作。 * 需要打开enable\_security\_policy开关统一审计策略才可以生效。 ## 语法格式 ``` ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ADD | REMOVE } { [ privilege_audit_clause ] [ access_audit_clause ] }; ALTER AUDIT POLICY [ IF EXISTS ] policy_name MODIFY ( filter_group_clause ); ALTER AUDIT POLICY [ IF EXISTS ] policy_name DROP FILTER; ALTER AUDIT POLICY [ IF EXISTS ] policy_name COMMENTS policy_comments; ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ENABLE | DISABLE }; ``` * privilege\_audit\_clause: ``` PRIVILEGES { DDL | ALL } ``` * access\_audit\_clause: ``` ACCESS { DML | ALL } ``` * filter\_group\_clause: ``` FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## 参数说明 * **policy\_name** 审计策略名称,需要唯一,不可重复。 取值范围:字符串,要符合标识符的命名规范。 * **DDL** 指的是针对数据库执行如下操作时进行审计,目前支持:CREATE、ALTER、DROP、ANALYZE、COMMENT、GRANT、REVOKE、SET、SHOW。 * **ALL** 指的是上述DDL支持的所有对数据库的操作。 * **DML** 指的是针对数据库执行如下操作时进行审计,目前支持:SELECT、COPY、DEALLOCATE、DELETE、EXECUTE、INSERT、PREPARE、REINDEX、TRUNCATE、UPDATE。 * **FILTER\_TYPE** 指定审计策略的过滤信息,过滤类型包括:IP、ROLES、APP。 * **filter\_value** 指具体过滤信息内容。 * **policy\_comments** 用于记录策略相关的描述信息。 * **ENABLE|DISABLE** 可以打开或关闭统一审计策略。若不指定ENABLE|DISABLE,语句默认为ENABLE。 ## 示例 请参考CREATE AUDIT POLICY的[示例](create_audit_policy.md)。 ## 相关链接 [CREATE AUDIT POLICY](create_audit_policy.md),[DROP AUDIT POLICY](drop_audit_policy.md)。 --- --- url: /en/docs/latest-lite/sql_reference/alter_data_source.md --- # ALTER DATA SOURCE ## Function **ALTER DATA SOURCE** modifies the attributes and content of the data source. The attributes include the name and owner. The content includes the type, version, and connection options. ## Precautions * Only the initial user, system administrator, and owner have the permission to modify data sources. * To change the owner, the new owner must be the initial user or a system administrator. * If the **password** option is displayed, ensure that the **datasource.key.cipher** and **datasource.key.rand** files exist in the *$GAUSSHOME***/bin** directory of each node in openGauss. If the two files do not exist, use the **gs\_guc** tool to generate them and use the **gs\_ssh** tool to release them to the *$GAUSSHOME***/bin** directory on each node. > \[!NOTE]NOTE > In the Lite scenario, openGauss provides this syntax, but the SQL on Anywhere capabilities are unavailable. ## Syntax ``` ALTER DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS ( {[ ADD | SET | DROP ] optname ['optvalue']} [, ...] )]; ALTER DATA SOURCE src_name RENAME TO src_new_name; ALTER DATA SOURCE src_name OWNER TO new_owner; ``` ## Parameter Description * **src\_name** Specifies the data source name to be modified. Value range: a string. It must comply with the identifier naming convention. * **TYPE** Changes the original **TYPE** value of the data source to the specified value. Value range: an empty string or a non-empty string * **VERSION** Changes the original **VERSION** value of the data source to the specified value. Value range: an empty string, a non-empty string, or null * **OPTIONS** Specifies the column to be added, modified, or deleted. The value of **optname** should be unique. Comply with the following rules to set this parameter: To add a column, you can omit **ADD** and simply specify the column name, which cannot be an existing column name. To modify a column, specify **SET** and an existing column name. To delete a column, specify **DROP** and an existing column name. Do not set **optvalue**. * **src\_new\_name** Specifies the new data source name. Value range: a string. It must comply with the naming convention rule. * **new\_user** Specifies the new owner of an object. Value range: a string. It must be a valid username. ## Examples ``` -- Create an empty data source. openGauss=# CREATE DATA SOURCE ds_test1; -- Rename the data source. openGauss=# ALTER DATA SOURCE ds_test1 RENAME TO ds_test; -- Change the owner. openGauss=# CREATE USER user_test1 IDENTIFIED BY 'Gs@123456'; openGauss=# ALTER USER user_test1 WITH SYSADMIN; openGauss=# ALTER DATA SOURCE ds_test OWNER TO user_test1; -- Modify TYPE and VERSION. openGauss=# ALTER DATA SOURCE ds_test TYPE 'MPPDB_TYPE' VERSION 'XXX'; -- Add a column. openGauss=# ALTER DATA SOURCE ds_test OPTIONS (add dsn 'gaussdb', username 'test_user'); -- Modify a column. openGauss=# ALTER DATA SOURCE ds_test OPTIONS (set dsn 'unknown'); -- Delete a column. openGauss=# ALTER DATA SOURCE ds_test OPTIONS (drop username); -- Delete the data source and user objects. openGauss=# DROP DATA SOURCE ds_test; openGauss=# DROP USER user_test1; ``` ## Helpful Links [CREATE DATA SOURCE](create_data_source.md) and [DROP DATA SOURCE](drop_data_source.md) --- --- url: /en/docs/latest/sql_reference/alter_data_source.md --- # ALTER DATA SOURCE ## Function **ALTER DATA SOURCE** modifies the attributes and content of the data source. The attributes include the name and owner. The content includes the type, version, and connection options. ## Precautions * Only the initial user, system administrator, and owner have the permission to modify data sources. * To change the owner, the new owner must be the initial user or a system administrator. * If the **password** option is displayed, ensure that the **datasource.key.cipher** and **datasource.key.rand** files exist in the *$GAUSSHOME*\*\*/bin\*\* directory of each node in openGauss. If the two files do not exist, use the **gs\_guc** tool to generate them and use the **gs\_ssh** tool to release them to the *$GAUSSHOME*\*\*/bin\*\* directory on each node. ## Syntax ``` ALTER DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS ( {[ ADD | SET | DROP ] optname ['optvalue']} [, ...] )]; ALTER DATA SOURCE src_name RENAME TO src_new_name; ALTER DATA SOURCE src_name OWNER TO new_owner; ``` ## Parameter Description * **src\_name** Specifies the data source name to be modified. Value range: a string. It must comply with the identifier naming convention. * **TYPE** Changes the original **TYPE** value of the data source to the specified value. Value range: an empty string or a non-empty string * **VERSION** Changes the original **VERSION** value of the data source to the specified value. Value range: an empty string, a non-empty string, or null * **OPTIONS** Specifies the column to be added, modified, or deleted. The value of **optname** should be unique. Comply with the following rules to set this parameter: To add a column, you can omit **ADD** and simply specify the column name, which cannot be an existing column name. To modify a column, specify **SET** and an existing column name. To delete a column, specify **DROP** and an existing column name. Do not set **optvalue**. * **src\_new\_name** Specifies the new data source name. Value range: a string. It must comply with the naming convention rule. * **new\_user** Specifies the new owner of an object. Value range: a string. It must be a valid username. ## Examples ``` -- Create an empty data source. openGauss=# CREATE DATA SOURCE ds_test1; -- Rename the data source. openGauss=# ALTER DATA SOURCE ds_test1 RENAME TO ds_test; -- Change the owner. openGauss=# CREATE USER user_test1 IDENTIFIED BY 'Gs@123456'; openGauss=# ALTER USER user_test1 WITH SYSADMIN; openGauss=# ALTER DATA SOURCE ds_test OWNER TO user_test1; -- Modify TYPE and VERSION. openGauss=# ALTER DATA SOURCE ds_test TYPE 'MPPDB_TYPE' VERSION 'XXX'; -- Add a column. openGauss=# ALTER DATA SOURCE ds_test OPTIONS (add dsn 'gaussdb', username 'test_user'); -- Modify a column. openGauss=# ALTER DATA SOURCE ds_test OPTIONS (set dsn 'unknown'); -- Delete a column. openGauss=# ALTER DATA SOURCE ds_test OPTIONS (drop username); -- Delete the data source and user objects. openGauss=# DROP DATA SOURCE ds_test; openGauss=# DROP USER user_test1; ``` ## Helpful Links [CREATE DATA SOURCE](create_data_source.md) and [DROP DATA SOURCE](drop_data_source.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_data_source.md --- # ALTER DATA SOURCE ## 功能描述 修改Data Source对象的属性和内容。 属性有:名称和属主;内容有:类型、版本和连接选项。 ## 注意选项 * 只有初始用户/系统管理员/属主才拥有修改Data Source的权限。 * 修改属主时,新的属主用户必须是初始用户或系统管理员。 * 当在OPTIONS中出现password选项时,需要保证openGauss每个节点的$GAUSSHOME/bin目录下存在datasource.key.cipher和datasource.key.rand文件,如果不存在这两个文件,请使用gs\_guc工具生成并放入每个节点的$GAUSSHOME/bin目录下。 > \[!NOTE]说明 > 轻量版场景下,openGauss提供此语法,但SQL on Anywhere不可用。 ## 语法格式 ``` ALTER DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS ( {[ ADD | SET | DROP ] optname ['optvalue']} [, ...] )]; ALTER DATA SOURCE src_name RENAME TO src_new_name; ALTER DATA SOURCE src_name OWNER TO new_owner; ``` ## 参数说明 * **src\_name** 待修改的Data Source的名称。 取值范围:字符串,需要符合标识符的命名规范。 * **TYPE** 将Data Source原来的TYPE修改为指定值。 取值范围:空串或非空字符串。 * **VERSION** 将Data Source原来的VERSION修改为指定值。 取值范围:空串或非空字符串或NULL。 * **OPTIONS** 修改OPTIONS中的字段:增加(ADD)、修改(SET)、删除(DROP),且字段名称optname需唯一,具体要求如下: 增加字段:ADD可以省略,待增加字段不能已经存在了; 修改字段:SET不可省略,待修改字段必须存在; 删除字段:DROP不可省略,待删除字段必须存在,且不能指定optvalue; * **src\_new\_name** 新的Data Source名称。 取值范围:字符串,需符合标识符命名规范。 * **new\_user** 对象的新属主。 取值范围:字符串,有效的用户名。 ## 示例 ``` --创建一个空Data Source对象。 openGauss=# CREATE DATA SOURCE ds_test1; --修改名称。 openGauss=# ALTER DATA SOURCE ds_test1 RENAME TO ds_test; --修改属主。 openGauss=# CREATE USER user_test1 IDENTIFIED BY 'XXXXXXXX'; openGauss=# ALTER USER user_test1 WITH SYSADMIN; openGauss=# ALTER DATA SOURCE ds_test OWNER TO user_test1; --修改TYPE和VERSION。 openGauss=# ALTER DATA SOURCE ds_test TYPE 'MPPDB_TYPE' VERSION 'XXX'; --添加字段。 openGauss=# ALTER DATA SOURCE ds_test OPTIONS (add dsn 'gaussdb', username 'test_user'); --修改字段。 openGauss=# ALTER DATA SOURCE ds_test OPTIONS (set dsn 'unknown'); --删除字段。 openGauss=# ALTER DATA SOURCE ds_test OPTIONS (drop username); --删除Data Source和user对象。 openGauss=# DROP DATA SOURCE ds_test; openGauss=# DROP USER user_test1; ``` ## 相关链接 [CREATE DATA SOURCE](create_data_source.md),[DROP DATA SOURCE](drop_data_source.md) --- --- url: /zh/docs/latest/sql_reference/alter_data_source.md --- # ALTER DATA SOURCE ## 功能描述 修改Data Source对象的属性和内容。 属性有:名称和属主;内容有:类型、版本和连接选项。 ## 注意选项 * 只有初始用户、系统管理员和属主才拥有修改Data Source的权限。 * 修改属主时,新的属主用户必须是初始用户或系统管理员。 * 当在OPTIONS中出现password选项时,需要保证openGauss每个节点的$GAUSSHOME/bin目录下存在datasource.key.cipher和datasource.key.rand文件,如果不存在这两个文件,请使用gs\_guc工具生成并使用gs\_ssh工具发布到每个节点的$GAUSSHOME/bin目录下。 ## 语法格式 ``` ALTER DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS ( {[ ADD | SET | DROP ] optname ['optvalue']} [, ...] )]; ALTER DATA SOURCE src_name RENAME TO src_new_name; ALTER DATA SOURCE src_name OWNER TO new_owner; ``` ## 参数说明 * **src\_name** 待修改的Data Source的名称。 取值范围:字符串,需要符合标识符的命名规范。 * **TYPE** 将Data Source原来的TYPE修改为指定值。 取值范围:空串或非空字符串。 * **VERSION** 将Data Source原来的VERSION修改为指定值。 取值范围:空串或非空字符串或NULL。 * **OPTIONS** 修改OPTIONS中的字段:增加(ADD)、修改(SET)、删除(DROP),且字段名称optname需唯一,具体要求如下: 增加字段:ADD可以省略,待增加字段不能已经存在了; 修改字段:SET不可省略,待修改字段必须存在; 删除字段:DROP不可省略,待删除字段必须存在,且不能指定optvalue; * **src\_new\_name** 新的Data Source名称。 取值范围:字符串,需符合标识符命名规范。 * **new\_user** 对象的新属主。 取值范围:字符串,有效的用户名。 ## 示例 ``` --创建一个空Data Source对象。 openGauss=# CREATE DATA SOURCE ds_test1; --修改名称。 openGauss=# ALTER DATA SOURCE ds_test1 RENAME TO ds_test; --修改属主。 openGauss=# CREATE USER user_test1 IDENTIFIED BY 'XXXXXXXX'; openGauss=# ALTER USER user_test1 WITH SYSADMIN; openGauss=# ALTER DATA SOURCE ds_test OWNER TO user_test1; --修改TYPE和VERSION。 openGauss=# ALTER DATA SOURCE ds_test TYPE 'MPPDB_TYPE' VERSION 'XXX'; --添加字段。 openGauss=# ALTER DATA SOURCE ds_test OPTIONS (add dsn 'gaussdb', username 'test_user'); --修改字段。 openGauss=# ALTER DATA SOURCE ds_test OPTIONS (set dsn 'unknown'); --删除字段。 openGauss=# ALTER DATA SOURCE ds_test OPTIONS (drop username); --删除Data Source和user对象。 openGauss=# DROP DATA SOURCE ds_test; openGauss=# DROP USER user_test1; ``` ## 相关链接 [CREATE DATA SOURCE](create_data_source.md),[DROP DATA SOURCE](drop_data_source.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_database.md --- # ALTER DATABASE ## Function **ALTER DATABASE** modifies a database, including its name, owner, connection limitation, and object isolation. ## Precautions * Only the database owner or a user granted with the ALTER permission can run the **ALTER DATABASE** command. The system administrator has this permission by default. The following is permission constraints depending on attributes to be modified: * To modify the database name, you must have the **CREATEDB** permission. * To modify a database owner, you must be a database owner or system administrator and a member of the new owner role, with the **CREATEDB** permission. * To modify the default tablespace of a database, a user must have the permission to create a tablespace. This statement physically migrates tables and indexes in a default tablespace to a new tablespace. Note that tables and indexes outside the default tablespace are not affected. * You are not allowed to rename a database in use. To rename it, connect to another database. ## Syntax * Modify the maximum number of connections to the database. ``` ALTER DATABASE database_name [ [ WITH ] CONNECTION LIMIT connlimit ]; ``` * Rename the database. ``` ALTER DATABASE database_name RENAME TO new_name; ``` * Change the database owner. ``` ALTER DATABASE database_name OWNER TO new_owner; ``` * Change the default tablespace of the database. ``` ALTER DATABASE database_name SET TABLESPACE new_tablespace; ``` * Modify the session parameter value of the database. ``` ALTER DATABASE database_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ``` * Reset the database configuration parameter. ``` ALTER DATABASE database_name RESET { configuration_parameter | ALL }; ``` * Modify the object isolation attribute of the database. ``` ALTER DATABASE database_name [ WITH ] { ENABLE | DISABLE } PRIVATE OBJECT; ``` > \[!NOTE]NOTE > > * To modify the object isolation attribute of a database, the database must be connected. Otherwise, the modification will fail. > * For a new database, the object isolation attribute is disabled by default. After this attribute is enabled, common users can view only the objects (such as tables, functions, views, and columns) that they have the permission to access. This attribute does not take effect for administrators. After this attribute is enabled, administrators can still view all database objects. ## Parameter Description * **database\_name** Specifies the name of the database whose attributes are to be modified. Value range: a string. It must comply with the naming convention rule. * **connlimit** Specifies the maximum number of concurrent connections that can be made to this database (excluding administrators' connections). Value range: The value must be an integer, preferably from 1 to 50. The default value **-1** indicates that there is no restriction on the number of concurrent connections. * **new\_name** Specifies the new name of a database. Value range: a string. It must comply with the naming convention rule. * **new\_owner** Specifies the new owner of a database. Value range: a string. It must be a valid username. * **new\_tablespace** Specifies the new default tablespace of a database. The tablespace exists in the database. The default tablespace is **pg\_default**. Value range: a string. It must be a valid tablespace name. * **configuration\_parameter** **value** Sets a specified database session parameter to a specified value. If the value is **DEFAULT** or **RESET**, the default setting is used in the new session. **OFF** closes the setting. Value range: a string * DEFAULT * OFF * RESET * **FROM CURRENT** Sets the value of the database based on the current connected session. * **RESET configuration\_parameter** Resets the specified database session parameter. * **RESET ALL** Resets all database session parameters. > \[!NOTE]NOTE > > * Modify the default tablespace of a database by moving the table or index in the old tablespace into the new tablespace. This operation does not affect the tables or indexes in other non-default tablespaces. > * The modified database session parameter values will take effect in the next session. ## Examples See [Examples](create_database.md#en-us_topic_0283137050_en-us_topic_0237122099_en-us_topic_0059778277_s6be7b8abbb4b4aceb9dae686434d672c) in **CREATE DATABASE**. ## Helpful Links [CREATE DATABASE](create_database.md) and [DROP DATABASE](drop_database.md) --- --- url: /en/docs/latest/sql_reference/alter_database.md --- # ALTER DATABASE ## Function **ALTER DATABASE** modifies a database, including its name, owner, connection limitation, and object isolation. ## Precautions * Only the database owner or a user granted with the ALTER permission can run the **ALTER DATABASE** command. The system administrator has this permission by default. The following is permission constraints depending on attributes to be modified: * To modify the database name, you must have the **CREATEDB** permission. * To modify a database owner, you must be a database owner or system administrator and a member of the new owner role, with the **CREATEDB** permission. * To modify the default tablespace of a database, a user must have the permission to create a tablespace. This statement physically migrates tables and indexes in a default tablespace to a new tablespace. Note that tables and indexes outside the default tablespace are not affected. * You are not allowed to rename a database in use. To rename it, connect to another database. ## Syntax * Modify the maximum number of connections to the database. ``` ALTER DATABASE database_name [ [ WITH ] CONNECTION LIMIT connlimit ]; ``` * Rename the database. ``` ALTER DATABASE database_name RENAME TO new_name; ``` * Change the database owner. ``` ALTER DATABASE database_name OWNER TO new_owner; ``` * Change the default tablespace of the database. ``` ALTER DATABASE database_name SET TABLESPACE new_tablespace; ``` * Modify the session parameter value of the database. ``` ALTER DATABASE database_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ``` * Reset the database configuration parameter. ``` ALTER DATABASE database_name RESET { configuration_parameter | ALL }; ``` * Modify the object isolation attribute of the database. ``` ALTER DATABASE database_name [ WITH ] { ENABLE | DISABLE } PRIVATE OBJECT; ``` > \[!NOTE]NOTE > > * To modify the object isolation attribute of a database, the database must be connected. Otherwise, the modification will fail. > > * For a new database, the object isolation attribute is disabled by default. After this attribute is enabled, common users can view only the objects (such as tables, functions, views, and columns) that they have the permission to access. This attribute does not take effect for administrators. After this attribute is enabled, administrators can still view all database objects. ## Parameter Description * **database\_name** Specifies the name of the database whose attributes are to be modified. Value range: a string. It must comply with the naming convention rule. * **connlimit** Specifies the maximum number of concurrent connections that can be made to this database (excluding administrators' connections). Value range: The value must be an integer, preferably from 1 to 50. The default value **-1** indicates that there is no restriction on the number of concurrent connections. * **new\_name** Specifies the new name of a database. Value range: a string. It must comply with the naming convention rule. * **new\_owner** Specifies the new owner of a database. Value range: a string. It must be a valid username. * **new\_tablespace** Specifies the new default tablespace of a database. The tablespace exists in the database. The default tablespace is **pg\_default**. Value range: a string. It must be a valid tablespace name. * **configuration\_parameter** **value** Sets a specified database session parameter to a specified value. If the value is **DEFAULT** or **RESET**, the default setting is used in the new session. **OFF** closes the setting. Value range: a string * DEFAULT * OFF * RESET * **FROM CURRENT** Sets the value of the database based on the current connected session. * **RESET configuration\_parameter** Resets the specified database session parameter. * **RESET ALL** Resets all database session parameters. > \[!NOTE]NOTE > > * Modify the default tablespace of a database by moving the table or index in the old tablespace into the new tablespace. This operation does not affect the tables or indexes in other non-default tablespaces. > > * The modified database session parameter values will take effect in the next session. ## Examples See [Examples](create_database.md#en-us_topic_0283137050_en-us_topic_0237122099_en-us_topic_0059778277_s6be7b8abbb4b4aceb9dae686434d672c) in **CREATE DATABASE**. ## Helpful Links [CREATE DATABASE](create_database.md) and [DROP DATABASE](drop_database.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-ALTER-DATABASE.md --- # ALTER DATABASE ## 功能描述 修改数据库的属性,包括它的名称、所有者、连接数限制、对象隔离属性等。 修改模式的属性。仅在修改默认字符集和字符序时为模式的含义。 ## 注意事项 相比于原始的openGauss,dolphin对于ALTER DATABASE语法的修改为: * 增加可修改项 \[ \[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset ] \[ \[DEFAULT] COLLATE \[ = ] default\_collation ]。 ## 语法格式 * 修改SCHEMA的默认字符集和字符序 ``` ALTER DATABASE schema_name [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ]; ``` \[!NOTE]说明 * B兼容性下,仅在 dolphin.b\_compatibility\_mode 为on时支持该语法。 * 使用该语法时,语法等效于ALTER SCHEMA。 ## 参数说明 * **schema\_name** 需要修改属性的数据库名称。 取值范围:字符串,要符合标识符的命名规范。 * **\[ \[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset ]** 指定模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **\[ \[DEFAULT] COLLATE \[ = ] default\_collation ]** 指定模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 ## 示例 请参考CREATE DATABASE的[示例](dolphin-CREATE-DATABASE.md#zh-cn_topic_0283137050_zh-cn_topic_0237122099_zh-cn_topic_0059778277_s6be7b8abbb4b4aceb9dae686434d672c)。 ## 相关链接 [CREATE DATABASE](dolphin-CREATE-DATABASE.md),[DROP DATABASE](dolphin-DROP-DATABASE.md),[ALTER DATABASE](dolphin-ALTER-DATABASE.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_database.md --- # ALTER DATABASE ## 功能描述 修改数据库的属性,包括它的名称、所有者、连接数限制、对象隔离属性等。 ## 注意事项 * 只有数据库的所有者或者被授予了数据库ALTER权限的用户才能执行ALTER DATABASE命令,系统管理员默认拥有此权限。针对所要修改属性的不同,还有以下权限约束: * 修改数据库名称,必须拥有CREATEDB权限。 * 修改数据库所有者,当前用户必须是该database的所有者或者系统管理员,必须拥有CREATEDB权限,且该用户是新所有者角色的成员。 * 修改数据库默认表空间,必须拥有新表空间的CREATE权限。这个语句会从物理上将一个数据库原来缺省表空间上的表和索引移至新的表空间。注意不在缺省表空间的表和索引不受此影响。 * 不能重命名当前使用的数据库,如果需要重新命名,须连接至其他数据库上。 ## 语法格式 * 修改数据库的最大连接数。 ``` ALTER DATABASE database_name [ [ WITH ] CONNECTION LIMIT connlimit ]; ``` * 修改数据库名称。 ``` ALTER DATABASE database_name RENAME TO new_name; ``` * 修改数据库所属者。 ``` ALTER DATABASE database_name OWNER TO new_owner; ``` * 修改数据库默认表空间。 ``` ALTER DATABASE database_name SET TABLESPACE new_tablespace; ``` > \[!NOTE]说明 > \> > \> 如果该数据库中的某些表或对象已经创建在new\_tablespace下,则无法将该数据库的默认表空间修改为new\_tablespace,执行会报错。 * 修改数据库指定会话参数值。 ``` ALTER DATABASE database_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ``` * 数据库配置参数重置。 ``` ALTER DATABASE database_name RESET { configuration_parameter | ALL }; ``` * 修改数据库对象隔离属性。 ``` ALTER DATABASE database_name [ WITH ] { ENABLE | DISABLE } PRIVATE OBJECT; ``` > \[!NOTE]说明 > > * 修改数据库的对象隔离属性时须连接至该数据库,否则无法更改。 > * 新创建的数据库,对象隔离属性默认是关闭的。当开启数据库对象隔离属性后,普通用户只能查看有权访问的对象(表、函数、视图、字段等)。对象隔离特性对管理员用户不生效,当开启对象隔离特性后,管理员也可以查看到全量的数据库对象。 ## 参数说明 * **database\_name** 需要修改属性的数据库名称。 取值范围:字符串,要符合标识符的命名规范。 * **connlimit** 数据库可以接收的最大并发连接数(管理员用户连接除外)。 取值范围:整数,建议填写1~50的整数。-1(缺省)表示没有限制。 * **new\_name** 数据库的新名称。 取值范围:字符串,要符合标识符的命名规范。 * **new\_owner** 数据库的新所有者。 取值范围:字符串,有效的用户名。 * **new\_tablespace** 数据库新的默认表空间,该表空间为数据库中已经存在的表空间。默认的表空间为pg\_default。 取值范围:字符串,有效的表空间名。 * **configuration\_parameter** **value** 把指定的数据库会话参数值设置为给定的值。如果value是DEFAULT或者RESET,则在新的会话中使用系统的缺省设置。OFF关闭设置。 取值范围:字符串, * DEFAULT * OFF * RESET * **FROM CURRENT** 根据当前会话连接的数据库设置该参数的值。 * **RESET configuration\_parameter** 重置指定的数据库会话参数值。 * **RESET ALL** 重置全部的数据库会话参数值。 > \[!NOTE]说明 > > * 修改数据库默认表空间,会将旧表空间中的所有表和索引转移到新表空间中,该操作不会影响其他非默认表空间中的表和索引。 > * 修改的数据库会话参数值,将在下一次会话中生效。 ## 示例 请参考CREATE DATABASE的[示例](create_database.md#zh-cn_topic_0283137050_zh-cn_topic_0237122099_zh-cn_topic_0059778277_s6be7b8abbb4b4aceb9dae686434d672c)。 ## 相关链接 [CREATE DATABASE](create_database.md),[DROP DATABASE](drop_database.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-ALTER-DATABASE.md --- # ALTER DATABASE ## 功能描述 修改数据库的属性,包括它的名称、所有者、连接数限制、对象隔离属性等。 修改模式的属性。仅在修改默认字符集和字符序时为模式的含义。 ## 注意事项 相比于原始的openGauss,dolphin对于ALTER DATABASE语法的修改为: * 增加可修改项 \[ \[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset ] \[ \[DEFAULT] COLLATE \[ = ] default\_collation ]。 ## 语法格式 * 修改SCHEMA的默认字符集和字符序 ``` ALTER DATABASE schema_name [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ]; ``` \[!NOTE]说明 * B兼容性下,仅在 dolphin.b\_compatibility\_mode 为on时支持该语法。 * 使用该语法时,语法等效于ALTER SCHEMA。 ## 参数说明 * **schema\_name** 需要修改属性的数据库名称。 取值范围:字符串,要符合标识符的命名规范。 * **\[ \[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset ]** 指定模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **\[ \[DEFAULT] COLLATE \[ = ] default\_collation ]** 指定模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 ## 示例 请参考CREATE DATABASE的[示例](dolphin-CREATE-DATABASE.md#zh-cn_topic_0283137050_zh-cn_topic_0237122099_zh-cn_topic_0059778277_s6be7b8abbb4b4aceb9dae686434d672c)。 ## 相关链接 [CREATE DATABASE](dolphin-CREATE-DATABASE.md),[DROP DATABASE](dolphin-DROP-DATABASE.md),[ALTER DATABASE](dolphin-ALTER-DATABASE.md) --- --- url: /zh/docs/latest/ograc/sql_reference/alter_database.md --- # ALTER DATABASE ## 功能描述 ALTER DATABASE用于修改数据库。 ## 注意事项 * 被授予了ALTER DATABASE权限的用户才能执行该命令。 ## 语法格式 * 指定数据库状态为MOUNT或者OPEN ``` ALTER DATABASE [ database_name ] { MOUNT | OPEN [ RESETLOGS | READ ONLY | READ WRITE | RESTRICTED | UPGRADE | FORCE IGNORE LOGS | [ UPGRADE ] REPLAY UNTIL lfn ] [ IGNORE SYSTIME ] }; ``` * 添加或删除日志文件 ``` ALTER DATABASE [ database_name ] { ARCHIVELOG | NOARCHIVELOG | ADD LOGFILE ( { 'file_name' SIZE integer [ B | K | M | G | T | P | E ] [ BLOCKSIZE { 512 | 4096 } ] } [,...] ) | DROP LOGFILE ( 'file_name' ) | ARCHIVE LOGFILE ( { 'file_name' } [,...] ) } ``` * 删除归档日志文件 ``` ALTER DATABASE [ database_name ] DELETE ARCHIVELOG { ALL | UNTIL TIME 'date_string' } [ FORCE ] ``` * 切换数据库备机的数据保护模式 ``` ALTER DATABASE [ database_name ] SET STANDBY DATABASE TO MAXIMIZE { PROTECTION | AVAILABILITY | PERFORMANCE } ``` * 修改一个或多个数据文件的属性 ``` ALTER DATABASE [ database_name ] DATAFILE { 'file_name' | file_number } [,...] { AUTOEXTEND { OFF | ON [ NEXT integer [ K | M | G ] | MAXSIZE { integer [ K | M | G ] | UNLIMITED } ] } | RESIZE integer [ K | M | G ] } ``` * 清理和重建日志文件 ``` ALTER DATABASE [ database_name ] CLEAR LOGFILE file_id ``` * 主备切换 ``` ALTER DATABASE [ database_name ] SWITCHOVER [TIMEOUT tm_s] ``` * 备机升主 ``` ALTER DATABASE [ database_name ] FAILOVER [ FORCE ] ``` * 取消升级模式 ``` ALTER DATABASE [ database_name ] CANCEL UPGRADE ``` * 修改数据库状态 ``` ALTER DATABASE [ database_name ] CONVERT TO { READONLY | READWRITE | [ CASCADED ] PHYSICAL STANDBY [ MOUNT ] } ``` * 删除备份集物理文件及SYS\_BACKUP\_SETS中备份集记录。 ``` ALTER DATABASE [ database_name ] DELETE BACKUPSET 'tag' [ FORCE ] ``` * 重建表空间 ``` ALTER DATABASE [ database_name ] REBUILD TABLESPACE tablespace_name ``` * 打开或关闭全局级逻辑复制开关 ``` ALTER DATABASE [ database_name ] ENABLE_LOGIC_REPLICATION { ON | OFF } ``` * 更新及同步密钥 ``` ALTER DATABASE [ database_name ] UPDATE MASTERKEY ``` ## 参数说明 * **database\_name**: 待修改的数据库名,不指定则取当前MOUNT状态的数据库。 * **MOUNT**: 数据库加载状态,但不打开数据库。 * **OPEN**: 数据库正常启动状态,具有如下子状态: * **RESETLOGS**: RESTID在原有基础上增加1。 * **READ ONLY**: 只读模式,此时数据库只支持查询。 * **READ WRITE**: 读写模式,启动到OPEN后的默认状态。 * **RESTRICTED**: 约束模式,该模式用来支持数据库维护,紧急修复等DFX能力。该模式只支持SYS用户启动并执行操作,进入该模式后,仅支持一个session连接。 * **UPGRADE**: 升级模式,只加载核心系统表。该模式只支持SYS用户启动并执行操作,进入该模式后,仅支持一个session连接。 * **FORCE IGNORE LOGS**: 强制忽略日志文件。 * **REPLAY UNTIL lfn**: 备机实例以该模式启动,重演到lfn点后停止重演。 * **IGNORE SYSTIME**: 忽略系统时间跳变对数据库产生的影响。 * **ARCHIVELOG**: 设置Redo日志归档。 * **NOARCHIVELOG**: 设置Redo日志不归档。 * **ADD LOGFILE ( { 'file\_name' SIZE integer \[ B | K | M | G | T | P | E ] \[ BLOCKSIZE { 512 | 4096 } ] } \[,...] )**: 在主机的Redo Log增加一个或多个Redo日志文件。 * **file\_name**: 文件名。 * **SIZE integer \[ B | K | M | G | T | P | E ]**: 指定文件大小。默认单位为字节。B表示单位为字节,K表示单位为KB,M表示单位为MB,G表示单位为GB,T表示单位为TB,P表示单位为PB,E表示单位为EB。 * **BLOCKSIZE { 512 | 4096 }**: 指定文件块大小。单位为字节。取值范围为512或4096,默认为512字节。 * **DROP LOGFILE ( 'file\_name' )**: 删除Redo日志文件,一次只能删除一个。 * **ARCHIVE LOGFILE ( { 'file\_name' } \[,...] )**: 归档在线日志,可以归档一个或多个。 * **DELETE ARCHIVELOG { ALL | UNTIL TIME 'date\_string' } \[ FORCE ]**: 删除归档日志文件,只能在归档模式下执行。 * **ALL**: 删除所有满足以下三个条件的归档日志: * 归档日志不被本机recovery覆盖,即小于本机rcy\_point点; * 归档日志已备份(通过FORCE配置项可忽略备份); * 归档日志号小于备机上已归档的连续日志号。 * **UNTIL TIME 'date\_string'**: 删除date之前产生的满足条件的归档日志。时间格式为YYYY-MM-DD hh:mm:ss。 * **FORCE**: 删除时忽略归档日志是否已经备份。 * **SET STANDBY DATABASE TO MAXIMIZE { PROTECTION | AVAILABILITY | PERFORMANCE }**: 切换数据库备机的数据保护模式。 * **PROTECTION**: 最大保护模式。提供最高级别的数据保护能力。要求数据库备机收到Redo日志后,主机的事务才能提交。 * **AVAILABILITY**: 最大可用模式。当备机无法写入Redo日志时,临时降低为PERFORMANCE,直到备机恢复可以成功写入日志。 * **PERFORMANCE**: 最大性能模式。保证数据库主机的最高可用性。主机不受备机影响,但如果主机提交的事务相关的恢复数据没有发送到备机,这些事务数据将丢失,不能保证数据无损失。 * **DATAFILE { 'file\_name' | file\_number } \[,...] { AUTOEXTEND { OFF | ON \[ NEXT integer \[ K | M | G ] | MAXSIZE { integer \[ K | M | G ] | UNLIMITED } ] } | RESIZE integer \[ K | M | G ] }**: 修改一个或多个数据文件的属性。数据文件可以通过文件名或者文件编号指定。 * **file\_name**: 文件名。支持绝对路径和单纯文件名两种方式。如果是后者,则数据库会根据指定的数据库实例路径的data目录拼接出一个全路径。 * **file\_number**: 文件编号。数据库中的数据文件编号。 * **AUTOEXTEND**: 设置自动扩展属性,以及开启时每次自动扩展的尺寸或自动扩展的上限。 * **OFF**: 关闭自动扩展属性。 * **ON**: 开启自动扩展属性。 * **NEXT**: 指定自动扩展的大小。默认值为16MB。 * **MAXSIZE**: 指定数据文件自动扩展的上限,不能超过当前文件大小。 * **UNLIMITED**: 自动扩展,无上限。 * **RESIZE**: 修改数据文件的大小。 * **CLEAR LOGFILE file\_id**: 清理和重建日志文件id为file\_id的日志文件内容,用于日志文件头部损坏导致数据库无法启动时,若此日志文件可以清理,则可以使用该命令清理损坏内容,重建日志文件,使数据库可以启动。 * **SWITCHOVER \[TIMEOUT tm\_s]**: 主备机切换。超时时间tm\_s为整型,单位是秒,取值范围为0,\[30, 1800],默认值为0。 * **FAILOVER \[ FORCE ]**: 当主备关系异常时,数据库备机升为主机。指定FORCE,则无论主备关系是否异常,都可以执行。 * **CANCEL UPGRADE**: 取消UPGRADE模式。数据库升级完成后,需要取消UPGRADE模式。 * **CONVERT TO { READONLY | READWRITE | \[ CASCADED ] PHYSICAL STANDBY \[ MOUNT ] }**: 修改数据库角色或状态。 * **READONLY**: 只读模式,此时数据库只支持查询。 * **READWRITE**: 启动到OPEN后的默认状态,支持读写。 * **\[ CASCADED ] PHYSICAL STANDBY \[ MOUNT ]**: 修改数据库角色为备机或者级联备机。如果指定MOUNT,则只修改角色,不修改数据库状态;否则数据库会自动转换为OPEN状态下的READ ONLY状态。 * **DELETE BACKUPSET 'tag' \[ FORCE ]**: 删除备份集物理文件及SYS\_BACKUP\_SETS中备份集记录。如果备份集在磁盘上不存在或者备份集介质不是磁盘,则报错。如果是增量备份集,系统表中有其他备份集依赖该备份集则报错,需要先删除依赖它的备份集。 * **FORCE**: 强制删除SYS\_BACKUP\_SETS中备份记录。 * **REBUILD TABLESPACE tablespace\_name**: 重建表空间。 * **ENABLE\_LOGIC\_REPLICATION { ON | OFF }**: 打开或关闭全局级逻辑复制开关。 * **UPDATE MASTERKEY**: 更新及同步密钥,适配表空间透明加密功能。 ## 示例 ``` -- 修改数据库状态为MOUNT SQL> ALTER DATABASE MOUNT; -- 在数据库MOUNT状态下,修改为OPEN状态。 SQL> ALTER DATABASE OPEN; -- 在数据库MOUNT状态下,重置数据库日志序列号为1。 SQL> ALTER DATABASE RESETLOGS; -- 在数据库MOUNT状态下,修改数据库状态为只读模式。 SQL> ALTER DATABASE OPEN READ ONLY; -- 增加名称为test1,大小为1G,BLOCKSIZE为4096字节的Redo日志文件 SQL> ALTER DATABASE ADD LOGFILE ('test1' SIZE 1G BLOCKSIZE 4096); -- 删除名称为test1的Redo日志文件 SQL> ALTER DATABASE DROP LOGFILE ('test1'); -- 删除2025/11/15 11:00:00前产生的满足条件的归档日志 SQL> ALTER DATABASE DELETE ARCHIVELOG UNTIL TIME '2025/11/15 11:00:00'; -- 关闭文件编号为1的数据文件自动扩展属性。 SQL> ALTER DATABASE DATAFILE 1 AUTOEXTEND OFF; -- 修改文件编号为1的数据文件自动扩展的大小为20M。 SQL> ALTER DATABASE DATAFILE 1 AUTOEXTEND ON NEXT 20M; -- 修改文件编号为1的数据文件自动扩展上限为10G。 SQL> ALTER DATABASE DATAFILE 1 AUTOEXTEND ON MAXSIZE 10G; -- 修改文件编号为1的数据文件自动扩展的大小无上限。 SQL> ALTER DATABASE DATAFILE 1 AUTOEXTEND ON MAXSIZE UNLIMITED; -- 在数据库MOUNT状态下,修改数据库角色为备机。 SQL> ALTER DATABASE CONVERT TO PHYSICAL STANDBY; -- 修改数据库状态为READWRITE。 SQL> ALTER DATABASE CONVERT TO READWRITE; -- 修改USER1数据文件的大小为128M。 SQL> ALTER DATABASE DATAFILE 'USER1' RESIZE 128M; -- 在数据库MOUNT状态下,重建文件id为0的日志文件头部。 SQL> ALTER DATABASE CLEAR LOGFILE 0; -- 删除tag为incr_bak的备份集文件及备份集记录。 SQL> ALTER DATABASE DELETE BACKUPSET 'incr_bak'; -- 打开全局级逻辑复制开关。 SQL> ALTER DATABASE ENABLE_LOGIC_REPLICATION ON; ``` --- --- url: /zh/docs/latest/sql_reference/alter_database.md --- # ALTER DATABASE ## 功能描述 修改数据库的属性,包括它的名称、所有者、连接数限制、对象隔离属性等。 ## 注意事项 * 只有数据库的所有者或者被授予了数据库ALTER权限的用户才能执行ALTER DATABASE命令,系统管理员默认拥有此权限。针对所要修改属性的不同,还有以下权限约束: * 修改数据库名称,必须拥有CREATEDB权限。 * 修改数据库所有者,当前用户必须是该database的所有者或者系统管理员,必须拥有CREATEDB权限,且该用户是新所有者角色的成员。 * 修改数据库默认表空间,必须拥有新表空间的CREATE权限。这个语句会从物理上将一个数据库原来缺省表空间上的表和索引移至新的表空间。注意不在缺省表空间的表和索引不受此影响。 * 不能重命名当前使用的数据库,如果需要重新命名,须连接至其他数据库上。 ## 语法格式 * 修改数据库的最大连接数。 ``` ALTER DATABASE database_name [ [ WITH ] CONNECTION LIMIT connlimit ]; ``` * 修改数据库名称。 ``` ALTER DATABASE database_name RENAME TO new_name; ``` * 修改数据库所属者。 ``` ALTER DATABASE database_name OWNER TO new_owner; ``` * 修改数据库默认表空间。 ``` ALTER DATABASE database_name SET TABLESPACE new_tablespace; ``` > \[!NOTE]说明 > \> > \> 如果该数据库中的某些表或对象已经创建在new\_tablespace下,则无法将该数据库的默认表空间修改为new\_tablespace,执行会报错。 * 修改数据库指定会话参数值。 ``` ALTER DATABASE database_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ``` * 数据库配置参数重置。 ``` ALTER DATABASE database_name RESET { configuration_parameter | ALL }; ``` * 修改数据库对象隔离属性。 ``` ALTER DATABASE database_name [ WITH ] { ENABLE | DISABLE } PRIVATE OBJECT; ``` > \[!NOTE]说明 > > * 修改数据库的对象隔离属性时须连接至该数据库,否则无法更改。 > > * 新创建的数据库,对象隔离属性默认是关闭的。当开启数据库对象隔离属性后,普通用户只能查看有权访问的对象(表、函数、视图、字段等)。对象隔离特性对管理员用户不生效,当开启对象隔离特性后,管理员也可以查看到全量的数据库对象。 ## 参数说明 * **database\_name** 需要修改属性的数据库名称。 取值范围:字符串,要符合标识符的命名规范。 * **connlimit** 数据库可以接收的最大并发连接数(管理员用户连接除外)。 取值范围:整数,建议填写1~50的整数。-1(缺省)表示没有限制。 * **new\_name** 数据库的新名称。 取值范围:字符串,要符合标识符的命名规范。 * **new\_owner** 数据库的新所有者。 取值范围:字符串,有效的用户名。 * **new\_tablespace** 数据库新的默认表空间,该表空间为数据库中已经存在的表空间。默认的表空间为pg\_default。 取值范围:字符串,有效的表空间名。 * **configuration\_parameter** **value** 把指定的数据库会话参数值设置为给定的值。如果value是DEFAULT或者RESET,则在新的会话中使用系统的缺省设置。OFF关闭设置。 取值范围:字符串, * DEFAULT * OFF * RESET * **FROM CURRENT** 根据当前会话连接的数据库设置该参数的值。 * **RESET configuration\_parameter** 重置指定的数据库会话参数值。 * **RESET ALL** 重置全部的数据库会话参数值。 > \[!NOTE]说明 > > * 修改数据库默认表空间,会将旧表空间中的所有表和索引转移到新表空间中,该操作不会影响其他非默认表空间中的表和索引。 > > * 修改的数据库会话参数值,将在下一次会话中生效。 ## 示例 请参考CREATE DATABASE的[示例](create_database.md#zh-cn_topic_0283137050_zh-cn_topic_0237122099_zh-cn_topic_0059778277_s6be7b8abbb4b4aceb9dae686434d672c)。 ## 相关链接 [CREATE DATABASE](create_database.md),[DROP DATABASE](drop_database.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_default_privileges.md --- # ALTER DEFAULT PRIVILEGES ## Function **ALTER DEFAULT PRIVILEGES** allows you to set the permissions that will be applied to objects created in the future. (It does not affect permissions granted to existing objects.) ## Precautions Only tables (including views), sequences, functions, and types can be changed. ## Syntax ``` ALTER DEFAULT PRIVILEGES [ FOR { ROLE | USER } target_role [, ...] ] [ IN SCHEMA schema_name [, ...] ] abbreviated_grant_or_revoke; ``` * **abbreviated\_grant\_or\_revoke** grants or revokes permissions on some objects. ``` grant_on_tables_clause | grant_on_sequences_clause | grant_on_functions_clause | grant_on_types_clause | grant_on_client_master_keys_clause | grant_on_column_encryption_keys_clause | revoke_on_tables_clause | revoke_on_sequences_clause | revoke_on_functions_clause | revoke_on_types_clause | revoke_on_client_master_keys_clause | revoke_on_column_encryption_keys_clause ``` * **grant\_on\_tables\_clause** grants permissions on tables. ``` GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **grant\_on\_sequences\_clause** grants permissions on sequences. ``` GRANT { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **grant\_on\_functions\_clause** grants permissions on functions. ``` GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **grant\_on\_types\_clause** grants permissions on types. ``` GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **grant\_on\_client\_master\_keys\_clause** grants permissions on CMKs. ``` GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` > \[!NOTE]NOTE > In the Lite scenario, openGauss provides this syntax, but encrypted database-related functions are unavailable. * **grant\_on\_column\_encryption\_keys\_clause** grants permissions on CEKs. ``` GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` > \[!NOTE]NOTE > In the Lite scenario, openGauss provides this syntax, but encrypted database-related functions are unavailable. * **revoke\_on\_tables\_clause** revokes permissions on tables. ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * **revoke\_on\_sequences\_clause** revokes permissions on sequences. ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * **revoke\_on\_functions\_clause** revokes permissions on functions. ``` REVOKE [ GRANT OPTION FOR ] { {EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * **revoke\_on\_types\_clause** revokes permissions on types. ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * **revoke\_on\_client\_master\_keys\_clause** revokes permissions on CMKs. ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` > \[!NOTE]NOTE > In the Lite scenario, openGauss provides this syntax, but encrypted database-related functions are unavailable. * **revoke\_on\_column\_encryption\_keys\_clause** revokes permissions on CEKs. ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` > \[!NOTE]NOTE > In the Lite scenario, openGauss provides this syntax, but encrypted database-related functions are unavailable. ## Parameter Description * **target\_role** Specifies the name of an existing role. If **FOR ROLE/USER** is omitted, the current role is assumed. Value range: an existing role name * **schema\_name** Specifies the name of an existing schema. **target\_role** must have the **CREATE** permission for **schema\_name**. Value range: an existing schema name * **role\_name** Specifies the name of an existing role to grant or revoke permissions for. Value range: an existing role name > \[!TIP]NOTICE > To drop a role for which the default permissions have been granted, reverse the changes in its default permissions or use **DROP OWNED BY** to get rid of the default permission entry for the role. ## Examples ``` -- Grant the SELECT permission on all the tables (and views) in tpcds to every user. openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT SELECT ON TABLES TO PUBLIC; -- Create a common user jack. openGauss=# CREATE USER jack PASSWORD 'xxxxxxxxx'; -- Grant the INSERT permission on all the tables in tpcds to the user jack. openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT INSERT ON TABLES TO jack; -- Revoke the preceding permissions. openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE SELECT ON TABLES FROM PUBLIC; openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE INSERT ON TABLES FROM jack; -- Delete user jack. openGauss=# DROP USER jack; ``` ## Helpful Links [GRANT](grant.md) and [REVOKE](revoke.md) --- --- url: /en/docs/latest/sql_reference/alter_default_privileges.md --- # ALTER DEFAULT PRIVILEGES ## Function **ALTER DEFAULT PRIVILEGES** allows you to set the permissions that will be applied to objects created in the future. (It does not affect permissions granted to existing objects.) ## Precautions Currently, you can change only the permissions for tables (including views), sequences, functions, types, CMKs of encrypted databases, and CEKs. ## Syntax ``` ALTER DEFAULT PRIVILEGES [ FOR { ROLE | USER } target_role [, ...] ] [ IN SCHEMA schema_name [, ...] ] abbreviated_grant_or_revoke; ``` * **abbreviated\_grant\_or\_revoke** grants or revokes permissions on some objects. ``` grant_on_tables_clause | grant_on_sequences_clause | grant_on_functions_clause | grant_on_types_clause | grant_on_client_master_keys_clause | grant_on_column_encryption_keys_clause | revoke_on_tables_clause | revoke_on_sequences_clause | revoke_on_functions_clause | revoke_on_types_clause | revoke_on_client_master_keys_clause | revoke_on_column_encryption_keys_clause ``` * **grant\_on\_tables\_clause** grants permissions on tables. ``` GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **grant\_on\_sequences\_clause** grants permissions on sequences. ``` GRANT { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **grant\_on\_functions\_clause** grants permissions on functions. ``` GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **grant\_on\_types\_clause** grants permissions on types. ``` GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **grant\_on\_client\_master\_keys\_clause** grants permissions on CMKs. ``` GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **grant\_on\_column\_encryption\_keys\_clause** grants permissions on CEKs. ``` GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * **revoke\_on\_tables\_clause** revokes permissions on tables. ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * **revoke\_on\_sequences\_clause** revokes permissions on sequences. ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * **revoke\_on\_functions\_clause** revokes permissions on functions. ``` REVOKE [ GRANT OPTION FOR ] { {EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * **revoke\_on\_types\_clause** revokes permissions on types. ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * **revoke\_on\_client\_master\_keys\_clause** revokes permissions on CMKs. ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * **revoke\_on\_column\_encryption\_keys\_clause** revokes permissions on CEKs. ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` ## Parameter Description * **target\_role** Specifies the name of an existing role. If **FOR ROLE/USER** is omitted, the current role is assumed. Value range: an existing role name * **schema\_name** Specifies the name of an existing schema. **target\_role** must have the **CREATE** permission for **schema\_name**. Value range: an existing schema name * **role\_name** Specifies the name of an existing role to grant or revoke permissions for. Value range: an existing role name > \[!TIP]NOTICE > To drop a role for which the default permissions have been granted, reverse the changes in its default permissions or use **DROP OWNED BY** to get rid of the default permission entry for the role. ## Examples ``` -- Grant the SELECT permission on all the tables (and views) in tpcds to every user. openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT SELECT ON TABLES TO PUBLIC; -- Create a common user jack. openGauss=# CREATE USER jack PASSWORD 'xxxxxxxxx'; -- Grant the INSERT permission on all the tables in tpcds to the user jack. openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT INSERT ON TABLES TO jack; -- Revoke the preceding permissions. openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE SELECT ON TABLES FROM PUBLIC; openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE INSERT ON TABLES FROM jack; -- Delete user jack. openGauss=# DROP USER jack; ``` ## Helpful Links [GRANT](grant.md) and [REVOKE](revoke.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_default_privileges.md --- # ALTER DEFAULT PRIVILEGES ## 功能描述 设置应用于将来创建的对象的权限(这不会影响分配到已有对象中的权限)。 ## 注意事项 目前只支持表(包括视图)、 序列、函数,类型更改。 ## 语法格式 ``` ALTER DEFAULT PRIVILEGES [ FOR { ROLE | USER } target_role [, ...] ] [ IN SCHEMA schema_name [, ...] ] abbreviated_grant_or_revoke; ``` * 其中abbreviated\_grant\_or\_revoke子句用于指定对哪些对象进行授权或回收权限。 ``` grant_on_tables_clause | grant_on_sequences_clause | grant_on_functions_clause | grant_on_types_clause | grant_on_client_master_keys_clause | grant_on_column_encryption_keys_clause | revoke_on_tables_clause | revoke_on_sequences_clause | revoke_on_functions_clause | revoke_on_types_clause | revoke_on_client_master_keys_clause | revoke_on_column_encryption_keys_clause ``` * 其中grant\_on\_tables\_clause子句用于对表授权。 ``` GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中grant\_on\_sequences\_clause子句用于对序列授权。 ``` GRANT { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中grant\_on\_functions\_clause子句用于对函数授权。 ``` GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中grant\_on\_types\_clause子句用于对类型授权。 ``` GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中grant\_on\_client\_master\_keys\_clause子句用于对客户端主密钥授权。 ``` GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` > \[!NOTE]说明 > 轻量版场景下,openGauss提供此语法,但密态数据库相关功能不可用。 * 其中grant\_on\_column\_encryption\_keys\_clause子句用于对列加密密钥授权。 ``` GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` > \[!NOTE]说明 > 轻量版场景下,openGauss提供此语法,但密态数据库相关功能不可用。 * 其中revoke\_on\_tables\_clause子句用于回收表对象的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * 其中revoke\_on\_sequences\_clause子句用于回收序列的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * 其中revoke\_on\_functions\_clause子句用于回收函数的权限。 ``` REVOKE [ GRANT OPTION FOR ] { {EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * 其中revoke\_on\_types\_clause子句用于回收类型的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * 其中revoke\_on\_client\_master\_keys\_clause子句用于回收客户端主密钥的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` > \[!NOTE]说明 > 轻量版场景下,openGauss提供此语法,但密态数据库相关功能不可用。 * 其中revoke\_on\_column\_encryption\_keys\_clause子句用于回收列加密密钥的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` > \[!NOTE]说明 > 轻量版场景下,openGauss提供此语法,但密态数据库相关功能不可用。 ## 参数说明 * **target\_role** 已有角色的名称。如果省略FOR ROLE/USER,则缺省值为当前角色/用户。 取值范围:已有角色的名称。 * **schema\_name** 现有模式的名称。 target\_role必须有schema\_name的CREATE权限。 取值范围:现有模式的名称。 * **role\_name** 被授予或者取消权限角色的名称。 取值范围:已存在的角色名称。 > \[!TIP]须知 > 如果想删除一个被赋予了默认权限的角色,有必要恢复改变的缺省权限或者使用DROP OWNED BY来为角色脱离缺省的权限记录。 ## 示例 ``` --将创建在模式tpcds里的所有表(和视图)的SELECT权限授予每一个用户。 openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT SELECT ON TABLES TO PUBLIC; --创建用户普通用户jack。 openGauss=# CREATE USER jack PASSWORD 'xxxxxxxxx'; --将tpcds下的所有表的插入权限授予用户jack。 openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT INSERT ON TABLES TO jack; --撤销上述权限。 openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE SELECT ON TABLES FROM PUBLIC; openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE INSERT ON TABLES FROM jack; --删除用户jack。 openGauss=# DROP USER jack; ``` ## 相关链接 [GRANT](grant.md),[REVOKE](revoke.md) --- --- url: /zh/docs/latest/sql_reference/alter_default_privileges.md --- # ALTER DEFAULT PRIVILEGES ## 功能描述 设置应用于将来创建的对象的权限(这不会影响分配到已有对象中的权限)。 ## 注意事项 目前只支持表(包括视图)、序列、函数、类型、密态数据库客户端主密钥和列加密密钥的权限更改。 ## 语法格式 ``` ALTER DEFAULT PRIVILEGES [ FOR { ROLE | USER } target_role [, ...] ] [ IN SCHEMA schema_name [, ...] ] abbreviated_grant_or_revoke; ``` * 其中abbreviated\_grant\_or\_revoke子句用于指定对哪些对象进行授权或回收权限。 ``` grant_on_tables_clause | grant_on_sequences_clause | grant_on_functions_clause | grant_on_types_clause | grant_on_client_master_keys_clause | grant_on_column_encryption_keys_clause | revoke_on_tables_clause | revoke_on_sequences_clause | revoke_on_functions_clause | revoke_on_types_clause | revoke_on_client_master_keys_clause | revoke_on_column_encryption_keys_clause ``` * 其中grant\_on\_tables\_clause子句用于对表授权。 ``` GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中grant\_on\_sequences\_clause子句用于对序列授权。 ``` GRANT { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中grant\_on\_functions\_clause子句用于对函数授权。 ``` GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中grant\_on\_types\_clause子句用于对类型授权。 ``` GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中grant\_on\_client\_master\_keys\_clause子句用于对客户端主密钥授权。 ``` GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中grant\_on\_column\_encryption\_keys\_clause子句用于对列加密密钥授权。 ``` GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] ``` * 其中revoke\_on\_tables\_clause子句用于回收表对象的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * 其中revoke\_on\_sequences\_clause子句用于回收序列的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * 其中revoke\_on\_functions\_clause子句用于回收函数的权限。 ``` REVOKE [ GRANT OPTION FOR ] { {EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * 其中revoke\_on\_types\_clause子句用于回收类型的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * 其中revoke\_on\_client\_master\_keys\_clause子句用于回收客户端主密钥的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` * 其中revoke\_on\_column\_encryption\_keys\_clause子句用于回收列加密密钥的权限。 ``` REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` ## 参数说明 * **target\_role** 已有角色的名称。如果省略FOR ROLE/USER,则缺省值为当前角色/用户。 取值范围:已有角色的名称。 * **schema\_name** 现有模式的名称。 target\_role必须有schema\_name的CREATE权限。 取值范围:现有模式的名称。 * **role\_name** 被授予或者取消权限角色的名称。 取值范围:已存在的角色名称。 > \[!TIP]须知 > 如果想删除一个被赋予了默认权限的角色,有必要恢复改变的缺省权限或者使用DROP OWNED BY来为角色脱离缺省的权限记录。 ## 示例 ``` --将创建在模式tpcds里的所有表(和视图)的SELECT权限授予每一个用户。 openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT SELECT ON TABLES TO PUBLIC; --创建用户普通用户jack。 openGauss=# CREATE USER jack PASSWORD 'xxxxxxxxx'; --将tpcds下的所有表的插入权限授予用户jack。 openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT INSERT ON TABLES TO jack; --撤销上述权限。 openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE SELECT ON TABLES FROM PUBLIC; openGauss=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE INSERT ON TABLES FROM jack; --删除用户jack。 openGauss=# DROP USER jack; ``` ## 相关链接 [GRANT](grant.md),[REVOKE](revoke.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_directory.md --- # ALTER DIRECTORY ## Function **ALTER DIRECTORY** modifies a directory. ## Precautions * Currently, only the directory owner can be changed. * When **enable\_access\_server\_directory** is set to **off**, only the initial user is allowed to change the directory owner. When **enable\_access\_server\_directory** is set to **on**, users with the **SYSADMIN** permission and the directory object owner can change the directory object owner, and the user who changes the owner is required to be a member of the new owner. ## Syntax ``` ALTER DIRECTORY directory_name OWNER TO new_owner; ``` ## Parameter Description **directory\_name** Specifies the name of a directory to be modified. The value must be an existing directory name. ## Examples ``` -- Create a directory. openGauss=# CREATE OR REPLACE DIRECTORY dir as '/tmp/'; -- Change the owner of the directory. openGauss=# ALTER DIRECTORY dir OWNER TO system; -- Delete a directory. openGauss=# DROP DIRECTORY dir; ``` ## Helpful Links [CREATE DIRECTORY](create_directory.md) and [DROP DIRECTORY](drop_directory.md) --- --- url: /en/docs/latest/sql_reference/alter_directory.md --- # ALTER DIRECTORY ## Function **ALTER DIRECTORY** modifies a directory. ## Precautions * Currently, only the directory owner can be changed. * When enable\_access\_server\_directory=off, only the initial user is allowed to modify the owner of the directory; when enable\_access\_server\_directory=on, users with SYSADMIN authority and the owner of the directory object can modify the directory, and the user is required to be a member of the new owner. ## Syntax ``` ALTER DIRECTORY directory_name OWNER TO new_owner; ``` ## Parameter Description **directory\_name** Specifies the name of a directory to be modified. The value must be an existing directory name. ## Examples ``` -- Create a directory. openGauss=# CREATE OR REPLACE DIRECTORY dir as '/tmp/'; -- Change the owner of the directory. openGauss=# ALTER DIRECTORY dir OWNER TO system; -- Delete a directory. openGauss=# DROP DIRECTORY dir; ``` ## Helpful Links [CREATE DIRECTORY](create_directory.md) and [DROP DIRECTORY](drop_directory.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_directory.md --- # ALTER DIRECTORY ## 功能描述 对directory属性进行修改。 ## 注意事项 * 目前只支持修改directory属主。 * 当enable\_access\_server\_directory=off时,只允许初始用户修改directory属主;当enable\_access\_server\_directory=on时,具有SYSADMIN权限的用户和directory对象的属主可以修改directory,且要求该用户是新属主的成员。 * 当修改directory属主时,若新属主与原属主相同,视为未修改属主。即使用户没有修改DIERECTORY的权限,也不会报错。 ## 语法格式 ``` ALTER DIRECTORY directory_name OWNER TO new_owner; ``` ## 参数描述 **directory\_name** 需要修改的目录名称,范围为已经存在的目录名称。 ## 示例 ``` --创建目录。 openGauss=# CREATE OR REPLACE DIRECTORY dir as '/tmp/'; --修改目录的owner。 openGauss=# ALTER DIRECTORY dir OWNER TO system; --删除目录。 openGauss=# DROP DIRECTORY dir; ``` ## 相关链接 [CREATE DIRECTORY](create_directory.md),[DROP DIRECTORY](drop_directory.md) --- --- url: /zh/docs/latest/sql_reference/alter_directory.md --- # ALTER DIRECTORY ## 功能描述 对directory属性进行修改。 ## 注意事项 * 目前只支持修改directory属主。 * 当enable\_access\_server\_directory=off时,只允许初始用户修改directory属主;当enable\_access\_server\_directory=on时,具有SYSADMIN权限的用户和directory对象的属主可以修改directory,且要求该用户是新属主的成员。 * 当修改directory属主时,若新属主与原属主相同,视为未修改属主。即使用户没有修改DIERECTORY的权限,也不会报错。 ## 语法格式 ``` ALTER DIRECTORY directory_name OWNER TO new_owner; ``` ## 参数描述 **directory\_name** 需要修改的目录名称,范围为已经存在的目录名称。 ## 示例 ``` --创建目录。 openGauss=# CREATE OR REPLACE DIRECTORY dir as '/tmp/'; --修改目录的owner。 openGauss=# ALTER DIRECTORY dir OWNER TO system; --删除目录。 openGauss=# DROP DIRECTORY dir; ``` ## 相关链接 [CREATE DIRECTORY](create_directory.md),[DROP DIRECTORY](drop_directory.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_event.md --- # ALTER EVENT ## Function **ALTER EVENT** modifies the parameters in the created scheduled event. ## Precautions * Operations related to scheduled events are supported only when **sql\_compatibility** is set to **'B'**. * Only the owner has the permission to modify the scheduled event to be modified. By default, the system administrator has the permission to modify all scheduled events. * You can execute SHOW EVENTS or view the log\_user column in the PG\_JOB table to obtain the event owner information. * Each time a scheduled event is modified, the owner of the modified event is changed to the current user. If a definer is specified during modification, the owner is changed to the specified definer. * The restrictions for the definer are the same as those described in [CREATE EVENT](create_event.md). > \[!TIP]NOTICE > > * If a system administrator modifies a scheduled event created by another user, the owner of the modified event is changed to the system administrator. The statements to be executed are executed by the system administrator. ## Syntax ``` ALTER [DEFINER = user] EVENT event_name [ON SCHEDULE schedule] [ON COMPLETION [NOT] PRESERVE] [RENAME TO new_event_name] [ENABLE | DISABLE | DISABLE ON SLAVE] [COMMENT 'string'] [DO event_body] ``` ## Parameter Description * definer Specifies the permission for the scheduled event statement to be executed during execution. By default, the permission of the user who creates the scheduled event is used. When definer is specified, the permission of the specified user is used. Only users with the sysadmin permission can specify the definer. * RENAME TO Specifies the updated scheduled event name. * ON COMPLETION \[NOT] PRESERVE Once a transaction is complete, the scheduled event is deleted from the system catalog immediately by default. You can overwrite the default behavior by setting **ON COMPLETION PRESERVE**. * ENABLE | DISABLE | DISABLE ON SLAVE The scheduled event is in the **ENABLE** state by default after it is created. That is, the statement to be executed is executed immediately at the specified time. You can use the keyword **DISABLE** to change the **ENABLE** state. The performance of **DISABLE ON SLAVE** is the same as that of **DISABLE**. * COMMENT 'string' You can add comments to the scheduled event. The comments can be viewed in the **GS\_JOB\_ATTRIBUTE** table. * event\_body Specifies the statement to be executed for a scheduled event. ## Examples ``` --Create a scheduled task. openGauss=# CREATE TABLE t_ev(num int); openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE AT sysdate + interval 5 second + interval 33 minute DISABLE DO insert into t_ev values(0); --Modify a scheduled task. openGauss=# ALTER EVENT event_e1 ENABLE DO select 1; openGauss=# ALTER EVENT event_e1 RENAME TO event_ee; ``` --- --- url: /en/docs/latest/sql_reference/alter_event.md --- # ALTER EVENT ## Function **ALTER EVENT** modifies the parameters in the created scheduled event. ## Precautions * Operations related to scheduled events are supported only when **sql\_compatibility** is set to **'B'**. * Only the owner has the permission to modify the scheduled event to be modified. By default, the system administrator has the permission to modify all scheduled events. * You can execute SHOW EVENTS or view the log\_user column in the PG\_JOB table to obtain the event owner information. * Each time a scheduled event is modified, the owner of the modified event is changed to the current user. If a definer is specified during modification, the owner is changed to the specified definer. * The restrictions for the definer are the same as those described in [CREATE EVENT](create_event.md). > \[!TIP]NOTICE > > * If a system administrator modifies a scheduled event created by another user, the owner of the modified event is changed to the system administrator. The statements to be executed are executed by the system administrator. ## Syntax ``` ALTER [DEFINER = user] EVENT event_name [ON SCHEDULE schedule] [ON COMPLETION [NOT] PRESERVE] [RENAME TO new_event_name] [ENABLE | DISABLE | DISABLE ON SLAVE] [COMMENT 'string'] [DO event_body] ``` ## Parameter Description * definer Specifies the permission for the scheduled event statement to be executed during execution. By default, the permission of the user who creates the scheduled event is used. When definer is specified, the permission of the specified user is used. Only users with the sysadmin permission can specify the definer. * RENAME TO Specifies the updated scheduled event name. * ON COMPLETION \[NOT] PRESERVE Once a transaction is complete, the scheduled event is deleted from the system catalog immediately by default. You can overwrite the default behavior by setting **ON COMPLETION PRESERVE**. * ENABLE | DISABLE | DISABLE ON SLAVE The scheduled event is in the **ENABLE** state by default after it is created. That is, the statement to be executed is executed immediately at the specified time. You can use the keyword **DISABLE** to change the **ENABLE** state. The performance of **DISABLE ON SLAVE** is the same as that of **DISABLE**. * COMMENT 'string' You can add comments to the scheduled event. The comments can be viewed in the **GS\_JOB\_ATTRIBUTE** table. * event\_body Specifies the statement to be executed for a scheduled event. ## Examples ``` --Create a scheduled task. openGauss=# CREATE TABLE t_ev(num int); openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE AT sysdate + interval 5 second + interval 33 minute DISABLE DO insert into t_ev values(0); --Modify a scheduled task. openGauss=# ALTER EVENT event_e1 ENABLE DO select 1; openGauss=# ALTER EVENT event_e1 RENAME TO event_ee; ``` --- --- url: /zh/docs/latest-lite/sql_reference/alter_event.md --- # ALTER EVENT ## 功能描述 修改已创建的定时任务中的参数。 ## 注意事项 * 定时任务相关操作只有sql\_compatibility = 'B'时支持。 * 只有定时任务的所有者有权修改待修改的定时任务,用户通过ALTER EVENT修改定时任务时需要拥有被指定schema的USAGE权限。系统管理员默认拥有修改所有定时任务的权限。 * 可以通过SHOW EVENTS或在PG\_JOB表中查看log\_user列来获得job的所有者信息 * 修改定时任务时每次修改成功后会更新被修改job的所有者为当前用户,若修改定时任务时指定了definer,则更新为被指定的definer。 * definer选项场景限制与[CREATE EVENT](create_event.md)章节中对definer限制场景一致。 > \[!TIP]须知 > > * 系统管理员修改其他用户创建的定时任务后,被修改定时任务的所有者将切换为系统管理员,待执行语句将使用系统管理员的权限执行。 ## 语法格式 ``` ALTER [DEFINER = user] EVENT event_name [ON SCHEDULE schedule] [ON COMPLETION [NOT] PRESERVE] [RENAME TO new_event_name] [ENABLE | DISABLE | DISABLE ON SLAVE] [COMMENT 'string'] [DO event_body] ``` ## 参数说明 * DEFINER 定时任务待执行语句在执行时使用的权限。默认情况下使用当前创建定时任务者的权限,当definer被指定时,使用被指定用户用户权限。 definer参数只有具有sysadmin权限的用户有权指定。 * ON SCHEDULE 定时任务执行时刻。其中schedule子句与[CREATE EVENT](create_event.md)中schedule一致。 * RENAME TO 更新定时任务名。 * ON COMPLETION \[NOT] PRESERVE 默认情况下,一旦事务处于完成状态,系统表中就会立刻删除该定时任务。用户可以通过设置ON COMPLETION PRESERVE来覆盖默认行为。 * ENABLE | DISABLE | DISABLE ON SLAVE 创建定时任务后,定时任务默认处于ENABLE状态,即到规定时间立即执行待执行语句。用户可以使用DISABLE关键字,改变定时任务的活动状态。DISABLE ON SLAVE表现与DISABLE一致。 * COMMENT 用户可以给定时任务添加注释,注释内容在GS\_JOB\_ATTRIBUTE表中查看。 * DO 定时任务待执行语句。 ## 示例 ``` --创建一个定时任务 openGauss=# CREATE TABLE t_ev(num int); openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE AT sysdate() + interval 5 second + interval 33 minute DISABLE DO insert into t_ev values(0); --修改定时任务 --修改定时任务状态和待执行语句 openGauss=# ALTER EVENT event_e1 ENABLE DO select 1; --修改定时任务名 openGauss=# ALTER EVENT event_e1 RENAME TO event_ee; ``` --- --- url: /zh/docs/latest/sql_reference/alter_event.md --- # ALTER EVENT ## 功能描述 修改已创建的定时任务中的参数。 ## 注意事项 * 定时任务相关操作只有sql\_compatibility = 'B'时支持。 * 只有定时任务的所有者有权修改待修改的定时任务,用户通过ALTER EVENT修改定时任务时需要拥有被指定schema的USAGE权限。系统管理员默认拥有修改所有定时任务的权限。 * 可以通过SHOW EVENTS或在PG\_JOB表中查看log\_user列来获得job的所有者信息 * 修改定时任务时每次修改成功后会更新被修改job的所有者为当前用户,若修改定时任务时指定了definer,则更新为被指定的definer。 * definer选项场景限制与[CREATE EVENT](create_event.md)章节中对definer限制场景一致。 > \[!TIP]须知 > > 系统管理员修改其他用户创建的定时任务后,被修改定时任务的所有者将切换为系统管理员,待执行语句将使用系统管理员的权限执行。 ## 语法格式 ``` ALTER [DEFINER = user] EVENT event_name [ON SCHEDULE schedule] [ON COMPLETION [NOT] PRESERVE] [RENAME TO new_event_name] [ENABLE | DISABLE | DISABLE ON SLAVE] [COMMENT 'string'] [DO event_body] ``` ## 参数说明 * DEFINER 定时任务待执行语句在执行时使用的权限。默认情况下使用当前创建定时任务者的权限,当definer被指定时,使用被指定用户用户权限。 definer参数只有具有sysadmin权限的用户有权指定。 * ON SCHEDULE 定时任务执行时刻。其中schedule子句与[CREATE EVENT](create_event.md)中schedule一致。 * RENAME TO 更新定时任务名。 * ON COMPLETION \[NOT] PRESERVE 默认情况下,一旦事务处于完成状态,系统表中就会立刻删除该定时任务。用户可以通过设置ON COMPLETION PRESERVE来覆盖默认行为。 * ENABLE | DISABLE | DISABLE ON SLAVE 创建定时任务后,定时任务默认处于ENABLE状态,即到规定时间立即执行待执行语句。用户可以使用DISABLE关键字,改变定时任务的活动状态。DISABLE ON SLAVE表现与DISABLE一致。 * COMMENT 用户可以给定时任务添加注释,注释内容在GS\_JOB\_ATTRIBUTE表中查看。 * DO 定时任务待执行语句。 ## 示例 ``` --创建一个定时任务 openGauss=# CREATE TABLE t_ev(num int); openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE AT sysdate() + interval 5 second + interval 33 minute DISABLE DO insert into t_ev values(0); --修改定时任务 --修改定时任务状态和待执行语句 openGauss=# ALTER EVENT event_e1 ENABLE DO select 1; --修改定时任务名 openGauss=# ALTER EVENT event_e1 RENAME TO event_ee; ``` --- --- url: /en/docs/latest-lite/sql_reference/alter_event_trigger.md --- # ALTER EVENT TRIGGER ## Function ALTER EVENT TRIGGER modifies an event trigger. ## Precautions Only the system administrator or super user has the permission to modify event triggers. ## Syntax ``` ALTER EVENT TRIGGER name DISABLE ALTER EVENT TRIGGER name ENABLE [ REPLICA | ALWAYS ] ALTER EVENT TRIGGER name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER EVENT TRIGGER name RENAME TO new_name ``` ## Parameter Description * **name** Specifies the name of the event trigger to be modified. Value range: all existing event triggers. * **new\_name** Specifies the new name after modification. Value range: strings that comply with the identifier naming convention. A value contains a maximum of 63 characters and cannot be the same as other event triggers on the same table. ## Examples For details, see [Examples](create_event_trigger.md#en-us_topic_0283137014_en-us_topic_0237122081_en-us_topic_0059777895_s7f55076bb56940b7920a431c0c344669) in [CREATE EVENT TRIGGER](create_event_trigger.md). ## Helpful Links [CREATE EVENT TRIGGER](create_event_trigger.md) and [DROP EVENT TRIGGER](drop_event_trigger.md) --- --- url: /en/docs/latest/sql_reference/alter_event_trigger.md --- # ALTER EVENT TRIGGER ## Function ALTER EVENT TRIGGER modifies an event trigger. ## Precautions Only the system administrator or super user has the permission to modify event triggers. ## Syntax ``` ALTER EVENT TRIGGER name DISABLE ALTER EVENT TRIGGER name ENABLE [ REPLICA | ALWAYS ] ALTER EVENT TRIGGER name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER EVENT TRIGGER name RENAME TO new_name ``` ## Parameter Description * **name** Specifies the name of the event trigger to be modified. Value range: all existing event triggers. * **new\_name** Specifies the new name after modification. Value range: strings that comply with the identifier naming convention. A value contains a maximum of 63 characters and cannot be the same as other event triggers on the same table. ## Examples For details, see [Examples](create_event_trigger.md#en-us_topic_0283137014_en-us_topic_0237122081_en-us_topic_0059777895_s7f55076bb56940b7920a431c0c344669) in [CREATE EVENT TRIGGER](create_event_trigger.md). ## Helpful Links [CREATE EVENT TRIGGER](create_event_trigger.md) and [DROP EVENT TRIGGER](drop_event_trigger.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_event_trigger.md --- # ALTER EVENT TRIGGER ## 功能描述 修改事件触发器。 ## 注意事项 只有系统管理员或者超级用户才有权限对事件触发器进行修改。 ## 语法格式 ``` ALTER EVENT TRIGGER name DISABLE ALTER EVENT TRIGGER name ENABLE [ REPLICA | ALWAYS ] ALTER EVENT TRIGGER name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER EVENT TRIGGER name RENAME TO new_name ``` ## 参数说明 * **name** 要修改的事件触发器名称。 取值范围:已存在的事件触发器。 * **new\_name** 修改后的新名称。 取值范围:符合标识符命名规范的字符串,最大长度不超过63个字符,且不能与所在表上其他事件触发器同名。 ## 示例 请参见[CREATE EVENT TRIGGER](create_event_trigger.md)的[示例](create_event_trigger.md#zh-cn_topic_0283137014_zh-cn_topic_0237122081_zh-cn_topic_0059777895_s7f55076bb56940b7920a431c0c344669)。 ## 相关链接 [CREATE EVENT TRIGGER](create_event_trigger.md),[DROP EVENT TRIGGER](drop_event_trigger.md) --- --- url: /zh/docs/latest/sql_reference/alter_event_trigger.md --- # ALTER EVENT TRIGGER ## 功能描述 修改事件触发器。 ## 注意事项 只有系统管理员或者超级用户才有权限对事件触发器进行修改。 ## 语法格式 ``` ALTER EVENT TRIGGER name DISABLE ALTER EVENT TRIGGER name ENABLE [ REPLICA | ALWAYS ] ALTER EVENT TRIGGER name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER EVENT TRIGGER name RENAME TO new_name ``` ## 参数说明 * **name** 要修改的事件触发器名称。 取值范围:已存在的事件触发器。 * **new\_name** 修改后的新名称。 取值范围:符合标识符命名规范的字符串,最大长度不超过63个字符,且不能与所在表上其他事件触发器同名。 ## 示例 请参见[CREATE EVENT TRIGGER](create_event_trigger.md)的[示例](create_event_trigger.md#zh-cn_topic_0283137014_zh-cn_topic_0237122081_zh-cn_topic_0059777895_s7f55076bb56940b7920a431c0c344669)。 ## 相关链接 [CREATE EVENT TRIGGER](create_event_trigger.md),[DROP EVENT TRIGGER](drop_event_trigger.md) --- --- url: /zh/docs/latest/sql_reference/alter_extension.md --- # ALTER Extension ## 功能描述 修改插件扩展。 ## 注意事项 ALTER Extension 修改一个已安装的扩展的定义。这里有几种方式: * UPDATE 这种方式更新这个扩展到一个新的版本。这个扩展必须满足一个适用的更新脚本(或者一系列脚本)这样就能修改当前安装版本到一个要求的版本。 * SET SCHEMA 这种方式移动扩展对象到另一个模式。这个扩展必须relocatable才能使命令成功。 * ADD member\_object 这种方式添加一个已存在对象到扩展。这主要在扩展更新脚本上有用。 这个对象接着会被视为扩展的成员;显而易见,该对象只能通过取消扩展来取消 。 * DROP member\_object 这个方式从扩展上移除一个成员对象。 主要在扩展更新脚本上有用。这个对象没有被取消,只是从扩展里分开了。 您必须拥有扩展来使用 ALTER Extension。 这个 ADD/DROP 方式要求添加/删除对象的所有权。 ## 语法格式 ``` ALTER Extension name UPDATE [ TO new_version ]; ALTER Extension name SET SCHEMA new_schema; ALTER Extension name ADD member_object; ALTER Extension name DROP member_object; where member_object is: AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | CONVERSION object_name | DOMAIN object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ [ argname ] [ argmode ] argtype [, ...] ] ) | MATERIALIZED VIEW object_name | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | SCHEMA object_name | SEQUENCE object_name | SERVER object_name | TABLE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name ``` ## 参数说明 * **name** 已安装扩展的名称。 * **new\_version** 扩展的新版本。可以通过被标识符和字面字符重写。如果不指定的扩展的新版本,ALTER Extension UPDATE会更新到扩展的控制文件中显示的默认版本。 * **new\_schema** 扩展的新模式。 * **object\_name** **agg\_name** **function\_name** **operator\_name** 从扩展里被被添加或移除的对象的名称。包含表、聚合 、域、外链表、函数、操作符、操作符类、操作符族、序列、文本搜索对象、类型和能被模式合格的视图的名称。 * **agg\_type** 在聚合函数操作上的一个输入数据类型,去引用一个零参数聚合函数,写 \* 代替这些输入数据类型列表。 * **source\_type** 强制转换的源数据类型的名称。 * **target\_type** 强制转换的目标数据类型的名称。 * **argmode** 这个函数参数的模型:IN、OUT、INOUT或者VARIADIC。如果省略的话,默认值为IN。ALTER Extension 不关心OUT参数 ,因为确认函数的一致性只需要输入参数,因此列出IN、INOUT和VARIADIC参数就足够了。 * **argname** 函数参数的名称。ALTER Extension不关心参数名称,确认函数的一致性只需要参数数据类型。 * **argtype** 函数参数的数据类型(可以有模式修饰)。 * **left\_type** **right\_type** 操作符参数的数据类型(可以有模式修饰),为前缀或后缀运算符的丢失参数写NONE 。 ## 示例 更新 hstore 扩展到版本 2.0: ``` ALTER Extension hstore UPDATE TO '2.0'; ``` 更新 hstore扩展的模式为utils: ``` ALTER Extension hstore SET SCHEMA utils; ``` 添加一个已存在的函数给 hstore 扩展: ``` ALTER Extension hstore ADD FUNCTION populate_record(anyelement, hstore); ``` --- --- url: /en/docs/latest-lite/sql_reference/alter_extension.md --- # ALTER EXTENSION ## Function ALTER EXTENSION modifies the plug-in extension. ## Precautions **ALTER EXTENSION** modifies the definition of an installed extension. Methods are as follows: * UPDATE The extension is updated to a new version. The extension must be applicable to an update script (or a series of scripts) so that the current installation version can be modified to a required version. * SET SCHEMA The extended object is moved to another schema. This extension must be relocatable to make the command successful. * ADD member\_object An existing object is added to the extension. This is mainly useful for extension update scripts. This object is then treated as a member of the extension. Obviously, the object can only be canceled by canceling the extension. * DROP member\_object A member object is removed from the extension. This method is useful in extension update scripts. The object is not canceled, but is simply separated from the extension. You must have an extension before using **ALTER EXTENSION**. You must have the permission on adding or deleting an object before using the ADD or DROP statement. ## Syntax ``` ALTER EXTENSION name UPDATE [ TO new_version ]; ALTER EXTENSION name SET SCHEMA new_schema; ALTER EXTENSION name ADD member_object; ALTER EXTENSION name DROP member_object; where member_object is: AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | CONVERSION object_name | DOMAIN object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ [ argname ] [ argmode ] argtype [, ...] ] ) | MATERIALIZED VIEW object_name | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | SCHEMA object_name | SEQUENCE object_name | SERVER object_name | TABLE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name ``` ## Parameter Description * **name** Name of an installed extension. * **new\_version** New version of the extension, which can be overridden by identifiers and string literals. If a new version of the extension is not specified, ALTER EXTENSION UPDATE updates to the default version shown in the extension's control file. * **new\_schema** New schema of the extension. * **object\_name** **agg\_name** **function\_name** **operator\_name** Names of objects that are added or removed from the extension, including names of tables, aggregations, domains, external linked lists, functions, operators, operator classes, operator families, sequences, text search objects, types, and views that can be schema-qualified. * **agg\_type** Input data type of the aggregate function. To reference a zero-parameter aggregate function, use **\*** to replace the input data type list. * **source\_type** Name of the source data type to be forcibly converted. * **target\_type** Name of the target data type to be forcibly converted. * **argmode** Model of the function parameter. The value can be **IN**, **OUT**, **INOUT**, or **VARIADIC**. The default value is **IN**. **ALTER EXTENSION** does not relate to the **OUT** parameter, because you only need to enter parameters to confirm the consistency of functions. Therefore, the **IN**, **INOUT**, and **VARIADIC** parameters are enough. * **argname** Name of a function parameter. ALTER EXTENSION does not relate to the parameter name. Only the parameter data type is required to confirm the consistency of the function. * **argtype** Data type (optionally schema-qualified) of a function parameter. * **left\_type** **right\_type** Data type (optionally schema-qualified) of an operator parameter. **NONE** is written for a missing parameter of a prefix or suffix operator. ## Examples Update the hstore extension to version 2.0. ``` ALTER EXTENSION hstore UPDATE TO '2.0'; ``` Run the following command to update the hstore extension mode to utils. ``` ALTER EXTENSION hstore SET SCHEMA utils; ``` Add an existing function for hstore extension. ``` ALTER EXTENSION hstore ADD FUNCTION populate_record(anyelement, hstore); ``` --- --- url: /en/docs/latest/sql_reference/alter_extension.md --- # ALTER EXTENSION ## Function ALTER EXTENSION modifies the plug-in extension. ## Precautions ALTER EXTENSION modifies the definition of an installed extension. Methods are as follows: * UPDATE The extension is updated to a new version. The extension must be applicable to an update script (or a series of scripts) so that the current installation version can be modified to a required version. * SET SCHEMA The extended object is moved to another schema. This extension must be relocatable to make the command successful. * ADD member\_object An existing object is added to the extension. This is mainly useful for extension update scripts. This object is then treated as a member of the extension. Obviously, the object can only be canceled by canceling the extension. * DROP member\_object A member object is removed from the extension. This method is useful in extension update scripts. The object is not canceled, but is simply separated from the extension. You must have an extension before using ALTER EXTENSION. You must have the permission on adding or deleting an object before using the ADD or DROP statement. ## Syntax ``` ALTER EXTENSION name UPDATE [ TO new_version ]; ALTER EXTENSION name SET SCHEMA new_schema; ALTER EXTENSION name ADD member_object; ALTER EXTENSION name DROP member_object; where member_object is: AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | CONVERSION object_name | DOMAIN object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ [ argname ] [ argmode ] argtype [, ...] ] ) | MATERIALIZED VIEW object_name | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | SCHEMA object_name | SEQUENCE object_name | SERVER object_name | TABLE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name ``` ## Parameter Description * **name** Name of an installed extension. * **new\_version** New version of the extension, which can be overridden by identifiers and string literals. If a new version of the extension is not specified, ALTER EXTENSION UPDATE updates to the default version shown in the extension's control file. * **new\_schema** New schema of the extension. * **object\_name** **agg\_name** **function\_name** **operator\_name** Names of objects that are added or removed from the extension, including names of tables, aggregations, domains, external linked lists, functions, operators, operator classes, operator families, sequences, text search objects, types, and views that can be schema-qualified. * **agg\_type** Input data type of the aggregate function. To reference a zero-parameter aggregate function, use **\*** to replace the input data type list. * **source\_type** Name of the source data type to be forcibly converted. * **target\_type** Name of the target data type to be forcibly converted. * **argmode** Model of the function parameter. The value can be **IN**, **OUT**, **INOUT**, or **VARIADIC**. The default value is **IN**. ALTER EXTENSION does not relate to the **OUT** parameter, because you only need to enter parameters to confirm the consistency of functions. Therefore, the **IN**, **INOUT**, and **VARIADIC** parameters are enough. * **argname** Name of a function parameter. ALTER EXTENSION does not relate to the parameter name. Only the parameter data type is required to confirm the consistency of the function. * **argtype** Data type (optionally schema-qualified) of a function parameter. * **left\_type** **right\_type** Data type (optionally schema-qualified) of an operator parameter. **NONE** is written for a missing parameter of a prefix or suffix operator. ## Example Update the hstore extension to version 2.0. ``` ALTER EXTENSION hstore UPDATE TO '2.0'; ``` Run the following command to update the hstore extension mode to utils. ``` ALTER EXTENSION hstore SET SCHEMA utils; ``` Add an existing function for hstore extension. ``` ALTER EXTENSION hstore ADD FUNCTION populate_record(anyelement, hstore); ``` --- --- url: /zh/docs/latest-lite/sql_reference/alter_extension.md --- # ALTER EXTENSION ## 功能描述 修改插件扩展。 ## 注意事项 ALTER EXTENSION 修改一个已安装的扩展的定义。这里有几种方式: * UPDATE 这种方式更新这个扩展到一个新的版本。这个扩展必须满足一个适用的更新脚本(或者一系列脚本) 这样就能修改当前安装版本到一个要求的版本。 * SET SCHEMA 这种方式移动扩展对象到另一个模式。这个扩展必须relocatable才能使命令成功。 * ADD member\_object 这种方式添加一个已存在对象到扩展。这主要在扩展更新脚本上有用。这个对象接着会被视为扩展的成员;显而易见,该对象只能通过取消扩展来取消 。 * DROP member\_object 这个方式从扩展上移除一个成员对象。主要在扩展更新脚本上有用。这个对象没有被取消,只是从扩展里分开了。 您必须拥有扩展来使用 ALTER EXTENSION。 这个 ADD/DROP 方式要求 添加/删除对象的所有权。 ## 语法格式 ``` ALTER EXTENSION name UPDATE [ TO new_version ]; ALTER EXTENSION name SET SCHEMA new_schema; ALTER EXTENSION name ADD member_object; ALTER EXTENSION name DROP member_object; where member_object is: AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | CONVERSION object_name | DOMAIN object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ [ argname ] [ argmode ] argtype [, ...] ] ) | MATERIALIZED VIEW object_name | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | SCHEMA object_name | SEQUENCE object_name | SERVER object_name | TABLE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name ``` ## 参数说明 * **name** 已安装扩展的名称。 * **new\_version** 扩展的新版本。可以通过被标识符和字面字符重写。如果不指定的扩展的新版本,ALTER EXTENSION UPDATE会更新到扩展的控制文件中显示的默认版本。 * **new\_schema** 扩展的新模式。 * **object\_name** **agg\_name** **function\_name** **operator\_name** 从扩展里被被添加或移除的对象的名称。包含表、聚合 、域、外链表、函数、操作符、操作符类、操作符族、序列、文本搜索对象、类型和能被模式合格的视图的名称。 * **agg\_type** 在聚合函数操作上的一个输入数据类型,去引用一个零参数聚合函数,写 \* 代替这些输入数据类型列表。 * **source\_type** 强制转换的源数据类型的名称。 * **target\_type** 强制转换的目标数据类型的名称。 * **argmode** 这个函数参数的模型:IN、OUT、INOUT或者 VARIADIC。如果省略的话,默认值为IN。ALTER EXTENSION 不关心OUT参数 ,因为确认函数的一致性只需要输入参数,因此列出 IN、INOUT和 VARIADIC参数就足够了。 * **argname** 函数参数的名称。ALTER EXTENSION不关心参数名称,确认函数的一致性只需要参数数据类型。 * **argtype** 函数参数的数据类型(可以有模式修饰)。 * **left\_type** **right\_type** 操作符参数的数据类型(可以有模式修饰),为前缀或后缀运算符的丢失参数写NONE 。 ## 示例 更新 hstore 扩展到版本 2.0: ``` ALTER EXTENSION hstore UPDATE TO '2.0'; ``` 更新 hstore扩展的模式为utils: ``` ALTER EXTENSION hstore SET SCHEMA utils; ``` 添加一个已存在的函数给 hstore 扩展: ``` ALTER EXTENSION hstore ADD FUNCTION populate_record(anyelement, hstore); ``` --- --- url: /en/docs/latest-lite/sql_reference/alter_foreign_data_wrapper.md --- # ALTER FOREIGN DATA WRAPPER ## Function Description Modifies the definition of a foreign data wrapper (FDW). ## Syntax ``` ALTER FOREIGN DATA WRAPPER name [ HANDLER handler_function | NO HANDLER ] [ VALIDATOR validator_function | NO VALIDATOR ] [ OPTIONS ( [ ADD | SET | DROP ] option ['value'] [,...] ) ] ``` ## Parameter Description * **name** Specifies the name of an FDW to be modified. * **HANDLER handler\_function** Specifies a new handler function for an FDW. * **NO HANDLER** Specifies that an FDW no longer has a handler function. > \[!TIP]NOTICE > \> > \> Foreign tables that use FDWs without handler functions cannot be accessed. * **VALIDATOR validator\_function** Specifies a new validator function for an FDW. > \[!TIP]NOTICE > \> > \> After a validator function is modified, options for an FDW, server, and user mapping may become invalid. Before using the FDW, the user should ensure that these options are correct. * **NO VALIDATOR** Specifies that the FDW no longer has a validator function. * **OPTIONS ( \[ ADD | SET | DROP ] option \['value'] \[,...] )** Specifies options to be modified (added, set, or dropped) for the FDW. If the operation is not explicitly specified, it is assumed that the operation is ADD. The option name must be unique. Use the FDW's validator function (if any) to validate the name and value. ## Examples ``` --Create an FDW named dbi. openGauss=# CREATE FOREIGN DATA WRAPPER dbi OPTIONS (debug 'true'); --Modify dbi: Add the foo option and delete the debug option. openGauss=# ALTER FOREIGN DATA WRAPPER dbi OPTIONS (ADD foo '1', DROP debug); --Change the dbi validator to myvalidator. openGauss=# ALTER FOREIGN DATA WRAPPER dbi VALIDATOR file_fdw_validator; ``` --- --- url: /en/docs/latest/sql_reference/alter_foreign_data_wrapper.md --- # ALTER FOREIGN DATA WRAPPER ## Function Description Modifies the definition of a foreign data wrapper (FDW). ## Syntax ``` ALTER FOREIGN DATA WRAPPER name [ HANDLER handler_function | NO HANDLER ] [ VALIDATOR validator_function | NO VALIDATOR ] [ OPTIONS ( [ ADD | SET | DROP ] option ['value'] [,...] ) ] ``` ## Parameter Description * **name** Specifies the name of an FDW to be modified. * **HANDLER handler\_function** Specifies a new handler function for an FDW. * **NO HANDLER** Specifies that an FDW no longer has a handler function. > \[!TIP]NOTICE > \> > \> Foreign tables that use FDWs without handler functions cannot be accessed. * **VALIDATOR validator\_function** Specifies a new validator function for an FDW. > \[!TIP]NOTICE > \> > \> After a validator function is modified, options for an FDW, server, and user mapping may become invalid. Before using the FDW, the user should ensure that these options are correct. * **NO VALIDATOR** Specifies that the FDW no longer has a validator function. * **OPTIONS ( \[ ADD | SET | DROP ] option \['value'] \[,...] )** Specifies options to be modified (added, set, or dropped) for the FDW. If the operation is not explicitly specified, it is assumed that the operation is ADD. The option name must be unique. Use the FDW's validator function (if any) to validate the name and value. ## Examples ``` --Create an FDW named dbi. openGauss=# CREATE FOREIGN DATA WRAPPER dbi OPTIONS (debug 'true'); --Modify dbi: Add the foo option and delete the debug option. openGauss=# ALTER FOREIGN DATA WRAPPER dbi OPTIONS (ADD foo '1', DROP debug); --Change the dbi validator to myvalidator. openGauss=# ALTER FOREIGN DATA WRAPPER dbi VALIDATOR file_fdw_validator; ``` --- --- url: /zh/docs/latest-lite/sql_reference/alter_foreign_data_wrapper.md --- # ALTER FOREIGN DATA WRAPPER ## 功能描述 修改外部数据包装器的定义。 ## 语法格式 ``` ALTER FOREIGN DATA WRAPPER name [ HANDLER handler_function | NO HANDLER ] [ VALIDATOR validator_function | NO VALIDATOR ] [ OPTIONS ( [ ADD | SET | DROP ] option ['value'] [,...] ) ] ``` ## 参数说明 * **name** 要修改的外部数据包装器名。 * **HANDLER handler\_function** 为外部数据包装器指定一个新的处理器函数。 * **NO HANDLER** 指定外部数据包装器不再具有处理器函数。 > \[!TIP]须知 > \> > \> 不能访问使用没有处理器的外部数据包装器的外部表。 * **VALIDATOR validator\_function** 为外部数据包装器指定一个新的验证器函数。 > \[!TIP]须知 > \> > \> 在修改验证器函数后,外部数据包装器,服务器和用户映射的选项可能会失效。在使用外部数据包装器之前,用户应确保这些选项是正确的。 * **NO VALIDATOR** 指定外部数据包装器不再具有验证器函数。 * **OPTIONS ( \[ ADD | SET | DROP ] option \['value'] \[,...] )** 外部数据包装器的修改选项。添加,设置和删除指定要执行的操作。如果未明确指定操作,则假定添加。选项名称不许是唯一的;如果有的话,使用外部数据包装器的验证器函数验证名称和值。 ## 示例 ``` --创建外部包装器dbi openGauss=# CREATE FOREIGN DATA WRAPPER dbi OPTIONS (debug 'true'); --修改外部包装器dbi,添加选项foo,删除选项debug openGauss=# ALTER FOREIGN DATA WRAPPER dbi OPTIONS (ADD foo '1', DROP debug); --修改外部数据包装器dbi的验证器为myvalidator openGauss=# ALTER FOREIGN DATA WRAPPER dbi VALIDATOR file_fdw_validator; ``` --- --- url: /zh/docs/latest/sql_reference/alter_foreign_data_wrapper.md --- # ALTER FOREIGN DATA WRAPPER ## 功能描述 修改外部数据包装器的定义。 ## 语法格式 ``` ALTER FOREIGN DATA WRAPPER name [ HANDLER handler_function | NO HANDLER ] [ VALIDATOR validator_function | NO VALIDATOR ] [ OPTIONS ( [ ADD | SET | DROP ] option ['value'] [,...] ) ] ``` ## 参数说明 * **name** 要修改的外部数据包装器名。 * **HANDLER handler\_function** 为外部数据包装器指定一个新的处理器函数。 * **NO HANDLER** 指定外部数据包装器不再具有处理器函数。 > \[!TIP]须知 > \> > \> 不能访问使用没有处理器的外部数据包装器的外部表。 * **VALIDATOR validator\_function** 为外部数据包装器指定一个新的验证器函数。 > \[!TIP]须知 > \> > \> 在修改验证器函数后,外部数据包装器,服务器和用户映射的选项可能会失效。在使用外部数据包装器之前,用户应确保这些选项是正确的。 * **NO VALIDATOR** 指定外部数据包装器不再具有验证器函数。 * **OPTIONS ( \[ ADD | SET | DROP ] option \['value'] \[,...] )** 外部数据包装器的修改选项。添加,设置和删除指定要执行的操作。如果未明确指定操作,则假定添加。选项名称不许是唯一的;如果有的话,使用外部数据包装器的验证器函数验证名称和值。 ## 示例 ``` --创建外部包装器dbi openGauss=# CREATE FOREIGN DATA WRAPPER dbi OPTIONS (debug 'true'); --修改外部包装器dbi,添加选项foo,删除选项debug openGauss=# ALTER FOREIGN DATA WRAPPER dbi OPTIONS (ADD foo '1', DROP debug); --修改外部数据包装器dbi的验证器为myvalidator openGauss=# ALTER FOREIGN DATA WRAPPER dbi VALIDATOR file_fdw_validator; ``` --- --- url: /en/docs/latest-lite/sql_reference/alter_foreign_table.md --- # ALTER FOREIGN TABLE ## Function **ALTER FOREIGN TABLE** modifies a foreign table. ## Syntax ``` ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']}[, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] table_name ALTER column_name OPTIONS; ``` ## Parameter Description * **table\_name** Specifies the name of an existing foreign table to be modified. Value range: an existing foreign table name. * **option** Specifies the option of a foreign table or foreign table column to be modified. **ADD**, **SET**, and **DROP** are operations to be performed. If no operation is set explicitly, the default value **ADD** is used. The option name must be unique (although table options and table column options can share the same name). The name and value of the option are also validated by a class library of a foreign data wrapper. * Options supported by **oracle\_fdw** are as follows: * **table** Name of a table on the Oracle server. The value must be the same as the table name recorded in the Oracle system catalog. Generally, the value consists of uppercase letters. * **schema** Schema (or owner) corresponding to the table. The value must be the same as the table name recorded in the Oracle system catalog. Generally, the value consists of uppercase letters. * Options supported by **mysql\_fdw** are as follows: * **dbname** Name of the MySQL database. * **table\_name** Name of a table in the MySQL database. * Options supported by **postgres\_fdw** are as follows: * **schema\_name** Schema name of a remote server. If this option is not specified, the schema name of the foreign table is used as the schema name of the remote server. * **table\_name** Table name of a remote server. If this option is not specified, the name of the foreign table is used as the table name of the remote server. * **column\_name** Column name of a table on a remote server. If this option is not specified, the column name of the foreign table is used as the column name of a table on a remote server. * Options supported by **file\_fdw** are as follows: * filename File to be read. This parameter is mandatory and must be an absolute path. * format File format of the remote server, which is the same as the **FORMAT** option in the **COPY** statement. The value can be **text**, **csv**, **binary**, or **fixed**. * header Specifies whether a specified file has a header, which is the same as the **HEADER** option of the **COPY** statement. * delimiter File delimiter, which is the same as the **DELIMITER** option of the **COPY** statement. * quote Quote character of a file, which is the same as the **QUOTE** option of the **COPY** statement. * escape Escape character of a file, which is the same as the **ESCAPE** option of the **COPY** statement. * null Null string of a file, which is the same as the **NULL** option of the **COPY** statement. * encoding Encoding of a file, which is the same as the **ENCODING** option of the **COPY** statement. * force\_not\_null This is a Boolean option. If it is true, the value of the declared field cannot be an empty string. This option is the same as the **FORCE\_NOT\_NULL** option of the **COPY** statement. > \[!NOTE]NOTE > For details about how to use **file\_fdw**, see [file\_fdw](../database_administration_guide/file_fdw.md). * **value** Specifies the new value of **option**. ## Helpful Links [CREATE FOREIGN TABLE](create_foreign_table.md) and [DROP FOREIGN TABLE](drop_foreign_table.md) --- --- url: /en/docs/latest/sql_reference/alter_foreign_table.md --- # ALTER FOREIGN TABLE ## Function **ALTER FOREIGN TABLE** modifies a foreign table. ## Syntax ``` ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']}[, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] table_name ALTER column_name OPTIONS; ``` ## Parameter Description * **table\_name** Specifies the name of an existing foreign table to be modified. Value range: an existing foreign table name. * **option** Specifies the option of a foreign table or foreign table column to be modified. **ADD**, **SET**, and **DROP** are operations to be performed. If no operation is set explicitly, the default value **ADD** is used. The option name must be unique (although table options and table column options can share the same name). The name and value of the option are also validated by a class library of a foreign data wrapper. * Options supported by **oracle\_fdw** are as follows: * **table** Name of a table on the Oracle server. The value must be the same as the table name recorded in the Oracle system catalog. Generally, the value consists of uppercase letters. * **schema** Schema (or owner) corresponding to the table. The value must be the same as the table name recorded in the Oracle system catalog. Generally, the value consists of uppercase letters. * Options supported by **mysql\_fdw** are as follows: * **dbname** Name of the MySQL database. * **table\_name** Name of a table in the MySQL database. * Options supported by **postgres\_fdw** are as follows: * **schema\_name** Schema name of a remote server. If this option is not specified, the schema name of the foreign table is used as the schema name of the remote server. * **table\_name** Table name of a remote server. If this option is not specified, the name of the foreign table is used as the table name of the remote server. * **column\_name** Column name of a table on a remote server. If this option is not specified, the column name of the foreign table is used as the column name of a table on a remote server. * Options supported by **file\_fdw** are as follows: * filename File to be read. This parameter is mandatory and must be an absolute path. * format File format of the remote server, which is the same as the **FORMAT** option in the **COPY** statement. The value can be **text**, **csv**, **binary**, or **fixed**. * header Specifies whether a specified file has a header, which is the same as the **HEADER** option of the **COPY** statement. * delimiter File delimiter, which is the same as the **DELIMITER** option of the **COPY** statement. * quote Quote character of a file, which is the same as the **QUOTE** option of the **COPY** statement. * escape Escape character of a file, which is the same as the **ESCAPE** option of the **COPY** statement. * null Null string of a file, which is the same as the **NULL** option of the **COPY** statement. * encoding Encoding of a file, which is the same as the **ENCODING** option of the **COPY** statement. * force\_not\_null This is a Boolean option. If it is true, the value of the declared field cannot be an empty string. This option is the same as the **FORCE\_NOT\_NULL** option of the **COPY** statement. > \[!NOTE]NOTE > For details about how to use **file\_fdw**, see [file\_fdw](../database_administration_guide/file_fdw.md). * **value** Specifies the new value of **option**. ## Helpful Links [CREATE FOREIGN TABLE](create_foreign_table.md) and [DROP FOREIGN TABLE](drop_foreign_table.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_foreign_table.md --- # ALTER FOREIGN TABLE ## 功能描述 对外表进行修改。 ## 语法格式 ``` ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']}[, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] table_name ALTER column_name OPTIONS; ``` ## 参数说明 * **table\_name** 需要修改的外表名称。 取值范围:已存在的外表名。 * **option** 改变外表或者外表字段的选项。ADD、SET和DROP指定执行的操作。如果没有显式设置,那么默认为ADD。选项的名字不允许重复(尽管表选项和表字段选项可以有相同的名字)。选项的名称和值也会通过外部数据封装器的类库进行校验。 * oracle\_fdw支持的options包括: * **table** oracle server侧的表名。需要同oracle系统表中记录的表名完全一致,通常是由大写字符组成。 * **schema** 表所对应的schema(或owner)。需要与oracle系统表中记录的表名完全一致,通常是由大写字符组成。 * mysql\_fdw支持的options包括: * **dbname** MySQL的database名称。 * **table\_name** MySQL侧的表名。 * postgres\_fdw支持的options包括: * **schema\_name** 远端server的schema名称。如果不指定的话,将使用外表自身的schema名称作为远端的schema名称。 * **table\_name** 远端server的表名。如果不指定的话,将使用外表自身的表名作为远端的表名。 * **column\_name** 远端server的表的列名。如果不指定的话,将使用外表自身的列名作为远端的的表的列名。 * file\_fdw支持的options包括: * filename 指定要读取的文件,必需的参数,且必须是一个绝对路径名。 * format 远端server的文件格式,支持text/csv/binary/fixed四种格式,和COPY语句的FORMAT选项相同。 * header 指定的文件是否有标题行,与COPY语句的HEADER选项相同。 * delimiter 指定文件的分隔符,与COPY的DELIMITER选项相同。 * quote 指定文件的引用字符,与COPY的QUOTE选项相同。 * escape 指定文件的转义字符,与COPY的ESCAPE选项相同。 * null 指定文件的null字符串,与COPY的NULL选项相同。 * encoding 指定文件的编码,与COPY的ENCODING选项相同。 * force\_not\_null 这是一个布尔选项。如果为真,则声明字段的值不应该匹配空字符串(也就是, 文件级别null选项)。与COPY的 FORCE\_NOT\_NULL选项里的字段相同。 > \[!NOTE]说明 > file\_fdw更多使用请参见[file\_fdw](../../../docs/zh/database_administration_guide/file_fdw.md)。 * **value** option的新值。 ## 相关链接 [CREATE FOREIGN TABLE](create_foreign_table.md),[DROP FOREIGN TABLE](drop_foreign_table.md) --- --- url: /zh/docs/latest/sql_reference/alter_foreign_table.md --- # ALTER FOREIGN TABLE ## 功能描述 对外表进行修改。 ## 语法格式 ``` ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']}[, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] table_name ALTER column_name OPTIONS; ``` ## 参数说明 * **table\_name** 需要修改的外表名称。 取值范围:已存在的外表名。 * **option** 改变外表或者外表字段的选项。ADD、SET和DROP指定执行的操作。如果没有显式设置,那么默认为ADD。选项的名字不允许重复(尽管表选项和表字段选项可以有相同的名字)。选项的名称和值也会通过外部数据封装器的类库进行校验。 * oracle\_fdw支持的options包括: * **table** oracle server侧的表名。需要同oracle系统表中记录的表名完全一致,通常是由大写字符组成。 * **schema** 表所对应的schema(或owner)。需要与oracle系统表中记录的表名完全一致,通常是由大写字符组成。 * mysql\_fdw支持的options包括: * **dbname** MySQL的database名称。 * **table\_name** MySQL侧的表名。 * postgres\_fdw支持的options包括: * **schema\_name** 远端server的schema名称。如果不指定的话,将使用外表自身的schema名称作为远端的schema名称。 * **table\_name** 远端server的表名。如果不指定的话,将使用外表自身的表名作为远端的表名。 * **column\_name** 远端server的表的列名。如果不指定的话,将使用外表自身的列名作为远端的的表的列名。 * file\_fdw支持的options包括: * filename 指定要读取的文件,必需的参数,且必须是一个绝对路径名。 * format 远端server的文件格式,支持text/csv/binary/fixed四种格式,和COPY语句的FORMAT选项相同。 * header 指定的文件是否有标题行,与COPY语句的HEADER选项相同。 * delimiter 指定文件的分隔符,与COPY的DELIMITER选项相同。 * quote 指定文件的引用字符,与COPY的QUOTE选项相同。 * escape 指定文件的转义字符,与COPY的ESCAPE选项相同。 * null 指定文件的null字符串,与COPY的NULL选项相同。 * encoding 指定文件的编码,与COPY的ENCODING选项相同。 * force\_not\_null 这是一个布尔选项。如果为真,则声明字段的值不应该匹配空字符串(也就是,文件级别null选项)。与COPY的 FORCE\_NOT\_NULL选项里的字段相同。 > \[!NOTE]说明 > file\_fdw更多使用请参见[file\_fdw](../database_administration_guide/file_fdw.md)。 * **value** option的新值。 ## 相关链接 [CREATE FOREIGN TABLE](create_foreign_table.md),[DROP FOREIGN TABLE](drop_foreign_table.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_function.md --- # ALTER FUNCTION ## Function **ALTER FUNCTION** modifies the attributes of a customized function. ## Precautions Only the function owner or a user granted with the ALTER permission can run the **ALTER FUNCTION** command. The system administrator has this permission by default. The following is permission constraints depending on attributes to be modified: * If a function involves operations on temporary tables, **ALTER FUNCTION** cannot be used. * To modify the owner or schema of a function, you must be a function owner or system administrator and a member of the new owner role. * Only the system administrator and initial user can change the schema of a function to **public**. * Only the initial user or the user who created the function can modify the function to be a definer's rights function. ## Syntax * Modify the additional parameters of the customized function. ``` ALTER FUNCTION function_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` The syntax of the **action** clause is as follows: ``` {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' ``` * Rename the customized function. ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * Change the owner of the customized function. ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * Modify the schema of the customized function. ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` ## Parameter Description * **function\_name** Specifies the name of the function to be modified. Value range: an existing function name * **argmode** Specifies whether a parameter is an input or output parameter. Value range: **IN**, **OUT**, **INOUT**, and **VARIADIC** * **argname** Parameter name. Value range: a string. It must comply with the identifier naming convention. * **argtype** Specifies the data type of a function parameter. * **CALLED ON NULL INPUT** Declares that some parameters of the function can be invoked in normal mode if the parameter values are null. Omitting this parameter is the same as specifying it. * **RETURNS NULL ON NULL INPUT** **STRICT** Specifies that the function always returns null whenever any of its parameters is null. If **STRICT** is specified, the function will not be executed when there are null parameters; instead a null result is assumed automatically. **RETURNS NULL ON NULL INPUT** and **STRICT** have the same functions. * **IMMUTABLE** Specifies that the function always returns the same result if the parameter values are the same. * **STABLE** Specifies that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same parameter value, but its result varies by SQL statements. * **VOLATILE** Specifies that the function value can change in a single table scan and no optimization is performed. * **LEAKPROOF** Specifies that the function has no side effect and the parameter contains only the return value. **LEAKPROOF** can be set only by the system administrator. * **EXTERNAL** (Optional) The purpose is to be compatible with SQL. This feature applies to all functions, not only external functions. * **SECURITY INVOKER** **AUTHID CURRENT\_USER** Specifies that the function will be executed with the permissions of the user who invokes it. Omitting this parameter is the same as specifying it. **SECURITY INVOKER** and **AUTHID CURRENT\_USER** have the same functions. * **SECURITY DEFINER** **AUTHID DEFINER** Specifies that the function will be executed with the permissions of the user who created it. **AUTHID DEFINER** and **SECURITY DEFINER** have the same function. * **COST execution\_cost** Estimates the execution cost of a function. The unit of **execution\_cost** is **cpu\_operator\_cost**. Value range: a positive integer * **ROWS result\_rows** Estimates the number of rows returned by the function. This is only allowed when the function is declared to return a set. Value range: a positive number. The default value is **1000**. * **configuration\_parameter** * **value** Sets a specified database session parameter to a specified value. If the value is **DEFAULT** or **RESET**, the default setting is used in the new session. **OFF** closes the setting. Value range: a string * DEFAULT * OFF * RESET Specifies the default value. * **from current** Uses the value of **configuration\_parameter** of the current session. * **new\_name** Specifies the new name of a function. To change the schema of a function, you must have the **CREATE** permission on the new schema. Value range: a string. It must comply with the identifier naming convention. * **new\_owner** Specifies the new owner of a function. To change the owner of a function, the new owner must have the **CREATE** permission on the schema to which the function belongs. Value range: an existing user role * **new\_schema** Specifies the new schema of a function. Value range: an existing schema * **COMMENT 'text'** Comment a function object. ## Examples See [Examples](create_function.md#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821) in **CREATE FUNCTION**. ## Helpful Links [CREATE FUNCTION](create_function.md) and [DROP FUNCTION](drop_function.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-alter-function.md --- # ALTER FUNCTION ## Function Description Modifies the attributes of a user-defined function. ## Precautions Compared with the original openGauss, Dolphin modifies the ALTER FUNCTION syntax as follows: 1. The modifiable LANGUAGE option is added. 2. The modifiable item { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } is added. 3. The modifiable item SQL SECURITY { DEFINER | INVOKER } is added. ## Syntax * Modify the additional parameter of the customized function. ``` ALTER FUNCTION function_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` The syntax of the **action** clause is as follows: ``` {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL|SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ``` ## Parameter Description * **LANGUAGE lang\_name** Name of the language used to implement the function. This parameter is compatible only with the syntax and has no actual effect. * **SQL SECURITY INVOKER** Specifies that the function is to be executed with the permissions of the user that calls it. This parameter can be omitted. The functions of SQL SECURITY INVOKER and SECURITY INVOKER and AUTHID CURRENT\_USER are the same. * **SQL SECURITY DEFINER** Specifies that the function is to be executed with the privileges of the user that created it. The functions of SQL SECURITY DEFINER and AUTHID DEFINER and SECURITY DEFINER are the same. * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** Syntax compatibility item. ## Example ``` --Specify NO SQL. openGauss=# ALTER FUNCTION f1 (s char(20)) NO SQL; --Specify CONTAINS SQL. openGauss=# ALTER FUNCTION f1 (s char(20)) CONTAINS SQL; --Specify LANGUAGE SQL. openGauss=# ALTER FUNCTION f1 (s char(20)) LANGUAGE SQL ; --Specify MODIFIES SQL DATA. openGauss=# ALTER FUNCTION f1 (s char(20)) MODIFIES SQL DATA; --Specify READS SQL DATA. openGauss=# ALTER FUNCTION f1 (s char(20)) READS SQL DATA; --Specify SECURITY INVOKER. openGauss=# ALTER FUNCTION f1 (s char(20)) SQL SECURITY INVOKER; --Specify SECURITY DEFINER. openGauss=# ALTER FUNCTION f1 (s char(20)) SQL SECURITY DEFINER; ``` ## Helpful Links [ALTER FUNCTION](https://docs.opengauss.org/en/docs/latest/sql_reference/alter_function.html) --- --- url: /en/docs/latest/sql_reference/alter_function.md --- # ALTER FUNCTION ## Function **ALTER FUNCTION** modifies the attributes of a customized function. ## Precautions Only the function owner or a user granted with the ALTER permission can run the **ALTER FUNCTION** command. The system administrator has this permission by default. The following is permission constraints depending on attributes to be modified: * If a function involves operations on temporary tables, **ALTER FUNCTION** cannot be used. * To modify the owner or schema of a function, you must be a function owner or system administrator and a member of the new owner role. * Only the system administrator and initial user can change the schema of a function to **public**. * Only the initial user or the user who created the function can modify the function to be a definer's rights function. ## Syntax * Modify the additional parameters of the customized function. ``` ALTER FUNCTION function_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` The syntax of the **action** clause is as follows: ``` {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' ``` * Rename the customized function. ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * Change the owner of the customized function. ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * Modify the schema of the customized function. ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` ## Parameter Description * **function\_name** Specifies the name of the function to be modified. Value range: an existing function name * **argmode** Specifies whether a parameter is an input or output parameter. Value range: **IN**, **OUT**, **INOUT**, and **VARIADIC** * **argname** Parameter name. Value range: a string. It must comply with the naming convention. * **argtype** Specifies the data type of a function parameter. * **CALLED ON NULL INPUT** Declares that some parameters of the function can be invoked in normal mode if the parameter values are null. Omitting this parameter is the same as specifying it. * **RETURNS NULL ON NULL INPUT** **STRICT** Specifies that the function always returns null whenever any of its parameters is null. If **STRICT** is specified, the function will not be executed when there are null parameters; instead a null result is assumed automatically. **RETURNS NULL ON NULL INPUT** and **STRICT** have the same functions. * **IMMUTABLE** Specifies that the function always returns the same result if the parameter values are the same. * **STABLE** Specifies that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same parameter value, but its result varies by SQL statements. * **VOLATILE** Specifies that the function value can change in a single table scan and no optimization is performed. * **LEAKPROOF** Specifies that the function has no side effect and the parameter contains only the return value. **LEAKPROOF** can be set only by the system administrator. * **EXTERNAL** (Optional) The purpose is to be compatible with SQL. This feature applies to all functions, not only external functions. * **SECURITY INVOKER** **AUTHID CURRENT\_USER** Specifies that the function will be executed with the permissions of the user who invokes it. Omitting this parameter is the same as specifying it. **SECURITY INVOKER** and **AUTHID CURRENT\_USER** have the same functions. * **SECURITY DEFINER** **AUTHID DEFINER** Specifies that the function will be executed with the permissions of the user who created it. **AUTHID DEFINER** and **SECURITY DEFINER** have the same function. * **COST execution\_cost** Estimates the execution cost of a function. The unit of **execution\_cost** is **cpu\_operator\_cost**. Value range: a positive integer * **ROWS result\_rows** Estimates the number of rows returned by the function. This is only allowed when the function is declared to return a set. Value range: a positive number. The default value is **1000**. * **configuration\_parameter** * **value** Sets a specified database session parameter to a specified value. If the value is **DEFAULT** or **RESET**, the default setting is used in the new session. **OFF** closes the setting. Value range: a string * DEFAULT * OFF * RESET Specifies the default value. * **from current** Uses the value of **configuration\_parameter** of the current session. * **new\_name** Specifies the new name of a function. To change the schema of a function, you must have the **CREATE** permission on the new schema. Value range: a string. It must comply with the naming convention. * **new\_owner** Specifies the new owner of a function. To change the owner of a function, the new owner must have the **CREATE** permission on the schema to which the function belongs. Value range: an existing user role * **new\_schema** Specifies the new schema of a function. Value range: an existing schema * **COMMENT 'text'** Comment a function object. ## Examples See [Examples](create_function.md#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821) in **CREATE FUNCTION**. ## Helpful Links [CREATE FUNCTION](create_function.md) and [DROP FUNCTION](drop_function.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-ALTER-FUNCTION.md --- # ALTER FUNCTION ## 功能描述 修改自定义函数的属性。 ## 注意事项 相比于原始的openGauss,dolphin对于ALTER FUNCTION语法的修改为: 1. 增加可修改 LANGUAGE 选项。 2. 增加可修改项 { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } 。 3. 增加可修改项 SQL SECURITY { DEFINER | INVOKER }。 ## 语法格式 * 修改自定义函数的附加参数。 ``` ALTER FUNCTION function_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为。 ``` {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL|SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ``` ## 参数说明 * **LANGUAGE lang\_name** 用以实现函数的语言的名称,仅语法兼容,实际修改不会生效。 * **SQL SECURITY INVOKER** 表明该函数将带着调用它的用户的权限执行。该参数可以省略。 SQL SECURITY INVOKER和SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SQL SECURITY DEFINER** 声明该函数将以创建它的用户的权限执行。 SQL SECURITY DEFINER和AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** 语法兼容项。 ## 示例 ``` --指定 NO SQL openGauss=# ALTER FUNCTION f1 (s char(20)) NO SQL; --指定 CONTAINS SQL openGauss=# ALTER FUNCTION f1 (s char(20)) CONTAINS SQL; --指定 LANGUAGE SQL openGauss=# ALTER FUNCTION f1 (s char(20)) LANGUAGE SQL ; --指定 MODIFIES SQL DATA openGauss=# ALTER FUNCTION f1 (s char(20)) MODIFIES SQL DATA; --指定 READS SQL DATA openGauss=# ALTER FUNCTION f1 (s char(20)) READS SQL DATA; --指定 SECURITY INVOKER openGauss=# ALTER FUNCTION f1 (s char(20)) SQL SECURITY INVOKER; --指定 SECURITY DEFINER openGauss=# ALTER FUNCTION f1 (s char(20)) SQL SECURITY DEFINER; ``` ## 相关链接 [ALTER FUNCTION](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_function.html) --- --- url: /zh/docs/latest-lite/sql_reference/alter_function.md --- # ALTER FUNCTION ## 功能描述 修改自定义函数的属性。 ## 注意事项 只有函数的所有者或者被授予了函数ALTER权限的用户才能执行ALTER FUNCTION命令,系统管理员默认拥有该权限。针对所要修改属性的不同,还有以下权限约束: * 如果函数中涉及对临时表相关的操作,则无法使用ALTER FUNCTION。 * 修改函数的所有者或修改函数的模式,当前用户必须是该函数的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 只有系统管理员和初始化用户可以将function的schema修改成public。 * 重命名函数时,不能与当前模式下已经存在的synonym产生命名冲突。 * 修改函数的模式时,不能与新模式下已经存在的synonym产生命名冲突。 * 仅有初始化用户或者创建该存储过程的用户可以修改存储过程为定义者权限的存储过程。 * 仅有初始化用户或者创建该函数的用户可以修改函数为定义者权限的函数。 * 打开三权分立时,即使是sysadmin权限用户,也需要校验用户的组权限。 * 重编译函数时,对于PACKAGE中定义的函数需要使用ALTER PACKAGE语句。 ## 语法格式 * 修改自定义函数的附加参数。 ``` ALTER FUNCTION function_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为。 ``` {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE | DETERMINISTIC} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' | {RESULT_CACHE | NOT RESULT_CACHE} ``` * 修改自定义函数的名称。 ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * 修改自定义函数的所属者。 ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * 修改自定义函数的模式。 ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` * 重编译函数。 ``` ALTER FUNCTION function_name COMPILE; ``` ## 参数说明 * **function\_name** 要修改的函数名称。 取值范围:已存在的函数名。 * **argmode** 标识该参数是输入、输出参数。 取值范围:IN/OUT/INOUT/VARIADIC。 * **argname** 参数名称。 取值范围:字符串,符合标识符命名规范。 * **argtype** 函数参数的类型。 * **CALLED ON NULL INPUT** 表明该函数的某些参数是NULL的时候可以按照正常的方式调用。缺省时与指定此参数的作用相同。 * **RETURNS NULL ON NULL INPUT** **STRICT** STRICT用于指定如果函数的某个参数是NULL,此函数总是返回NULL。如果声明了这个参数,则如果存在NULL参数时不会执行该函数;而只是自动假设一个NULL结果。 RETURNS NULL ON NULL INPUT和STRICT的功能相同。 * **IMMUTABLE** 表示该函数在给出同样的参数值时总是返回同样的结果。 * **STABLE** 表示该函数不能修改数据库,对相同参数值,在同一次表扫描里,该函数的返回值不变,但是返回值可能在不同SQL语句之间变化。 * **VOLATILE** 表示该函数值可以在一次表扫描内改变,不会做任何优化。 * **RESULT\_CACHE**|**NOT RESULT\_CACHE** 表示用户定义的函数是否支持函数结果缓存。 * **LEAKPROOF** 表示该函数没有副作用,指出参数只包括返回值。LEAKPROOF只能由系统管理员设置。 * **EXTERNAL** (可选)目的是和SQL兼容,这个特性适合于所有函数,而不仅是外部函数。 * **SECURITY INVOKER** **AUTHID CURRENT\_USER** 表明该函数将以调用它的用户的权限执行。缺省时与指定此参数的作用相同。 SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SECURITY DEFINER** **AUTHID DEFINER** 声明该函数将以创建它的用户的权限执行。 AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **COST execution\_cost** 用来估计函数的执行成本。 execution\_cost以cpu\_operator\_cost为单位。 取值范围:正数。 * **ROWS result\_rows** 估计函数返回的行数。用于函数返回的是一个集合。 取值范围:正数,默认值是1000行。 * **configuration\_parameter** * **value** 把指定的数据库会话参数值设置为给定的值。如果value是DEFAULT或者RESET,则在新的会话中使用系统的缺省设置。OFF关闭设置。 取值范围:字符串。 * DEFAULT * OFF * RESET 指定默认值。 * **from current** 取当前会话中的值设置为configuration\_parameter的值。 * **new\_name** 函数的新名称。要修改函数的所属模式,必须拥有新模式的CREATE权限。 取值范围:字符串,符合标识符命名规范。 * **new\_owner** 函数的新所有者。要修改函数的所有者,新所有者必须拥有该函数所属模式的CREATE权限。注意:仅有初始化用户才可将函数的owner设置为初始化用户。 取值范围:已存在的用户角色。 * **new\_schema** 函数的新模式。 取值范围:已存在的模式。 * **COMMENT 'text'** 修改函数对象的注释。 ## 示例 请参见CREATE FUNCTION的[示例](create_function.md#zh-cn_topic_0283136560_zh-cn_topic_0237122104_zh-cn_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821)。 ## 相关链接 [CREATE FUNCTION](create_function.md),[DROP FUNCTION](drop_function.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-ALTER-FUNCTION.md --- # ALTER FUNCTION ## 功能描述 修改自定义函数的属性。 ## 注意事项 相比于原始的openGauss,dolphin对于ALTER FUNCTION语法的修改为: 1. 增加可修改 LANGUAGE 选项。 2. 增加可修改项 { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } 。 3. 增加可修改项 SQL SECURITY { DEFINER | INVOKER }。 ## 语法格式 * 修改自定义函数的附加参数。 ``` ALTER FUNCTION function_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为。 ``` {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL|SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ``` ## 参数说明 * **LANGUAGE lang\_name** 用以实现函数的语言的名称,仅语法兼容,实际修改不会生效。 * **SQL SECURITY INVOKER** 表明该函数将带着调用它的用户的权限执行。该参数可以省略。 SQL SECURITY INVOKER和SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SQL SECURITY DEFINER** 声明该函数将以创建它的用户的权限执行。 SQL SECURITY DEFINER和AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** 语法兼容项。 ## 示例 ``` --指定 NO SQL openGauss=# ALTER FUNCTION f1 (s char(20)) NO SQL; --指定 CONTAINS SQL openGauss=# ALTER FUNCTION f1 (s char(20)) CONTAINS SQL; --指定 LANGUAGE SQL openGauss=# ALTER FUNCTION f1 (s char(20)) LANGUAGE SQL ; --指定 MODIFIES SQL DATA openGauss=# ALTER FUNCTION f1 (s char(20)) MODIFIES SQL DATA; --指定 READS SQL DATA openGauss=# ALTER FUNCTION f1 (s char(20)) READS SQL DATA; --指定 SECURITY INVOKER openGauss=# ALTER FUNCTION f1 (s char(20)) SQL SECURITY INVOKER; --指定 SECURITY DEFINER openGauss=# ALTER FUNCTION f1 (s char(20)) SQL SECURITY DEFINER; ``` ## 相关链接 [ALTER FUNCTION](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_function.html) --- --- url: /zh/docs/latest/sql_reference/alter_function.md --- # ALTER FUNCTION ## 功能描述 修改自定义函数的属性。 ## 注意事项 只有函数的所有者或者被授予了函数ALTER权限的用户才能执行ALTER FUNCTION命令,系统管理员默认拥有该权限。针对所要修改属性的不同,还有以下权限约束: * 如果函数中涉及对临时表相关的操作,则无法使用ALTER FUNCTION。 * 修改函数的所有者或修改函数的模式,当前用户必须是该函数的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 只有系统管理员和初始化用户可以将function的schema修改成public。 * 重命名函数时,不能与当前模式下已存在的synonym产生命名冲突。 * 修改函数的模式时,不能与新模式下已存在的synonym产生命名冲突。 * 仅有初始化用户或者创建该存储过程的用户可以修改存储过程为定义者权限的存储过程。 * 仅有初始化用户或者创建该函数的用户可以修改函数为定义者权限的函数。 * 打开三权分立时,即使是sysadmin权限用户,也需要校验用户的组权限。 * 重编译函数时,对于PACKAGE中定义的函数需要使用ALTER PACKAGE语句。 ## 语法格式 * 修改自定义函数的附加参数。 ``` ALTER FUNCTION function_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为。 ``` {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE | DETERMINISTIC} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' | {RESULT_CACHE | NOT RESULT_CACHE} ``` * 修改自定义函数的名称。 ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * 修改自定义函数的所属者。 ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * 修改自定义函数的模式。 ``` ALTER FUNCTION funname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` * 重编译函数。 ``` ALTER FUNCTION function_name COMPILE; ``` ## 参数说明 * **function\_name** 要修改的函数名称。 取值范围:已存在的函数名。 * **argmode** 标识该参数是输入、输出参数。 取值范围:IN/OUT/INOUT/VARIADIC。 * **argname** 参数名称。 取值范围:字符串,符合标识符命名规范。 * **argtype** 函数参数的类型。 * **CALLED ON NULL INPUT** 表明该函数的某些参数是NULL的时候可以按照正常的方式调用。缺省时与指定此参数的作用相同。 * **RETURNS NULL ON NULL INPUT** **STRICT** STRICT用于指定如果函数的某个参数是NULL,此函数总是返回NULL。如果声明了这个参数,则如果存在NULL参数时不会执行该函数;而只是自动假设一个NULL结果。 RETURNS NULL ON NULL INPUT和STRICT的功能相同。 * **IMMUTABLE** 表示该函数在给出同样的参数值时总是返回同样的结果。 * **STABLE** 表示该函数不能修改数据库,对相同参数值,在同一次表扫描里,该函数的返回值不变,但是返回值可能在不同SQL语句之间变化。 * **VOLATILE** 表示该函数值可以在一次表扫描内改变,不会做任何优化。 * **LEAKPROOF** 表示该函数没有副作用,指出参数只包括返回值。LEAKPROOF只能由系统管理员设置。 * **LEAKPROOF** 表示该函数没有副作用,指出参数只包括返回值。LEAKPROOF只能由系统管理员设置。 * **EXTERNAL** (可选)目的是和SQL兼容,这个特性适合于所有函数,而不仅是外部函数。 * **SECURITY INVOKER** **AUTHID CURRENT\_USER** 表明该函数将以调用它的用户的权限执行。缺省时与指定此参数的作用相同。 SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SECURITY DEFINER** **AUTHID DEFINER** 声明该函数将以创建它的用户的权限执行。 AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **COST execution\_cost** 用来估计函数的执行成本。 execution\_cost以cpu\_operator\_cost为单位。 取值范围:正数 * **ROWS result\_rows** 估计函数返回的行数。用于函数返回的是一个集合。 取值范围:正数,默认值是1000行。 * **configuration\_parameter** * **value** 把指定的数据库会话参数值设置为给定的值。如果value是DEFAULT或者RESET,则在新的会话中使用系统的缺省设置。OFF关闭设置。 取值范围:字符串 * DEFAULT * OFF * RESET 指定默认值。 * **from current** 取当前会话中的值设置为configuration\_parameter的值。 * **new\_name** 函数的新名称。要修改函数的所属模式,必须拥有新模式的CREATE权限。 取值范围:字符串,符合标识符命名规范。 * **new\_owner** 函数的新所有者。要修改函数的所有者,新所有者必须拥有该函数所属模式的CREATE权限。注意:仅有初始化用户才可将函数的owner设置为初始化用户。 取值范围:已存在的用户角色。 * **new\_schema** 函数的新模式。 取值范围:已存在的模式。 * **COMMENT 'text'** 修改函数对象的注释。 ## 示例 请参见CREATE FUNCTION的[示例](create_function.md#zh-cn_topic_0283136560_zh-cn_topic_0237122104_zh-cn_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821)。 ## 相关链接 [CREATE FUNCTION](create_function.md),[DROP FUNCTION](drop_function.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_global_configuration.md --- # ALTER GLOBAL CONFIGURATION ## Function **ALTER GLOBAL CONFIGURATION** adds and modifies the **gs\_global\_config** system catalog and adds the value of **key-value**. ## Precautions Only the initial database user can run this command. The keyword cannot be changed to **weak\_password**. ## Syntax ``` ALTER GLOBAL CONFIGURATION with(paraname=value,paraname=value...); ``` ## Parameter Description * paraname Parameter name, which is of the text type. * value Parameter value, which is of the text type. --- --- url: /en/docs/latest/sql_reference/alter_global_configuration.md --- # ALTER GLOBAL CONFIGURATION ## Function **ALTER GLOBAL CONFIGURATION** adds and modifies the **gs\_global\_config** system catalog and adds the value of **key-value**. ## Precautions * Only the initial database user can run this command. * The keyword cannot be changed to **weak\_password**. ## Syntax ``` ALTER GLOBAL CONFIGURATION with(paraname=value,paraname=value...); ``` ## Parameter Description * paraname Parameter name, which is of the text type. * value Parameter value, which is of the text type. --- --- url: /zh/docs/latest-lite/sql_reference/alter_global_configuration.md --- # ALTER GLOBAL CONFIGURATION ## 功能描述 新增、修改系统表gs\_global\_config,增加key-value值。 ## 注意事项 仅支持数据库初始用户运行此命令。 不支持创建修改关键字为weak\_password。 ## 语法格式 ``` ALTER GLOBAL CONFIGURATION with(paraname=value,paraname=value...); ``` ## 参数说明 * paraname 参数名称,text类型。 * value 参数值,text类型。 --- --- url: /zh/docs/latest/sql_reference/alter_global_configuration.md --- # ALTER GLOBAL CONFIGURATION ## 功能描述 新增、修改系统表gs\_global\_config,增加key-value值。 ## 注意事项 * 仅支持数据库初始用户运行此命令。 * 不支持创建修改关键字为weak\_password。 ## 语法格式 ``` ALTER GLOBAL CONFIGURATION with(paraname=value,paraname=value...); ``` ## 参数说明 * paraname 参数名称,text类型。 * value 参数值,text类型。 --- --- url: /en/docs/latest-lite/sql_reference/alter_group.md --- # ALTER GROUP ## Function **ALTER GROUP** modifies the attributes of a user group. ## Precautions **ALTER GROUP** is an alias for **ALTER ROLE**, and it is not a standard SQL syntax and not recommended. Users can use **ALTER ROLE** directly. ## Syntax * Add users to a group. ``` ALTER GROUP group_name ADD USER user_name [, ... ]; ``` * Remove users from a group. ``` ALTER GROUP group_name DROP USER user_name [, ... ]; ``` * Change the name of the group. ``` ALTER GROUP group_name RENAME TO new_name; ``` ## Parameter Description See [Parameter Description](alter_role.md#en-us_topic_0283137195_en-us_topic_0237122068_en-us_topic_0059778744_s50961af6143d4aafaf8fa02febbbf331) in **ALTER ROLE**. ## Examples ``` -- Add users to a group. openGauss=# ALTER GROUP super_users ADD USER lche, jim; -- Remove users from a group. openGauss=# ALTER GROUP super_users DROP USER jim; -- Change the name of the group. openGauss=# ALTER GROUP super_users RENAME TO normal_users; ``` ## Helpful Links [ALTER GROUP](alter_group.md), [DROP GROUP](drop_group.md), and [ALTER ROLE](alter_role.md) --- --- url: /en/docs/latest/sql_reference/alter_group.md --- # ALTER GROUP ## Function **ALTER GROUP** modifies the attributes of a user group. ## Precautions **ALTER GROUP** is an alias for **ALTER ROLE**, and it is not a standard SQL syntax and not recommended. Users can use **ALTER ROLE** directly. ## Syntax * Add users to a group. ``` ALTER GROUP group_name ADD USER user_name [, ... ]; ``` * Remove users from a group. ``` ALTER GROUP group_name DROP USER user_name [, ... ]; ``` * Change the name of the group. ``` ALTER GROUP group_name RENAME TO new_name; ``` ## Parameter Description See [Parameter Description](alter_role.md#en-us_topic_0283137195_en-us_topic_0237122068_en-us_topic_0059778744_s50961af6143d4aafaf8fa02febbbf331) in **ALTER ROLE**. ## Examples ``` -- Add users to a group. openGauss=# ALTER GROUP super_users ADD USER lche, jim; -- Remove users from a group. openGauss=# ALTER GROUP super_users DROP USER jim; -- Change the name of the group. openGauss=# ALTER GROUP super_users RENAME TO normal_users; ``` ## Helpful Links [ALTER GROUP](alter_group.md), [DROP GROUP](drop_group.md), and [ALTER ROLE](alter_role.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_group.md --- # ALTER GROUP ## 功能描述 修改一个用户组的属性。 ## 注意事项 ALTER GROUP是ALTER ROLE的别名,非SQL标准语法,不推荐使用,建议用户直接使用ALTER ROLE替代。 ## 语法格式 * 向用户组中添加用户。 ``` ALTER GROUP group_name ADD USER user_name [, ... ]; ``` * 从用户组中删除用户。 ``` ALTER GROUP group_name DROP USER user_name [, ... ]; ``` * 修改用户组的名称。 ``` ALTER GROUP group_name RENAME TO new_name; ``` ## 参数说明 请参考ALTER ROLE的[参数说明](alter_role.md#zh-cn_topic_0283137195_zh-cn_topic_0237122068_zh-cn_topic_0059778744_s50961af6143d4aafaf8fa02febbbf331)。 ## 示例 ``` --向用户组中添加用户。 openGauss=# ALTER GROUP super_users ADD USER lche, jim; --从用户组中删除用户。 openGauss=# ALTER GROUP super_users DROP USER jim; --修改用户组的名称。 openGauss=# ALTER GROUP super_users RENAME TO normal_users; ``` ## 相关链接 [ALTER GROUP](alter_group.md),[DROP GROUP](drop_group.md),[ALTER ROLE](alter_role.md) --- --- url: /zh/docs/latest/sql_reference/alter_group.md --- # ALTER GROUP ## 功能描述 修改一个用户组的属性。 ## 注意事项 ALTER GROUP是ALTER ROLE的别名,非SQL标准语法,不推荐使用,建议用户直接使用ALTER ROLE替代。 ## 语法格式 * 向用户组中添加用户。 ``` ALTER GROUP group_name ADD USER user_name [, ... ]; ``` * 从用户组中删除用户。 ``` ALTER GROUP group_name DROP USER user_name [, ... ]; ``` * 修改用户组的名称。 ``` ALTER GROUP group_name RENAME TO new_name; ``` ## 参数说明 请参考ALTER ROLE的[参数说明](alter_role.md#zh-cn_topic_0283137195_zh-cn_topic_0237122068_zh-cn_topic_0059778744_s50961af6143d4aafaf8fa02febbbf331)。 ## 示例 ``` --向用户组中添加用户。 openGauss=# ALTER GROUP super_users ADD USER lche, jim; --从用户组中删除用户。 openGauss=# ALTER GROUP super_users DROP USER jim; --修改用户组的名称。 openGauss=# ALTER GROUP super_users RENAME TO normal_users; ``` ## 相关链接 [ALTER GROUP](alter_group.md),[DROP GROUP](drop_group.md),[ALTER ROLE](alter_role.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_index.md --- # ALTER INDEX ## Function **ALTER INDEX** modifies the definition of an existing index. It has the following forms: * IF EXISTS Sends a notice instead of an error if the specified index does not exist. * RENAME TO Changes only the name of the index. The stored data is not affected. * SET TABLESPACE This option changes the index tablespace to the specified tablespace and moves index-related data files to the new tablespace. * SET ( { STORAGE\_PARAMETER = value } \[, ...] ) Changes one or more index-method-specific storage parameters of an index. Note that the index content will not be modified immediately by this statement. You may need to use **REINDEX** to recreate the index based on different parameters to achieve the expected effect. * RESET ( { storage\_parameter } \[, ...] ) Resets one or more index-method-specific storage parameters of an index to the default value. Similar to the **SET** statement, **REINDEX** may be used to completely update the index. * \[ MODIFY PARTITION index\_partition\_name ] UNUSABLE Sets the indexes on a table or index partition to be unavailable. * REBUILD \[ PARTITION index\_partition\_name ] Rebuilds indexes on a table or an index partition. * RENAME PARTITION Renames an index partition. * MOVE PARTITION Modifies the tablespace to which an index partition belongs. ## Precautions The owner of an index, a user who has the INDEX permission on the table where the index resides, or a user granted the ALTER ANY INDEX permission can run this command. By default, a system administrator has this permission. ## Syntax * Rename a table index. ``` ALTER INDEX [ IF EXISTS ] index_name RENAME TO new_name; ``` * Change the tablespace to which a table index belongs. ``` ALTER INDEX [ IF EXISTS ] index_name SET TABLESPACE tablespace_name; ``` * Modify the storage parameter of a table index. ``` ALTER INDEX [ IF EXISTS ] index_name SET ( {storage_parameter = value} [, ... ] ); ``` * Reset the storage parameter of a table index. ``` ALTER INDEX [ IF EXISTS ] index_name RESET ( storage_parameter [, ... ] ) ; ``` * Set a table index or an index partition to be unavailable. ``` ALTER INDEX [ IF EXISTS ] index_name [ MODIFY PARTITION index_partition_name ] UNUSABLE; ``` > \[!NOTE]NOTE > The syntax cannot be used for column-store tables. * Rebuild a table index or index partition. ``` ALTER INDEX index_name REBUILD [ PARTITION index_partition_name ]; ``` * Rename an index partition. ``` ALTER INDEX [ IF EXISTS ] index_name RENAME PARTITION index_partition_name TO new_index_partition_name; ``` * Modify the tablespace to which an index partition belongs. ``` ALTER INDEX [ IF EXISTS ] index_name MOVE PARTITION index_partition_name TABLESPACE new_tablespace; ``` ## Parameter Description * **index\_name** Specifies the index name to be modified. * **new\_name** Specifies the new name of the index. Value range: a string. It must comply with the naming convention rule. * **tablespace\_name** Specifies the tablespace name. Value range: an existing tablespace name * **storage\_parameter** Specifies the name of an index-method-specific parameter. * **value** Specifies the new value for an index-method-specific storage parameter. This might be a number or a word depending on the parameter. * **new\_index\_partition\_name** Specifies the new name of the index partition. * **index\_partition\_name** Specifies the name of an index partition. * **new\_tablespace** Specifies a new tablespace. ## Examples See [Examples](create_index.md#en-us_topic_0283136578_en-us_topic_0237122106_en-us_topic_0059777455_s985289833081489e9d77c485755bd362) in **CREATE INDEX**. ## Helpful Links [CREATE INDEX](create_index.md), [DROP INDEX](drop_index.md), and [REINDEX](reindex.md) --- --- url: /en/docs/latest/sql_reference/alter_index.md --- # ALTER INDEX ## Function **ALTER INDEX** modifies the definition of an existing index. It has the following forms: * IF EXISTS Sends a notice instead of an error if the specified index does not exist. * RENAME TO Changes only the name of the index. The stored data is not affected. * SET TABLESPACE This option changes the index tablespace to the specified tablespace and moves index-related data files to the new tablespace. * SET ( { STORAGE\_PARAMETER = value } \[, ...] ) Changes one or more index-method-specific storage parameters of an index. Note that the index content will not be modified immediately by this statement. You may need to use **REINDEX** to recreate the index based on different parameters to achieve the expected effect. * RESET ( { storage\_parameter } \[, ...] ) Resets one or more index-method-specific storage parameters of an index to the default value. Similar to the **SET** statement, **REINDEX** may be used to completely update the index. * \[ MODIFY PARTITION index\_partition\_name ] UNUSABLE Sets the indexes on a table or index partition to be unavailable. * REBUILD \[ PARTITION index\_partition\_name ] Rebuilds indexes on a table or an index partition. * RENAME PARTITION Renames an index partition. * MOVE PARTITION Modifies the tablespace to which an index partition belongs. ## Precautions The owner of an index, a user who has the INDEX permission on the table where the index resides, or a user granted the ALTER ANY INDEX permission can run this command. By default, a system administrator has this permission. ## Syntax * Rename a table index. ``` ALTER INDEX [ IF EXISTS ] index_name RENAME TO new_name; ``` * Change the tablespace to which a table index belongs. ``` ALTER INDEX [ IF EXISTS ] index_name SET TABLESPACE tablespace_name; ``` * Modify the storage parameter of a table index. ``` ALTER INDEX [ IF EXISTS ] index_name SET ( {storage_parameter = value} [, ... ] ); ``` * Reset the storage parameter of a table index. ``` ALTER INDEX [ IF EXISTS ] index_name RESET ( storage_parameter [, ... ] ) ; ``` * Set a table index or an index partition to be unavailable. ``` ALTER INDEX [ IF EXISTS ] index_name [ MODIFY PARTITION index_partition_name ] UNUSABLE; ``` > \[!NOTE]NOTE > The syntax cannot be used for column-store tables. * Rebuild a table index or index partition. ``` ALTER INDEX index_name REBUILD [ PARTITION index_partition_name ]; ``` * Rename an index partition. ``` ALTER INDEX [ IF EXISTS ] index_name RENAME PARTITION index_partition_name TO new_index_partition_name; ``` * Modify the tablespace to which an index partition belongs. ``` ALTER INDEX [ IF EXISTS ] index_name MOVE PARTITION index_partition_name TABLESPACE new_tablespace; ``` ## Parameter Description * **index\_name** Specifies the index name to be modified. * **new\_name** Specifies the new name of the index. Value range: a string. It must comply with the naming convention rule. * **tablespace\_name** Specifies the tablespace name. Value range: an existing tablespace name * **storage\_parameter** Specifies the name of an index-method-specific parameter. * **value** Specifies the new value for an index-method-specific storage parameter. This might be a number or a word depending on the parameter. * **new\_index\_partition\_name** Specifies the new name of the index partition. * **index\_partition\_name** Specifies the name of an index partition. * **new\_tablespace** Specifies a new tablespace. ## Examples See [Examples](create_index.md#en-us_topic_0283136578_en-us_topic_0237122106_en-us_topic_0059777455_s985289833081489e9d77c485755bd362) in **CREATE INDEX**. ## Helpful Links [CREATE INDEX](create_index.md), [DROP INDEX](drop_index.md), and [REINDEX](reindex.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_index.md --- # ALTER INDEX ## 功能描述 ALTER INDEX用于修改现有索引的定义。 它有几种子形式: * IF EXISTS 如果指定的索引不存在,则发出一个notice而不是error。 * RENAME TO 只改变索引的名称。对存储的数据没有影响。 * SET TABLESPACE 这个选项会改变索引的表空间为指定表空间,并且把索引相关的数据文件移动到新的表空间里。 * SET ( { STORAGE\_PARAMETER = value } \[, ...] ) 改变索引的一个或多个索引方法特定的存储参数。 需要注意的是索引内容不会被这个命令立即修改,根据参数的不同,可能需要使用REINDEX重建索引来获得期望的效果。 * RESET ( { storage\_parameter } \[, ...] ) 重置索引的一个或多个索引方法特定的存储参数为缺省值。与SET一样,可能需要使用REINDEX来完全更新索引。 * \[ MODIFY PARTITION index\_partition\_name ] UNUSABLE 用于设置表或者索引分区上的索引不可用。 * INVISIBLE / VISIBLE 用于设置表索引隐藏/可见。 * REBUILD \[ PARTITION index\_partition\_name ] 用于重建表或者索引分区上的索引。 * RENAME PARTITION 用于重命名索引分区。 * MOVE PARTITION 用于修改索引分区的所属表空间。 * ENABLE / DISABLE 用于启用/禁用表索引,仅适用于函数索引。 ## 注意事项 索引的所有者或者拥有索引所在表的INDEX权限的用户或者被授予了ALTER ANY INDEX权限的用户有权限执行此命令,系统管理员默认拥有此权限。 ## 语法格式 * 重命名表索引的名称。 ``` ALTER INDEX [ IF EXISTS ] index_name RENAME TO new_name; ``` * 修改表索引的所属空间。 ``` ALTER INDEX [ IF EXISTS ] index_name SET TABLESPACE tablespace_name; ``` * 修改表索引的存储参数。 ``` ALTER INDEX [ IF EXISTS ] index_name SET ( {storage_parameter = value} [, ... ] ); ``` * 重置表索引的存储参数。 ``` ALTER INDEX [ IF EXISTS ] index_name RESET ( storage_parameter [, ... ] ) ; ``` * 设置表索引或索引分区不可用。 ``` ALTER INDEX [ IF EXISTS ] index_name [ MODIFY PARTITION index_partition_name ] UNUSABLE; ``` > \[!NOTE]说明 > 列存表不支持该语法。 * 设置表索引隐藏/可见。 ``` ALTER INDEX [ IF EXISTS ] index_name INVISIBLE / VISIBLE; ``` * 重建表索引或索引分区。 ``` ALTER INDEX index_name REBUILD [ PARTITION index_partition_name ]; ``` * 重命名索引分区。 ``` ALTER INDEX [ IF EXISTS ] index_name RENAME PARTITION index_partition_name TO new_index_partition_name; ``` * 修改索引分区的所属表空间。 ``` ALTER INDEX [ IF EXISTS ] index_name MOVE PARTITION index_partition_name TABLESPACE new_tablespace; ``` * 启用/禁用表索引,仅适用于函数索引。 ``` ALTER INDEX [ IF EXISTS ] index_name ENABLE / DISABLE; ``` ## 参数说明 * **index\_name** 要修改的索引名。 * **new\_name** 新的索引名。 取值范围:字符串,且符合标识符命名规范。 * **tablespace\_name** 表空间的名称。 取值范围:已存在的表空间。 * **storage\_parameter** 索引方法特定的参数名。 * **value** 索引方法特定的存储参数的新值。根据参数的不同,这可能是一个数字或单词。 * **new\_index\_partition\_name** 新索引分区名。 * **index\_partition\_name** 索引分区名。 * **new\_tablespace** 新表空间。 ## 示例 请参见CREATE INDEX的[示例](create_index.md)。 ## 相关链接 [CREATE INDEX](create_index.md),[DROP INDEX](drop_index.md),[REINDEX](reindex.md) --- --- url: /zh/docs/latest/ograc/sql_reference/alter_index.md --- # ALTER INDEX ## 功能描述 ALTER INDEX用于修改现有索引的定义。 ## 注意事项 索引的所有者或者被授予了ALTER ANY INDEX权限的用户有权限执行此命令,普通用户不可以修改系统用户对象。 ## 语法格式 * 重命名表索引的名称。 ``` ALTER INDEX [ schema_name.]index_name ON [ schema_name.]table_name RENAME TO [ schema_name.]new_name; ``` * 重建表索引或索引分区。 ``` ALTER INDEX [ schema_name.]index_name ON [ schema_name.]table_name REBUILD [ PARTITION part_name[,...] | SUBPARTITION subpart_name[,...] ] [ PARALLEL n | PCTFREE n | TABLESPACE tablespace_name ] [,...] ; ``` * 索引空页回收。 ``` ALTER INDEX [ schema_name.]index_name ON [ schema_name.]table_name COALESCE ``` * 设置失效索引。 ``` ALTER INDEX [ schema_name.]index_name ON [ schema_name.]table_name UNUSABLE ``` * 修改索引初始数据页面上事务槽的个数。 ``` ALTER INDEX [ schema_name.]index_name ON [ schema_name.]table_name INITRANS integer ``` * 修改特定分区或二级分区索引。 ``` ALTER INDEX [ schema_name.]index_name ON [ schema_name.]table_name MODIFY [ PARTITION part_name { COALESCE | UNUSABLE | INITRANS integer } | SUBPARTITION subpart_name { COALESCE | UNUSABLE } ] ``` ## 参数说明 * **schema\_name**: 模式名 * **index\_name**: 要修改的索引名 * **table\_name**: 索引所在的表名 * **new\_name**: 新的索引名 * **part\_name**: 分区名 * **subpart\_name**: 二级分区名 * **PARALLEL n**: 指定重建索引时的并行度。 * n的取值范围为\[1, 64]。 * 函数索引不支持并行重建。 * **PCTFREE n**: 指定为索引数据块保留的空间百分比。当数据块的可用空间低于该空间百分比时,只能更新该数据块的数据,不能向该数据块插入数据。 * n的取值范围为\[0, 80],默认值是8。 * **tablespace\_name**: 表空间名,支持重建索引到其他表空间。 * **INITRANS n**: 修改索引初始数据页面上事务槽的个数。 * n的取值范围为\[1, 255]。 * 修改后的新值只对新分配的页面有效,对已经分配的老页面无效。 * 对于分区索引,会同步修改索引分区及子分区的INITRANS属性。 ## 示例 ``` SQL> CREATE TABLE alter_index_test(id INT) PARTITION BY RANGE(id) (PARTITION p1 VALUES LESS THAN (100), PARTITION p2 VALUES LESS THAN (200)); -- 创建分区索引 SQL> CREATE INDEX idx ON alter_index_test(id) LOCAL; -- 重命名索引 SQL> ALTER INDEX idx ON alter_index_test RENAME TO new_idx; -- 失效索引 SQL> ALTER INDEX new_idx ON alter_index_test UNUSABLE; -- 重建索引 SQL> ALTER INDEX new_idx ON alter_index_test REBUILD PCTFREE 50; -- 重建索引分区,指定并行度 SQL> ALTER INDEX new_idx ON alter_index_test REBUILD PARTITION p2 PARALLEL 2; -- 指定分区p1的INITRANS SQL> ALTER INDEX new_idx ON alter_index_test MODIFY PARTITION p1 INITRANS 200; SQL> DROP TABLE alter_index_test; ``` --- --- url: /zh/docs/latest/sql_reference/alter_index.md --- # ALTER INDEX ## 功能描述 ALTER INDEX用于修改现有索引的定义。 它有几种子形式: * IF EXISTS 如果指定的索引不存在,则发出一个notice而不是error。 * RENAME TO 只改变索引的名称。对存储的数据没有影响。 * SET TABLESPACE 这个选项会改变索引的表空间为指定表空间,并且把索引相关的数据文件移动到新的表空间里。 * SET ( { STORAGE\_PARAMETER = value } \[, ...] ) 改变索引的一个或多个索引方法特定的存储参数。 需要注意的是索引内容不会被这个命令立即修改,根据参数的不同,可能需要使用REINDEX重建索引来获得期望的效果。 * RESET ( { storage\_parameter } \[, ...] ) 重置索引的一个或多个索引方法特定的存储参数为缺省值。与SET一样,可能需要使用REINDEX来完全更新索引。 * \[ MODIFY PARTITION index\_partition\_name ] UNUSABLE 用于设置表或者索引分区上的索引不可用。 * INVISIBLE / VISIBLE 用于设置表索引隐藏/可见。 * REBUILD \[ PARTITION index\_partition\_name ] 用于重建表或者索引分区上的索引。 * RENAME PARTITION 用于重命名索引分区。 * MOVE PARTITION 用于修改索引分区的所属表空间。 * ENABLE / DISABLE 用于启用/禁用表索引,仅适用于函数索引。 ## 注意事项 索引的所有者或者拥有索引所在表的INDEX权限的用户或者被授予了ALTER ANY INDEX权限的用户有权限执行此命令,系统管理员默认拥有此权限。 ## 语法格式 * 重命名表索引的名称。 ``` ALTER INDEX [ IF EXISTS ] index_name RENAME TO new_name; ``` * 修改表索引的所属空间。 ``` ALTER INDEX [ IF EXISTS ] index_name SET TABLESPACE tablespace_name; ``` * 修改表索引的存储参数。 ``` ALTER INDEX [ IF EXISTS ] index_name SET ( {storage_parameter = value} [, ... ] ); ``` * 重置表索引的存储参数。 ``` ALTER INDEX [ IF EXISTS ] index_name RESET ( storage_parameter [, ... ] ) ; ``` * 设置表索引或索引分区不可用。 ``` ALTER INDEX [ IF EXISTS ] index_name [ MODIFY PARTITION index_partition_name ] UNUSABLE; ``` > \[!NOTE]说明 > 列存表不支持该语法。 * 设置表索引隐藏/可见。 ``` ALTER INDEX [ IF EXISTS ] index_name INVISIBLE / VISIBLE; ``` * 重建表索引或索引分区。 ``` ALTER INDEX index_name REBUILD [ PARTITION index_partition_name ]; ``` * 重命名索引分区。 ``` ALTER INDEX [ IF EXISTS ] index_name RENAME PARTITION index_partition_name TO new_index_partition_name; ``` * 修改索引分区的所属表空间。 ``` ALTER INDEX [ IF EXISTS ] index_name MOVE PARTITION index_partition_name TABLESPACE new_tablespace; ``` * 启用/禁用表索引,仅适用于函数索引。 ``` ALTER INDEX [ IF EXISTS ] index_name ENABLE / DISABLE; ``` ## 参数说明 * **index\_name** 要修改的索引名。 * **new\_name** 新的索引名。 取值范围:字符串,且符合标识符命名规范。 * **tablespace\_name** 表空间的名称。 取值范围:已存在的表空间。 * **storage\_parameter** 索引方法特定的参数名。 * **value** 索引方法特定的存储参数的新值。根据参数的不同,这可能是一个数字或单词。 * **new\_index\_partition\_name** 新索引分区名。 * **index\_partition\_name** 索引分区名。 * **new\_tablespace** 新表空间。 ## 示例 请参见CREATE INDEX的[示例](create_index.md#zh-cn_topic_0283136578_zh-cn_topic_0237122106_zh-cn_topic_0059777455_s985289833081489e9d77c485755bd362)。 ## 相关链接 [CREATE INDEX](create_index.md),[DROP INDEX](drop_index.md),[REINDEX](reindex.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_language.md --- # ALTER LANGUAGE ## Function **ALTER LANGUAGE** modifies the definition of a procedural language. A single-node system or centralized system does not support modifying procedural languages. ## Syntax ``` ALTER [ PROCEDURAL ] LANGUAGE name RENAME TO new_name ALTER [ PROCEDURAL ] LANGUAGE name OWNER TO new_owner ``` ## Parameter Description * **name** Name of a language. * **new\_name** New name of a language. * **new\_owner** New owner of a language. ## Compatibility The SQL standard does not contain the **ALTER LANGUAGE** statement. --- --- url: /en/docs/latest/sql_reference/alter_language.md --- # ALTER LANGUAGE ## Function **ALTER LANGUAGE** modifies the definition of a procedural language. A single-node system or centralized system does not support modifying procedural languages. ## Syntax ``` ALTER [ PROCEDURAL ] LANGUAGE name RENAME TO new_name ALTER [ PROCEDURAL ] LANGUAGE name OWNER TO new_owner ``` ## Parameter Description * **name** Name of a language. * **new\_name** New name of a language. * **new\_owner** New owner of a language. ## Compatibility The SQL standard does not contain the **ALTER LANGUAGE** statement. --- --- url: /zh/docs/latest-lite/sql_reference/alter_language.md --- # ALTER LANGUAGE ## 功能描述 修改一个过程语言的定义。单机和集中式暂不支持修改过程语言。 ## 语法格式 ``` ALTER [ PROCEDURAL ] LANGUAGE name RENAME TO new_name ALTER [ PROCEDURAL ] LANGUAGE name OWNER TO new_owner ``` ## 参数说明 * **name** 语言的名字。 * **new\_name** 语言的新名字。 * **new\_owner** 语言的新的所有者。 ## 兼容性 SQL标准里没有ALTER LANGUAGE语句。 --- --- url: /zh/docs/latest/sql_reference/alter_language.md --- # ALTER LANGUAGE ## 功能描述 修改一个过程语言的定义。单机和集中式暂不支持修改过程语言。 ## 语法格式 ``` ALTER [ PROCEDURAL ] LANGUAGE name RENAME TO new_name ALTER [ PROCEDURAL ] LANGUAGE name OWNER TO new_owner ``` ## 参数说明 * **name** 语言的名字。 * **new\_name** 语言的新名字。 * **new\_owner** 语言的新的所有者。 ## 兼容性 SQL标准里没有ALTER LANGUAGE语句。 --- --- url: /en/docs/latest-lite/sql_reference/alter_large_object.md --- # ALTER LARGE OBJECT ## Function **ALTER LARGE OBJECT** changes the owner of a large object. ## Precautions Only a system administrator or the owner of the to-be-modified large object can run **ALTER LARGE OBJECT**. ## Syntax ``` ALTER LARGE OBJECT large_object_oid OWNER TO new_owner; ``` ## Parameter Description * **large\_object\_oid** Specifies the OID of the large object to be modified. Value range: an existing large object name * **OWNER TO new\_owner** Specifies the new owner of an object. Value range: an existing username or role name ## Examples None --- --- url: /en/docs/latest/sql_reference/alter_large_object.md --- # ALTER LARGE OBJECT ## Function **ALTER LARGE OBJECT** changes the owner of a large object. ## Precautions Only a system administrator or the owner of the to-be-modified large object can run **ALTER LARGE OBJECT**. ## Syntax ``` ALTER LARGE OBJECT large_object_oid OWNER TO new_owner; ``` ## Parameter Description * **large\_object\_oid** Specifies the OID of the large object to be modified. Value range: an existing large object name * **OWNER TO new\_owner** Specifies the new owner of an object. Value range: an existing username or role name ## Examples None --- --- url: /zh/docs/latest-lite/sql_reference/alter_large_object.md --- # ALTER LARGE OBJECT ## 功能描述 ALTER LARGE OBJECT用于更改一个large object的定义。它的唯一的功能是分配一个新的所有者。 ## 注意事项 使用ALTER LARGE OBJECT必须是系统管理员或者是其所有者。 ## 语法格式 ``` ALTER LARGE OBJECT large_object_oid OWNER TO new_owner; ``` ## 参数说明 * **large\_object\_oid** 要被变large object的OID 。 取值范围:已存在的大对象名。 * **OWNER TO new\_owner** large object新的所有者。 取值范围:已存在的用户名/角色名。 ## 示例 无。 --- --- url: /zh/docs/latest/sql_reference/alter_large_object.md --- # ALTER LARGE OBJECT ## 功能描述 ALTER LARGE OBJECT用于更改一个large object的定义。它的唯一的功能是分配一个新的所有者。 ## 注意事项 使用ALTER LARGE OBJECT必须是系统管理员或者是其所有者。 ## 语法格式 ``` ALTER LARGE OBJECT large_object_oid OWNER TO new_owner; ``` ## 参数说明 * **large\_object\_oid** 要被变large object的OID 。 取值范围:已存在的大对象名。 * **OWNER TO new\_owner** large object新的所有者。 取值范围:已存在的用户名/角色名。 ## 示例 无。 --- --- url: /en/docs/latest-lite/sql_reference/alter_masking_policy.md --- # ALTER MASKING POLICY ## Function **ALTER MASKING POLICY** modifies masking policies. ## Precautions * Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. * The masking policy takes effect only after **enable\_security\_policy** is set to **on**. * For details about the execution effect and supported data types of preset masking functions, see "Database Security > Dynamic Data Masking" in *Feature Description*. ## Syntax * Modify the policy description. ``` ALTER MASKING POLICY policy_name COMMENTS policy_comments; ``` * Modify the masking method. ``` ALTER MASKING POLICY policy_name [ADD | REMOVE | MODIFY] masking_actions[, ...]*; The syntax of masking_action. masking_function ON LABEL(label_name[, ...]*) ``` * Modify the scenarios where the masking policies take effect. ``` ALTER MASKING POLICY policy_name MODIFY(FILTER ON FILTER_TYPE(filter_value[, ...]*)[, ...]*); ``` * Removes the filters of the masking policies. ``` ALTER MASKING POLICY policy_name DROP FILTER; ``` * Enable or disable the masking policies. ``` ALTER MASKING POLICY policy_name [ENABLE | DISABLE]; ``` ## Parameter Description * **policy\_name** Specifies the masking policy name, which must be unique. Value range: a string. It must comply with the naming convention. * **policy\_comments** Adds or modifies description of masking policies. * **masking\_function** Specifies eight preset masking methods or user-defined functions. Schemas are supported. **maskall** is not a preset function. It is hard-coded and cannot be displayed by running **\df**. The masking methods during presetting are as follows: ``` maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking ``` * **label\_name** Specifies the resource label name. * **FILTER\_TYPE** Specifies the types of information to be filtered by the policies: **IP**, **ROLES**, and **APP**. * **filter\_value** Indicates the detailed information to be filtered, such as the IP address, app name, and username. * **ENABLE|DISABLE** Enables or disables the masking policy. If **ENABLE|DISABLE** is not specified, **ENABLE** is used by default. ## Examples ``` -- Create users dev_mask and bob_mask. openGauss=# CREATE USER dev_mask PASSWORD 'xxxxxx'; openGauss=# CREATE USER bob_mask PASSWORD 'xxxxxx'; -- Create table tb_for_masking. openGauss=# CREATE TABLE tb_for_masking(col1 text, col2 text, col3 text); -- Create a resource label for label sensitive column col1. openGauss=# CREATE RESOURCE LABEL mask_lb1 ADD COLUMN(tb_for_masking.col1); -- Create a resource label for label sensitive column col2. openGauss=# CREATE RESOURCE LABEL mask_lb2 ADD COLUMN(tb_for_masking.col2); -- Create a masking policy for the operation of accessing sensitive column col1. openGauss=# CREATE MASKING POLICY maskpol1 maskall ON LABEL(mask_lb1); -- Add description for masking policy maskpol1. openGauss=# ALTER MASKING POLICY maskpol1 COMMENTS 'masking policy for tb_for_masking.col1'; -- Modify masking policy maskpol1 to add a masking method. openGauss=# ALTER MASKING POLICY maskpol1 ADD randommasking ON LABEL(mask_lb2); -- Modify masking policy maskpol1 to remove a masking method. openGauss=# ALTER MASKING POLICY maskpol1 REMOVE randommasking ON LABEL(mask_lb2); -- Modify masking policy maskpol1 to modify a masking method. openGauss=# ALTER MASKING POLICY maskpol1 MODIFY randommasking ON LABEL(mask_lb1); -- Modify masking policy maskpol1 so that it takes effect only for scenarios where users are dev_mask and bob_mask, client tools are psql and gsql, and the IP addresses are 10.20.30.40 and 127.0.0.0/24. openGauss=# ALTER MASKING POLICY maskpol1 MODIFY (FILTER ON ROLES(dev_mask, bob_mask), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24')); -- Modify masking policy maskpol1 so that it takes effect for all user scenarios. openGauss=# ALTER MASKING POLICY maskpol1 DROP FILTER; -- Disable masking policy maskpol1. openGauss=# ALTER MASKING POLICY maskpol1 DISABLE; ``` ## Helpful Links [CREATE MASKING POLICY](create_masking_policy.md) and [DROP MASKING POLICY](drop_masking_policy.md) --- --- url: /en/docs/latest/sql_reference/alter_masking_policy.md --- # ALTER MASKING POLICY ## Function **ALTER MASKING POLICY** modifies masking policies. ## Precautions * Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. * The masking policy takes effect only after **enable\_security\_policy** is set to **on**. * For details about the execution effect and supported data types of preset masking functions, see "Database Security > Dynamic Data Masking" in *Feature Description*. ## Syntax * Modify the policy description. ``` ALTER MASKING POLICY policy_name COMMENTS policy_comments; ``` * Modify the masking method. ``` ALTER MASKING POLICY policy_name [ADD | REMOVE | MODIFY] masking_actions[, ...]*; The syntax of masking_action. masking_function ON LABEL(label_name[, ...]*) ``` * Modify the scenarios where the masking policies take effect. ``` ALTER MASKING POLICY policy_name MODIFY(FILTER ON FILTER_TYPE(filter_value[, ...]*)[, ...]*); ``` * Removes the filters of the masking policies. ``` ALTER MASKING POLICY policy_name DROP FILTER; ``` * Enable or disable the masking policies. ``` ALTER MASKING POLICY policy_name [ENABLE | DISABLE]; ``` ## Parameter Description * **policy\_name** Specifies the masking policy name, which must be unique. Value range: a string. It must comply with the naming convention. * **policy\_comments** Adds or modifies description of masking policies. * **masking\_function** Specifies eight preset masking methods or user-defined functions. Schemas are supported. **maskall** is not a preset function. It is hard-coded and cannot be displayed by running **\df**. The masking methods during presetting are as follows: ``` maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking ``` * **label\_name** Specifies the resource label name. * **FILTER\_TYPE** Specifies the types of information to be filtered by the policies: **IP**, **ROLES**, and **APP**. * **filter\_value** Indicates the detailed information to be filtered, such as the IP address, app name, and username. * **ENABLE|DISABLE** Enables or disables the masking policy. If **ENABLE|DISABLE** is not specified, **ENABLE** is used by default. ## Examples ``` -- Create users dev_mask and bob_mask. openGauss=# CREATE USER dev_mask PASSWORD 'xxxxxx'; openGauss=# CREATE USER bob_mask PASSWORD 'xxxxxx'; -- Create table tb_for_masking. openGauss=# CREATE TABLE tb_for_masking(col1 text, col2 text, col3 text); -- Create a resource label for label sensitive column col1. openGauss=# CREATE RESOURCE LABEL mask_lb1 ADD COLUMN(tb_for_masking.col1); -- Create a resource label for label sensitive column col2. openGauss=# CREATE RESOURCE LABEL mask_lb2 ADD COLUMN(tb_for_masking.col2); -- Create a masking policy for the operation of accessing sensitive column col1. openGauss=# CREATE MASKING POLICY maskpol1 maskall ON LABEL(mask_lb1); -- Add description for masking policy maskpol1. openGauss=# ALTER MASKING POLICY maskpol1 COMMENTS 'masking policy for tb_for_masking.col1'; -- Modify masking policy maskpol1 to add a masking method. openGauss=# ALTER MASKING POLICY maskpol1 ADD randommasking ON LABEL(mask_lb2); -- Modify masking policy maskpol1 to remove a masking method. openGauss=# ALTER MASKING POLICY maskpol1 REMOVE randommasking ON LABEL(mask_lb2); -- Modify masking policy maskpol1 to modify a masking method. openGauss=# ALTER MASKING POLICY maskpol1 MODIFY randommasking ON LABEL(mask_lb1); -- Modify masking policy maskpol1 so that it takes effect only for scenarios where users are dev_mask and bob_mask, client tools are psql and gsql, and the IP addresses are 10.20.30.40 and 127.0.0.0/24. openGauss=# ALTER MASKING POLICY maskpol1 MODIFY (FILTER ON ROLES(dev_mask, bob_mask), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24')); -- Modify masking policy maskpol1 so that it takes effect for all user scenarios. openGauss=# ALTER MASKING POLICY maskpol1 DROP FILTER; -- Disable masking policy maskpol1. openGauss=# ALTER MASKING POLICY maskpol1 DISABLE; ``` ## Helpful Links [CREATE MASKING POLICY](create_masking_policy.md) and [DROP MASKING POLICY](drop_masking_policy.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_masking_policy.md --- # ALTER MASKING POLICY ## 功能描述 修改脱敏策略。 ## 注意事项 * 只有poladmin,sysadmin或初始用户才能执行此操作。 * 需要打开enable\_security\_policy开关脱敏策略才可以生效。 * 预置脱敏函数的执行效果及支持的数据类型请参考《关于openGauss》中”特性描述 > 数据库安全 > 动态数据脱敏机制”章节。 ## 语法格式 * 修改策略描述: ``` ALTER MASKING POLICY policy_name COMMENTS policy_comments; ``` * 修改脱敏方式: ``` ALTER MASKING POLICY policy_name [ADD | REMOVE | MODIFY] masking_actions[, ...]*; 其中masking_action: masking_function ON LABEL(label_name[, ...]*) ``` * 修改脱敏策略生效场景: ``` ALTER MASKING POLICY policy_name MODIFY(FILTER ON FILTER_TYPE(filter_value[, ...]*)[, ...]*); ``` * 移除脱敏策略生效场景,使策略对所用场景生效: ``` ALTER MASKING POLICY policy_name DROP FILTER; ``` * 修改脱敏策略开启/关闭: ``` ALTER MASKING POLICY policy_name [ENABLE | DISABLE]; ``` ## 参数说明 * **policy\_name** 脱敏策略名称,需要唯一,不可重复。 取值范围:字符串,要符合标识符的命名规范。 * **policy\_comments** 需要为脱敏策略添加或修改的描述信息。 * **masking\_function** 指的是预置的八种脱敏方式或者用户自定义的函数,支持模式。 maskall不是预置函数,硬编码在代码中,不支持\df展示。 预置时脱敏方式如下: ``` maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking ``` * **label\_name** 资源标签名称。 * **FILTER\_TYPE** 指定脱敏策略的过滤信息,过滤类型包括:IP、ROLES、APP。 * **filter\_value** 指具体过滤信息内容,例如具体的IP,具体的APP名称,具体的用户名。 * **ENABLE|DISABLE** 可以打开或关闭脱敏策略。若不指定ENABLE|DISABLE,语句默认为ENABLE。 ## 示例 ``` --创建dev_mask和bob_mask用户。 openGauss=# CREATE USER dev_mask PASSWORD 'XXXXXXXX'; openGauss=# CREATE USER bob_mask PASSWORD 'XXXXXXXX'; --创建一个表tb_for_masking openGauss=# CREATE TABLE tb_for_masking(col1 text, col2 text, col3 text); --创建资源标签标记敏感列col1 openGauss=# CREATE RESOURCE LABEL mask_lb1 ADD COLUMN(tb_for_masking.col1); --创建资源标签标记敏感列col2 openGauss=# CREATE RESOURCE LABEL mask_lb2 ADD COLUMN(tb_for_masking.col2); --对访问敏感列col1的操作创建脱敏策略 openGauss=# CREATE MASKING POLICY maskpol1 maskall ON LABEL(mask_lb1); --为脱敏策略maskpol1添加描述 openGauss=# ALTER MASKING POLICY maskpol1 COMMENTS 'masking policy for tb_for_masking.col1'; --修改脱敏策略maskpol1,新增一项脱敏方式 openGauss=# ALTER MASKING POLICY maskpol1 ADD randommasking ON LABEL(mask_lb2); --修改脱敏策略maskpol1,移除一项脱敏方式 openGauss=# ALTER MASKING POLICY maskpol1 REMOVE randommasking ON LABEL(mask_lb2); --修改脱敏策略maskpol1,修改一项脱敏方式 openGauss=# ALTER MASKING POLICY maskpol1 MODIFY randommasking ON LABEL(mask_lb1); --修改脱敏策略maskpol1使之仅对用户dev_mask和bob_mask,客户端工具为psql和gsql,IP地址为'10.20.30.40', '127.0.0.0/24'场景生效。 openGauss=# ALTER MASKING POLICY maskpol1 MODIFY (FILTER ON ROLES(dev_mask, bob_mask), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24')); --修改脱敏策略maskpol1,使之对所有用户场景生效 openGauss=# ALTER MASKING POLICY maskpol1 DROP FILTER; --禁用脱敏策略maskpol1 openGauss=# ALTER MASKING POLICY maskpol1 DISABLE; ``` ## 相关链接 [CREATE MASKING POLICY](create_masking_policy.md),[DROP MASKING POLICY](drop_masking_policy.md)。 --- --- url: /zh/docs/latest/sql_reference/alter_masking_policy.md --- # ALTER MASKING POLICY ## 功能描述 修改脱敏策略。 ## 注意事项 * 只有poladmin、sysadmin或初始用户才能执行此操作。 * 需要打开enable\_security\_policy开关脱敏策略才可以生效。 * 预置脱敏函数的执行效果及支持的数据类型请参考《关于openGauss》中“特性描述 > 数据库安全 > 动态数据脱敏机制”章节。 ## 语法格式 * 修改策略描述: ``` ALTER MASKING POLICY policy_name COMMENTS policy_comments; ``` * 修改脱敏方式: ``` ALTER MASKING POLICY policy_name [ADD | REMOVE | MODIFY] masking_actions[, ...]*; 其中masking_action: masking_function ON LABEL(label_name[, ...]*) ``` * 修改脱敏策略生效场景: ``` ALTER MASKING POLICY policy_name MODIFY(FILTER ON FILTER_TYPE(filter_value[, ...]*)[, ...]*); ``` * 移除脱敏策略生效场景,使策略对所用场景生效: ``` ALTER MASKING POLICY policy_name DROP FILTER; ``` * 修改脱敏策略开启/关闭: ``` ALTER MASKING POLICY policy_name [ENABLE | DISABLE]; ``` ## 参数说明 * **policy\_name** 脱敏策略名称,需要唯一,不可重复。 取值范围:字符串,要符合标识符的命名规范。 * **policy\_comments** 需要为脱敏策略添加或修改的描述信息。 * **masking\_function** 指的是预置的八种脱敏方式或者用户自定义的函数,支持模式。 maskall不是预置函数,硬编码在代码中,不支持\df展示。 预置时脱敏方式如下: ``` maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking ``` * **label\_name** 资源标签名称。 * **FILTER\_TYPE** 指定脱敏策略的过滤信息,过滤类型包括:IP、ROLES、APP。 * **filter\_value** 指具体过滤信息内容,例如具体的IP、具体的APP名称、具体的用户名。 * **ENABLE|DISABLE** 可以打开或关闭脱敏策略。若不指定ENABLE|DISABLE,语句默认为ENABLE。 ## 示例 ``` --创建dev_mask和bob_mask用户。 openGauss=# CREATE USER dev_mask PASSWORD 'xxxxxxxx'; openGauss=# CREATE USER bob_mask PASSWORD 'xxxxxxxx'; --创建一个表tb_for_masking openGauss=# CREATE TABLE tb_for_masking(col1 text, col2 text, col3 text); --创建资源标签标记敏感列col1 openGauss=# CREATE RESOURCE LABEL mask_lb1 ADD COLUMN(tb_for_masking.col1); --创建资源标签标记敏感列col2 openGauss=# CREATE RESOURCE LABEL mask_lb2 ADD COLUMN(tb_for_masking.col2); --对访问敏感列col1的操作创建脱敏策略 openGauss=# CREATE MASKING POLICY maskpol1 maskall ON LABEL(mask_lb1); --为脱敏策略maskpol1添加描述 openGauss=# ALTER MASKING POLICY maskpol1 COMMENTS 'masking policy for tb_for_masking.col1'; --修改脱敏策略maskpol1,新增一项脱敏方式 openGauss=# ALTER MASKING POLICY maskpol1 ADD randommasking ON LABEL(mask_lb2); --修改脱敏策略maskpol1,移除一项脱敏方式 openGauss=# ALTER MASKING POLICY maskpol1 REMOVE randommasking ON LABEL(mask_lb2); --修改脱敏策略maskpol1,修改一项脱敏方式 openGauss=# ALTER MASKING POLICY maskpol1 MODIFY randommasking ON LABEL(mask_lb1); --修改脱敏策略maskpol1使之仅对用户dev_mask和bob_mask,客户端工具为psql和gsql,IP地址为'10.20.30.40','127.0.0.0/24'场景生效。 openGauss=# ALTER MASKING POLICY maskpol1 MODIFY (FILTER ON ROLES(dev_mask, bob_mask), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24')); --修改脱敏策略maskpol1,使之对所有用户场景生效 openGauss=# ALTER MASKING POLICY maskpol1 DROP FILTER; --禁用脱敏策略maskpol1 openGauss=# ALTER MASKING POLICY maskpol1 DISABLE; ``` ## 相关链接 [CREATE MASKING POLICY](create_masking_policy.md),[DROP MASKING POLICY](drop_masking_policy.md)。 --- --- url: /en/docs/latest-lite/sql_reference/alter_materialized_view.md --- # ALTER MATERIALIZED VIEW ## Function **ALTER MATERIALIZED VIEW** changes multiple auxiliary attributes of an existing materialized view. Statements and actions that can be used for **ALTER MATERIALIZED VIEW** are a subset of **ALTER TABLE** and have the same meaning when used for materialized views. For details, see [ALTER TABLE](alter_table.md). ## Precautions * Only the owner of a materialized view or a system administrator has the **ALTER TMATERIALIZED VIEW** permission. * The materialized view structure cannot be modified. ## Syntax * Change the owner of the materialized view. ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name OWNER TO new_owner; ``` * Modify the column of a materialized view. ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME [ COLUMN ] column_name TO new_column_name; ``` * Rename a materialized view. ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME TO new_name; ``` ## Parameter Description * **mv\_name** Specifies the name of an existing materialized view, which can be schema-qualified. Value range: a string. It must comply with the naming convention. * **column\_name** Specifies the name of a new or existing column. Value range: a string. It must comply with the naming convention. * **new\_column\_name** Specifies the new name of an existing column. * **new\_owner** Specifies the user name of the new owner of a materialized view. * **new\_name** Specifies the new name of a materialized view. ## Examples ``` -- Rename the materialized view foo to bar. openGauss=# ALTER MATERIALIZED VIEW foo RENAME TO bar; ``` ## Helpful Links [CREATE MATERIALIZED VIEW](create_materialized_view.md), [CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md), [DROP MATERIALIZED VIEW](drop_materialized_view.md), [REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md), and [REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /en/docs/latest/sql_reference/alter_materialized_view.md --- # ALTER MATERIALIZED VIEW ## Function **ALTER MATERIALIZED VIEW** changes multiple auxiliary attributes of an existing materialized view. Statements and actions that can be used for **ALTER MATERIALIZED VIEW** are a subset of **ALTER TABLE** and have the same meaning when used for materialized views. For details, see [ALTER TABLE](alter_table.md). ## Precautions * Only the owner of a materialized view or a system administrator has the **ALTER TMATERIALIZED VIEW** permission. * The materialized view structure cannot be modified. ## Syntax * Change the owner of the materialized view. ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name OWNER TO new_owner; ``` * Modify the column of a materialized view. ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME [ COLUMN ] column_name TO new_column_name; ``` * Rename a materialized view. ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME TO new_name; ``` ## Parameter Description * **mv\_name** Specifies the name of an existing materialized view, which can be schema-qualified. Value range: a string. It must comply with the naming convention. * **column\_name** Specifies the name of a new or existing column. Value range: a string. It must comply with the naming convention. * **new\_column\_name** Specifies the new name of an existing column. * **new\_owner** Specifies the user name of the new owner of a materialized view. * **new\_name** Specifies the new name of a materialized view. ## Examples ``` -- Rename the materialized view foo to bar. openGauss=# ALTER MATERIALIZED VIEW foo RENAME TO bar; ``` ## Helpful Links [CREATE MATERIALIZED VIEW](create_materialized_view.md), [CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md), [DROP MATERIALIZED VIEW](drop_materialized_view.md), [REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md), and [REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_materialized_view.md --- # ALTER MATERIALIZED VIEW ## 功能描述 更改一个现有物化视图的多个辅助属性。 可用于ALTER MATERIALIZED VIEW的语句形式和动作是ALTER TABLE的一个子集,并且在用于物化视图时具有相同的含义。详见[ALTER TABLE](alter_table.md)。 ## 注意事项 * 只有物化视图的所有者有权限执行ALTER TMATERIALIZED VIEW命令,系统管理员默认拥有此权限。 * 不支持更改物化视图结构。 ## 语法格式 * 修改物化视图的所属用户。 ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name OWNER TO new_owner; ``` * 修改物化视图的列。 ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME [ COLUMN ] column_name TO new_column_name; ``` * 重命名物化视图。 ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME TO new_name; ``` ## 参数说明 * **mv\_name** 一个现有物化视图的名称,可以用模式修饰。 取值范围:字符串,符合标识符命名规范。 * **column\_name** 一个新的或者现有的列的名称。 取值范围:字符串,符合标识符命名规范。 * **new\_column\_name** 一个现有列的新名称。 * **new\_owner** 该物化视图的新拥有者的用户名。 * **new\_name** 该物化视图的新名称。 ## 示例 ``` --把物化视图foo重命名为bar。 openGauss=# ALTER MATERIALIZED VIEW foo RENAME TO bar; ``` ## 相关链接 [CREATE MATERIALIZED VIEW](create_materialized_view.md),[CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md),[DROP MATERIALIZED VIEW](drop_materialized_view.md),[REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md),[REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /zh/docs/latest/sql_reference/alter_materialized_view.md --- # ALTER MATERIALIZED VIEW ## 功能描述 更改一个现有物化视图的多个辅助属性。 可用于ALTER MATERIALIZED VIEW的语句形式和动作是ALTER TABLE的一个子集,并且在用于物化视图时具有相同的含义。详见[ALTER TABLE](alter_table.md)。 ## 注意事项 * 只有物化视图的所有者有权限执行ALTER TMATERIALIZED VIEW命令,系统管理员默认拥有此权限。 * 不支持更改物化视图结构。 ## 语法格式 * 修改物化视图的所属用户。 ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name OWNER TO new_owner; ``` * 修改物化视图的列。 ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME [ COLUMN ] column_name TO new_column_name; ``` * 重命名物化视图。 ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME TO new_name; ``` ## 参数说明 * **mv\_name** 一个现有物化视图的名称,可以用模式修饰。 取值范围:字符串,符合标识符命名规范。 * **column\_name** 一个新的或者现有的列的名称。 取值范围:字符串,符合标识符命名规范。 * **new\_column\_name** 一个现有列的新名称。 * **new\_owner** 该物化视图的新拥有者的用户名。 * **new\_name** 该物化视图的新名称。 ## 示例 ``` --把物化视图foo重命名为bar。 openGauss=# ALTER MATERIALIZED VIEW foo RENAME TO bar; ``` ## 相关链接 [CREATE MATERIALIZED VIEW](create_materialized_view.md),[CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md),[DROP MATERIALIZED VIEW](drop_materialized_view.md),[REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md) ,[REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_operator.md --- # ALTER OPERATOR ## Function ALTER OPERATOR modifies the definition of an operator. ## Precautions ALTER OPERATOR changes the definition of an operator. Currently, the only function available is to change the owner of the operator. To use ALTER OPERATOR, you must be the owner of the operator. To modify the owner, you must also be a direct or indirect member of the new owning role, and that member must have CREATE permission on the operator's schema. (These restrictions force the owner to do nothing that cannot be done by deleting and recreating the operator. However, a user with the SYSADMIN permission can modify the ownership of any operator in any way.) ## Syntax ``` ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) OWNER TO new_owner ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) SET SCHEMA new_schema ``` ## Parameter Description * **name** Name of an existing operator. * **left\_type** Data type of the left operand for the operator; if there is no left operand, write NONE. * **right\_type** Data type of the right operand for the operator; if there is no right operand, write NONE. * **new\_owner** New owner of the operator. * **new\_schema** New schema name of the operator. ## Example Change a user-defined operator for text a @@ b: ``` ALTER OPERATOR @@ (text, text) OWNER TO joe; ``` ## Compatibility The SQL standard does not contain the ALTER OPERATOR statement. --- --- url: /en/docs/latest/sql_reference/alter_operator.md --- # ALTER OPERATOR ## Function ALTER OPERATOR modifies the definition of an operator. ## Precautions ALTER OPERATOR changes the definition of an operator. Currently, the only function available is to change the owner of the operator. To use ALTER OPERATOR, you must be the owner of the operator. To modify the owner, you must also be a direct or indirect member of the new owning role, and that member must have CREATE permission on the operator's schema. (These restrictions force the owner to do nothing that cannot be done by deleting and recreating the operator. However, a user with the SYSADMIN permission can modify the ownership of any operator in any way.) ## Syntax ``` ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) OWNER TO new_owner ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) SET SCHEMA new_schema ``` ## Parameter Description * **name** Name of an existing operator. * **left\_type** Data type of the left operand for the operator; if there is no left operand, write NONE. * **right\_type** Data type of the right operand for the operator; if there is no right operand, write NONE. * **new\_owner** New owner of the operator. * **new\_schema** New schema name of the operator. ## Example Change a user-defined operator for text a @@ b: ``` ALTER OPERATOR @@ (text, text) OWNER TO joe; ``` ## Compatibility The SQL standard does not contain the ALTER OPERATOR statement. --- --- url: /zh/docs/latest-lite/sql_reference/alter_operator.md --- # ALTER OPERATOR ## 功能描述 修改一个操作符的定义。 ## 注意事项 ALTER OPERATOR改变一个操作符的定义。 目前唯一能用的功能是改变操作符的所有者。 要使用ALTER OPERATOR,你必须是该操作符的所有者。 要修改所有者,你还必须是新的所有角色的直接或间接成员,并且该成员必须在此操作符的模式上有CREATE权限。 (这些限制强制了修改该所有者不会做任何通过删除和重建操作符不能做的事情。不过,具有SYSADMIN权限用户可以以任何方式修改任意操作符的所有权。) ## 语法格式 ``` ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) OWNER TO new_owner ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) SET SCHEMA new_schema ``` ## 参数说明 * **name** 一个现有操作符的名字。 * **left\_type** 操作符的左操作数的数据类型;如果没有左操作数,那么写NONE。 * **right\_type** 操作符的右操作数的数据类型;如果没有右操作数,那么写NONE。 * **new\_owner** 操作符的新所有者。 * **new\_schema** 操作符的新模式名。 ## 示例 改变一个用于text的用户定义操作符a @@ b: ``` ALTER OPERATOR @@ (text, text) OWNER TO joe; ``` ## 兼容性 SQL 标准里没有ALTER OPERATOR语句。 --- --- url: /zh/docs/latest/sql_reference/alter_operator.md --- # ALTER OPERATOR ## 功能描述 修改一个操作符的定义。 ## 注意事项 ALTER OPERATOR改变一个操作符的定义。目前唯一能用的功能是改变操作符的所有者。 要使用ALTER OPERATOR,你必须是该操作符的所有者。要修改所有者,你还必须是新的所有角色的直接或间接成员,并且该成员必须在此操作符的模式上有CREATE权限。(这些限制强制了修改该所有者不会做任何通过删除和重建操作符不能做的事情。不过,具有SYSADMIN权限用户可以以任何方式修改任意操作符的所有权。) ## 语法格式 ``` ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) OWNER TO new_owner ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) SET SCHEMA new_schema ``` ## 参数说明 * **name** 一个现有操作符的名字。 * **left\_type** 操作符的左操作数的数据类型;如果没有左操作数,那么写NONE。 * **right\_type** 操作符的右操作数的数据类型;如果没有右操作数,那么写NONE。 * **new\_owner** 操作符的新所有者。 * **new\_schema** 操作符的新模式名。 ## 示例 改变一个用于text的用户定义操作符a @@ b: ``` ALTER OPERATOR @@ (text, text) OWNER TO joe; ``` ## 兼容性 SQL 标准里没有ALTER OPERATOR语句。 --- --- url: /en/docs/latest-lite/sql_reference/alter_package.md --- # ALTER PACKAGE ## Function **ALTER PACKAGE** alters the attributes of a package. ## Precautions Currently, only users with the **ALTER PACKAGE OWNER** permission can run this command. The system administrator has this permission by default. The restrictions are as follows: * The current user must be the owner of the package or the system administrator and a member of the new owner role. ## Syntax * Change the owner of a package. ``` ALTER PACKAGE package_name OWNER TO new_owner; ``` ## Parameter Description * **package\_name** Specifies the name of the package to be modified. Value range: an existing package name. Only one package can be modified at a time. * **new\_owner** Specifies the new owner of a package. To change the owner of a package, the new owner must have the **CREATE** permission on the schema to which the package belongs. Value range: an existing user role. ## Examples For details, see [CREATE PACKAGE](create_package.md). ## Helpful Links [CREATE PACKAGE](create_package.md) and [DROP PACKAGE](drop_package.md) --- --- url: /en/docs/latest/sql_reference/alter_package.md --- # ALTER PACKAGE ## Function **ALTER PACKAGE** alters the attributes of a package. ## Precautions Currently, only users with the **ALTER PACKAGE OWNER** permission can run this command. The system administrator has this permission by default. The restrictions are as follows: * The current user must be the owner of the package or the system administrator and a member of the new owner role. ## Syntax * Change the owner of a package. ``` ALTER PACKAGE package_name OWNER TO new_owner; ``` ## Parameter Description * **package\_name** Specifies the name of the package to be modified. Value range: an existing package name. Only one package can be modified at a time. * **new\_owner** Specifies the new owner of a package. To change the owner of a package, the new owner must have the **CREATE** permission on the schema to which the package belongs. Value range: an existing user role. ## Examples For details, see [CREATE PACKAGE](create_package.md). ## Helpful Links [CREATE PACKAGE](create_package.md) and [DROP PACKAGE](drop_package.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_package.md --- # ALTER PACKAGE ## 功能描述 修改PACKAGE的属性或重编译PACKAGE。当PACKAGE因为依赖的引用对象发生改变而变为失效状态后,直接使用PACKAGE中失效的对象可能会导致错误的执行结果。如PACKAGE中定义存储过程的入参依赖自定义的类型或表字段,对自定义类型或表字段添加新属性后,调用原来的存储过程无法向新添加的属性传参,openGauss支持对这种场景下的PACKAGE进行重新编译,恢复其有效状态。 ## 注意事项 * 目前仅支持ALTER PACKAGE OWNER和ALTER PACKAGE COMPILE功能,系统管理员默认拥有该权限,有以下权限约束: * 当前用户必须是该PACKAGE的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 仅有初始化用户可以修改定义者权限的package的owner。 ## 语法格式 * 修改PACKAGE的所属者。 ``` ALTER PACKAGE package_name OWNER TO new_owner; ``` * 重编译PACKAGE。 ``` ALTER PACKAGE package_name COMPILE { compile_pkg_opt } ; ``` ## 参数说明 * **package\_name** 要修改的PACKAGE名称。 取值范围:已存在的PACKAGE名,仅支持修改单个PACKAGE。 * **new\_owner** PACKAGE的新所有者。要修改函数的所有者,新所有者必须拥有该PACKAGE所属模式的CREATE权限。 取值范围:已存在的用户角色。 * **compile\_pkg\_opt** 重编译PACKAGE的选项,包括SPECIFICATION, BODY, PACKAGE或不指定,不指定时默认选项为PACKAGE。 ## 示例 请参见[CREATE PACKAGE](create_package.md)中示例。 ## 相关链接 [CREATE PACKAGE](create_package.md),[DROP PACKAGE](drop_package.md) --- --- url: /zh/docs/latest/sql_reference/alter_package.md --- # ALTER PACKAGE ## 功能描述 修改PACKAGE的属性或重编译PACKAGE。当PACKAGE因为依赖的引用对象发生改变而变为失效状态后,直接使用PACKAGE中失效的对象可能会导致错误的执行结果。如PACKAGE中定义存储过程的入参依赖自定义的类型或表字段,对自定义类型或表字段添加新属性后,调用原来的存储过程无法向新添加的属性传参,openGauss支持对这种场景下的PACKAGE进行重新编译,恢复其有效状态。 ## 注意事项 * 目前仅支持ALTER PACKAGE OWNER和ALTER PACKAGE COMPILE功能,系统管理员默认拥有该权限,有以下权限约束: * 当前用户必须是该PACKAGE的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 仅有初始化用户可以修改定义者权限的package的owner。 ## 语法格式 * 修改PACKAGE的所属者。 ``` ALTER PACKAGE package_name OWNER TO new_owner; ``` * 重编译PACKAGE。 ``` ALTER PACKAGE package_name COMPILE { compile_pkg_opt } ; ``` ## 参数说明 * **package\_name** 要修改的PACKAGE名称。 取值范围:已存在的PACKAGE名,仅支持修改单个PACKAGE。 * **new\_owner** PACKAGE的新所有者。要修改函数的所有者,新所有者必须拥有该PACKAGE所属模式的CREATE权限。 取值范围:已存在的用户角色。 * **compile\_pkg\_opt** 重编译PACKAGE的选项,包括SPECIFICATION, BODY, PACKAGE或不指定,不指定时默认选项为PACKAGE。 ## 示例 请参见[CREATE PACKAGE](create_package.md)中示例。 ## 相关链接 [CREATE PACKAGE](create_package.md),[DROP PACKAGE](drop_package.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-ALTER-PROC.md --- # ALTER PROC ## 功能描述 修改自定义存储过程的属性。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。原openGauss的ALTER PROCEDURE语法请参考章节[ALTER PROCEDURE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_procedure.html)。 * 新增支持通过ALTER PROC方式修改自定义存储过程的属性,功能和ALTER PROCEDURE方式保持一致。 * ALTER PROCEDURE/PROC COMPILE仅在A库生效,在D库报错不支持。 ## 语法格式 * 修改自定义存储过程的附加参数。 ``` ALTER { PROCEDURE | PROC } procedure_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为: ``` {CALLED ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' ``` * 修改自定义存储过程的名称。 ``` ALTER { PROCEDURE | PROC } proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * 修改自定义存储过程的所属者。 ``` ALTER { PROCEDURE | PROC } proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * 修改自定义存储过程的模式。 ``` ALTER { PROCEDURE | PROC } proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` * 重编译存储过程。 ``` ALTER { PROCEDURE | PROC } procedure_name COMPILE; ``` 仅在A库生效,在D库报错不支持。 ## 参数说明 * **PROC** 新增通过ALTER PROC方式修改自定义存储过程的属性,功能和ALTER PROCEDURE方式保持一致。 ## 示例 ```sql create schema test_proc; set current_schema to test_proc; create procedure p1() is begin RAISE INFO 'call procedure: p1'; end; / create proc p2() is begin RAISE INFO 'call procedure: p2'; end; / alter procedure p1() stable; alter proc p2() stable; select provolatile from pg_proc where proname = 'p1'; provolatile ------------- s (1 row) select provolatile from pg_proc where proname = 'p2'; provolatile ------------- s (1 row) alter procedure p1() rename to new_p1; alter proc p2() rename to new_p2; \df new_p1(); List of functions Schema | Name | Result data type | Argument data types | Type | fencedmode | propackage | prokind -----------+--------+------------------+---------------------+--------+------------+------------+--------- test_proc | new_p1 | void | | normal | f | f | p (1 row) \df new_p2(); List of functions Schema | Name | Result data type | Argument data types | Type | fencedmode | propackage | prokind -----------+--------+------------------+---------------------+--------+------------+------------+--------- test_proc | new_p2 | void | | normal | f | f | p (1 row) create user test_proc_user with password 'xxxxxxxx'; grant all privileges to test_proc_user; alter procedure new_p1() owner to test_proc_user; alter proc new_p2() owner to test_proc_user; select usename from pg_user a, pg_proc b where a.usesysid = b.proowner and b.proname = 'new_p1'; usename ---------------- test_proc_user (1 row) select usename from pg_user a, pg_proc b where a.usesysid = b.proowner and b.proname = 'new_p2'; usename ---------------- test_proc_user (1 row) create schema new_schema; alter procedure new_p1() set schema new_schema; alter proc new_p2() set schema new_schema; select nspname from pg_namespace a, pg_proc b where a.oid = b.pronamespace and b.proname = 'new_p1'; nspname ------------ new_schema (1 row) select nspname from pg_namespace a, pg_proc b where a.oid = b.pronamespace and b.proname = 'new_p2'; nspname ------------ new_schema (1 row) alter procedure new_p1 compile; ERROR: This operation is not supported. alter procedure new_p1() compile; ERROR: This operation is not supported. alter proc new_p2 compile; ERROR: This operation is not supported. alter proc new_p2() compile; ERROR: This operation is not supported. call new_schema.new_p1(); INFO: call procedure: p1 new_p1 -------- (1 row) call new_schema.new_p2(); INFO: call procedure: p2 new_p2 -------- (1 row) ``` ## 相关链接 [ALTER PROCEDURE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_procedure.html) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-ALTER-PROC.md --- # ALTER PROC ## 功能描述 修改自定义存储过程的属性。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。原openGauss的ALTER PROCEDURE语法请参考章节[ALTER PROCEDURE](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_procedure.html)。 * 新增支持通过ALTER PROC方式修改自定义存储过程的属性,功能和ALTER PROCEDURE方式保持一致。 * ALTER PROCEDURE/PROC COMPILE仅在A库生效,在D库报错不支持。 ## 语法格式 * 修改自定义存储过程的附加参数。 ``` ALTER { PROCEDURE | PROC } procedure_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为: ``` {CALLED ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' ``` * 修改自定义存储过程的名称。 ``` ALTER { PROCEDURE | PROC } proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * 修改自定义存储过程的所属者。 ``` ALTER { PROCEDURE | PROC } proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * 修改自定义存储过程的模式。 ``` ALTER { PROCEDURE | PROC } proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` * 重编译存储过程。 ``` ALTER { PROCEDURE | PROC } procedure_name COMPILE; ``` 仅在A库生效,在D库报错不支持。 ## 参数说明 * **PROC** 新增通过ALTER PROC方式修改自定义存储过程的属性,功能和ALTER PROCEDURE方式保持一致。 ## 示例 ```sql create schema test_proc; set current_schema to test_proc; create procedure p1() is begin RAISE INFO 'call procedure: p1'; end; / create proc p2() is begin RAISE INFO 'call procedure: p2'; end; / alter procedure p1() stable; alter proc p2() stable; select provolatile from pg_proc where proname = 'p1'; provolatile ------------- s (1 row) select provolatile from pg_proc where proname = 'p2'; provolatile ------------- s (1 row) alter procedure p1() rename to new_p1; alter proc p2() rename to new_p2; \df new_p1(); List of functions Schema | Name | Result data type | Argument data types | Type | fencedmode | propackage | prokind -----------+--------+------------------+---------------------+--------+------------+------------+--------- test_proc | new_p1 | void | | normal | f | f | p (1 row) \df new_p2(); List of functions Schema | Name | Result data type | Argument data types | Type | fencedmode | propackage | prokind -----------+--------+------------------+---------------------+--------+------------+------------+--------- test_proc | new_p2 | void | | normal | f | f | p (1 row) create user test_proc_user with password 'xxxxxxxx'; grant all privileges to test_proc_user; alter procedure new_p1() owner to test_proc_user; alter proc new_p2() owner to test_proc_user; select usename from pg_user a, pg_proc b where a.usesysid = b.proowner and b.proname = 'new_p1'; usename ---------------- test_proc_user (1 row) select usename from pg_user a, pg_proc b where a.usesysid = b.proowner and b.proname = 'new_p2'; usename ---------------- test_proc_user (1 row) create schema new_schema; alter procedure new_p1() set schema new_schema; alter proc new_p2() set schema new_schema; select nspname from pg_namespace a, pg_proc b where a.oid = b.pronamespace and b.proname = 'new_p1'; nspname ------------ new_schema (1 row) select nspname from pg_namespace a, pg_proc b where a.oid = b.pronamespace and b.proname = 'new_p2'; nspname ------------ new_schema (1 row) alter procedure new_p1 compile; ERROR: This operation is not supported. alter procedure new_p1() compile; ERROR: This operation is not supported. alter proc new_p2 compile; ERROR: This operation is not supported. alter proc new_p2() compile; ERROR: This operation is not supported. call new_schema.new_p1(); INFO: call procedure: p1 new_p1 -------- (1 row) call new_schema.new_p2(); INFO: call procedure: p2 new_p2 -------- (1 row) ``` ## 相关链接 [ALTER PROCEDURE](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_procedure.html) --- --- url: /en/docs/latest-lite/sql_reference/alter_procedure.md --- # ALTER PROCEDURE ## Function **ALTER PROCEDURE** alters the attributes of a customized stored procedure. ## Precautions Only the owner of a stored procedure or a user granted with the **ALTER** permission can run the **ALTER PROCEDURE** command. The system administrator has this permission by default. The following is permission constraints depending on attributes to be modified: * If a stored procedure involves operations on temporary tables, **ALTER PROCEDURE** cannot be used. * To modify the owner or schema of a stored procedure, you must be the owner of the stored procedure or system administrator and a member of the new owner role. * Only the system administrator and initial user can change the schema of a stored procedure to **public**. ## Syntax * Modify the additional parameters of a customized stored procedure. ``` ALTER PROCEDURE procedure_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` The syntax of the **action** clause is as follows: ``` {CALLED ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' ``` * Modify the name of a customized stored procedure. ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * Modify the owner of a customized stored procedure. ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * Modify the schema of a customized stored procedure. ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` ## Parameter Description * **procedure\_name** Specifies the name of the stored procedure to be modified. Value range: an existing stored procedure name * **argmode** Specifies whether a parameter is an input or output parameter. Value range: **IN**, **OUT**, **INOUT**, and **VARIADIC** * **argname** Specifies the parameter name. Value range: a string. It must comply with the identifier naming convention. * **argtype** Specifies the type of the stored procedure parameter. * **CALLED ON NULL INPUT** Declares that some parameters of the stored procedure can be called in normal mode if the parameter values are null. Omitting this parameter is the same as specifying it. * **IMMUTABLE** Specifies that the stored procedure always returns the same result if the parameter values are the same. * **STABLE** Specifies that the stored procedure cannot modify the database, and that within a single table scan it will consistently return the same result for the same parameter value, but its result varies by SQL statements. * **VOLATILE** Specifies that the stored procedure value can change in a single table scan and no optimization is performed. * **LEAKPROOF** Specifies that the stored procedure has no side effect and the parameter contains only the return value. **LEAKPROOF** can be set only by the system administrator. * **EXTERNAL** (Optional) The purpose is to be compatible with SQL. This feature applies to all functions, not only external functions. * **SECURITY INVOKER** **AUTHID CURRENT\_USER** Specifies that the stored procedure will be executed with the permissions of the user who calls it. Omitting this parameter is the same as specifying it. **SECURITY INVOKER** and **AUTHID CURRENT\_USER** have the same functions. * **SECURITY DEFINER** **AUTHID DEFINER** Specifies that the stored procedure will be executed with the permissions of the user who created it. **AUTHID DEFINER** and **SECURITY DEFINER** have the same functions. * **COST execution\_cost** Estimates the execution cost of the stored procedure. The unit of **execution\_cost** is **cpu\_operator\_cost**. Value range: a positive integer * **ROWS result\_rows** Estimates the number of rows returned by the stored procedure. This is only allowed when the stored procedure is declared to return a set. Value range: a positive number. The default value is **1000**. * **configuration\_parameter** * **value** Sets a specified database session parameter to a specified value. If the value is **DEFAULT** or **RESET**, the default setting is used in the new session. **OFF** disables the setting. Value range: a string. * DEFAULT * OFF * RESET Specifies the default value. * **from current** Uses the value of **configuration\_parameter** of the current session. * **new\_name** Specifies the new name of the stored procedure. To change the schema of a stored procedure, you must have the **CREATE** permission on the new schema. Value range: a string. It must comply with the identifier naming convention. * **new\_owner** Specifies the new owner of the stored procedure. To change the owner of a stored procedure, the new owner must have the CREATE permission on the schema to which the stored procedure belongs. Value range: an existing user role * **new\_schema** Specifies the new schema of the stored procedure. Value range: an existing schema * **COMMENT 'text'** Comment a stored procedure. ## Examples See [Examples](create_function.md#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821) in **CREATE FUNCTION**. ## Helpful Links [CREATE PROCEDURE](create_procedure.md) and [DROP PROCEDURE](drop_procedure.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-alter-procedure.md --- # ALTER PROCEDURE ## Function Description Alters the attributes of a customized stored procedure. ## Precautions Compared with the original openGauss, Dolphin modifies the ALTER PROCEDURE syntax as follows: 1. The modifiable LANGUAGE option is added. 2. The modifiable item { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } is added. 3. The modifiable item SQL SECURITY { DEFINER | INVOKER } is added. ## Syntax * Modify the additional parameters of the customized stored procedure. ``` ALTER PROCEDURE procedure_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` The syntax of the **action** clause is as follows: ``` {CALLED ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ``` ## Parameter Description * **LANGUAGE lang\_name** Name of the language used to implement the stored procedure. This parameter is compatible only with the syntax and has no actual effect. * **SQL SECURITY INVOKER** ​ Specifies that the stored procedure is to be executed with the permissions of the user that calls it. This parameter can be omitted. ​ The functions of SQL SECURITY INVOKER and SECURITY INVOKER and AUTHID CURRENT\_USER are the same. * **SQL SECURITY DEFINER** Specifies that the stored procedure is to be executed with the privileges of the user that created it. The functions of SQL SECURITY DEFINER and AUTHID DEFINER and SECURITY DEFINER are the same. * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** Syntax compatibility item. ## Example ``` --Specify NO SQL. openGauss=# ALTER PROCEDURE proc1() NO SQL; --Specify CONTAINS SQL. openGauss=# ALTER PROCEDURE proc1() CONTAINS SQL; --Specify LANGUAGE SQL. openGauss=# ALTER PROCEDURE proc1() CONTAINS SQL LANGUAGE SQL ; --Specify MODIFIES SQL DATA. openGauss=# ALTER PROCEDURE proc1() CONTAINS SQL MODIFIES SQL DATA; --Specify SECURITY INVOKER. openGauss=# ALTER PROCEDURE proc1() SQL SECURITY INVOKER; ``` ## Helpful Links [ALTER PROCEDURE](https://docs.opengauss.org/en/docs/latest/sql_reference/alter_procedure.html) --- --- url: /en/docs/latest/sql_reference/alter_procedure.md --- # ALTER PROCEDURE ## Function **ALTER PROCEDURE** alters the attributes of a customized stored procedure. ## Precautions Only the owner of a stored procedure or a user granted with the **ALTER** permission can run the **ALTER PROCEDURE** command. The system administrator has this permission by default. The following is permission constraints depending on attributes to be modified: * If a stored procedure involves operations on temporary tables, **ALTER PROCEDURE** cannot be used. * To modify the owner or schema of a stored procedure, you must be the owner of the stored procedure or system administrator and a member of the new owner role. * Only the system administrator and initial user can change the schema of a stored procedure to **public**. ## Syntax * Modify the additional parameters of a customized stored procedure. ``` ALTER PROCEDURE procedure_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` The syntax of the **action** clause is as follows: ``` {CALLED ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' ``` * Modify the name of a customized stored procedure. ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * Modify the owner of a customized stored procedure. ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * Modify the schema of a customized stored procedure. ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` ## Parameter Description * **procedure\_name** Specifies the name of the stored procedure to be modified. Value range: an existing stored procedure name * **argmode** Specifies whether a parameter is an input or output parameter. Value range: **IN**, **OUT**, **INOUT**, and **VARIADIC** * **argname** Specifies the parameter name. Value range: a string. It must comply with the identifier naming convention. * **argtype** Specifies the type of the stored procedure parameter. * **CALLED ON NULL INPUT** Declares that some parameters of the stored procedure can be called in normal mode if the parameter values are null. Omitting this parameter is the same as specifying it. * **IMMUTABLE** Specifies that the stored procedure always returns the same result if the parameter values are the same. * **STABLE** Specifies that the stored procedure cannot modify the database, and that within a single table scan it will consistently return the same result for the same parameter value, but its result varies by SQL statements. * **VOLATILE** Specifies that the stored procedure value can change in a single table scan and no optimization is performed. * **LEAKPROOF** Specifies that the stored procedure has no side effect and the parameter contains only the return value. **LEAKPROOF** can be set only by the system administrator. * **EXTERNAL** (Optional) The purpose is to be compatible with SQL. This feature applies to all functions, not only external functions. * **SECURITY INVOKER** **AUTHID CURRENT\_USER** Specifies that the stored procedure will be executed with the permissions of the user who calls it. Omitting this parameter is the same as specifying it. **SECURITY INVOKER** and **AUTHID CURRENT\_USER** have the same functions. * **SECURITY DEFINER** **AUTHID DEFINER** Specifies that the stored procedure will be executed with the permissions of the user who created it. **AUTHID DEFINER** and **SECURITY DEFINER** have the same functions. * **COST execution\_cost** Estimates the execution cost of the stored procedure. The unit of **execution\_cost** is **cpu\_operator\_cost**. Value range: a positive integer * **ROWS result\_rows** Estimates the number of rows returned by the stored procedure. This is only allowed when the stored procedure is declared to return a set. Value range: a positive number. The default value is **1000**. * **configuration\_parameter** * **value** Sets a specified database session parameter to a specified value. If the value is **DEFAULT** or **RESET**, the default setting is used in the new session. **OFF** disables the setting. Value range: a string. * DEFAULT * OFF * RESET Specifies the default value. * **from current** Uses the value of **configuration\_parameter** of the current session. * **new\_name** Specifies the new name of the stored procedure. To change the schema of a stored procedure, you must have the **CREATE** permission on the new schema. Value range: a string. It must comply with the identifier naming convention. * **new\_owner** Specifies the new owner of the stored procedure. To change the owner of a stored procedure, the new owner must have the CREATE permission on the schema to which the stored procedure belongs. Value range: an existing user role * **new\_schema** Specifies the new schema of the stored procedure. Value range: an existing schema * **COMMENT 'text'** Comment a stored procedure. ## Examples See [Examples](create_function.md#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821) in **CREATE FUNCTION**. ## Helpful Links [CREATE PROCEDURE](create_procedure.md) and [DROP PROCEDURE](drop_procedure.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-ALTER-PROCEDURE.md --- # ALTER PROCEDURE ## 功能描述 修改自定义存储过程的属性。 ## 注意事项 相比于原始的openGauss,dolphin对于ALTER PROCEDURE语法的修改为: 1. 增加可修改 LANGUAGE 选项。 2. 增加可修改项 { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } 。 3. 增加可修改项 SQL SECURITY { DEFINER | INVOKER }。 ## 语法格式 * 修改自定义存储过程的附加参数。 ``` ALTER PROCEDURE procedure_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为。 ``` {CALLED ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ``` ## 参数说明 * **LANGUAGE lang\_name** 用以实现存储过程的语言的名称,仅语法兼容,实际修改不会生效。 * **SQL SECURITY INVOKER** ​ 表明该存储过程将带着调用它的用户的权限执行。该参数可以省略。 ​ SQL SECURITY INVOKER和SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SQL SECURITY DEFINER** 声明该存储过程将以创建它的用户的权限执行。 SQL SECURITY DEFINER和AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** 语法兼容项。 ## 示例 ``` --指定 NO SQL openGauss=# ALTER PROCEDURE proc1() NO SQL; --指定 CONTAINS SQL openGauss=# ALTER PROCEDURE proc1() CONTAINS SQL; --指定 LANGUAGE SQL openGauss=# ALTER PROCEDURE proc1() CONTAINS SQL LANGUAGE SQL ; --指定 MODIFIES SQL DATA openGauss=# ALTER PROCEDURE proc1() CONTAINS SQL MODIFIES SQL DATA; --指定 SECURITY INVOKER openGauss=# ALTER PROCEDURE proc1() SQL SECURITY INVOKER; ``` ## 相关链接 [ALTER PROCEDURE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_procedure.html) --- --- url: /zh/docs/latest-lite/sql_reference/alter_procedure.md --- # ALTER PROCEDURE ## 功能描述 修改自定义存储过程的属性。 ## 注意事项 只有存储过程的所有者或者被授予了存储过程ALTER权限的用户才能执行ALTER PROCEDURE命令,系统管理员默认拥有该权限。针对所要修改属性的不同,还有以下权限约束: * 如果存储过程中涉及对临时表相关的操作,则无法使用ALTER PROCEDURE。 * 修改存储过程的所有者或修改存储过程的模式,当前用户必须是该存储过程的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 只有系统管理员和初始化用户可以将procedure的schema修改成public。 * 重命名存储过程时,不能与当前模式下已经存在的synonym产生命名冲突。 * 修改存储过程的模式时,不能与新模式下已经存在的synonym产生命名冲突。 * 重编译存储过程时,对于PACKAGE中定义的存储过程需要使用ALTER PACKAGE语句。 ## 语法格式 * 修改自定义存储过程的附加参数。 ``` ALTER PROCEDURE procedure_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为。 ``` {CALLED ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' ``` * 修改自定义存储过程的名称。 ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * 修改自定义存储过程的所属者。 ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * 修改自定义存储过程的模式。 ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` * 重编译存储过程。 ``` ALTER PROCEDURE procedure_name COMPILE; ``` ## 参数说明 * **procedure\_name** 要修改的存储过程名称。 取值范围:已存在的存储过程名。 * **argmode** 标识该参数是输入、输出参数。 取值范围:IN/OUT/INOUT/VARIADIC。 * **argname** 参数名称。 取值范围:字符串,符合标识符命名规范。 * **argtype** 存储过程参数的类型。 * **CALLED ON NULL INPUT** 表明该存储过程的某些参数是NULL的时候可以按照正常的方式调用。缺省时与指定此参数的作用相同。 * **IMMUTABLE** 表示该存储过程在给出同样的参数值时总是返回同样的结果。 * **STABLE** 表示该存储过程不能修改数据库,对相同参数值,在同一次表扫描里,该函数的返回值不变,但是返回值可能在不同SQL语句之间变化。 * **VOLATILE** 表示该存储过程值可以在一次表扫描内改变,不会做任何优化。 * **LEAKPROOF** 表示该存储过程没有副作用,指出参数只包括返回值。LEAKPROOF只能由系统管理员设置。 * **EXTERNAL** (可选)目的是和SQL兼容,这个特性适合于所有函数,而不仅是外部函数。 * **SECURITY INVOKER** **AUTHID CURRENT\_USER** 表明该存储过程将以调用它的用户的权限执行。缺省时与指定此参数的作用相同。 SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SECURITY DEFINER** **AUTHID DEFINER** 声明该存储过程将以创建它的用户的权限执行。 AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **COST execution\_cost** 用来估计存储过程的执行成本。 execution\_cost以cpu\_operator\_cost为单位。 取值范围:正数。 * **ROWS result\_rows** 估计存储过程返回的行数。用于存储过程返回的是一个集合。 取值范围:正数,默认值是1000行。 * **configuration\_parameter** * **value** 把指定的数据库会话参数值设置为给定的值。如果value是DEFAULT或者RESET,则在新的会话中使用系统的缺省设置。OFF关闭设置。 取值范围:字符串。 * DEFAULT * OFF * RESET 指定默认值。 * **from current** 取当前会话中的值设置为configuration\_parameter的值。 * **new\_name** 存储过程的新名称。要修改存储过程的所属模式,必须拥有新模式的CREATE权限。 取值范围:字符串,符合标识符命名规范。 * **new\_owner** 存储过程的新所有者。要修改存储过程的所有者,新所有者必须拥有该存储过程所属模式的CREATE权限。 取值范围:已存在的用户角色。 * **new\_schema** 存储过程的新模式。 取值范围:已存在的模式。 * **COMMENT 'text'** 修改存储过程的注释。 ## 示例 请参见CREATE FUNCTION的[示例](create_function.md#zh-cn_topic_0283136560_zh-cn_topic_0237122104_zh-cn_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821)。 ## 相关链接 [CREATE PROCEDURE](create_procedure.md),[DROP PROCEDURE](drop_procedure.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-ALTER-PROCEDURE.md --- # ALTER PROCEDURE ## 功能描述 修改自定义存储过程的属性。 ## 注意事项 相比于原始的openGauss,dolphin对于ALTER PROCEDURE语法的修改为: 1. 增加可修改 LANGUAGE 选项。 2. 增加可修改项 { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } 。 3. 增加可修改项 SQL SECURITY { DEFINER | INVOKER }。 ## 语法格式 * 修改自定义存储过程的附加参数。 ``` ALTER PROCEDURE procedure_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为。 ``` {CALLED ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ``` ## 参数说明 * **LANGUAGE lang\_name** 用以实现存储过程的语言的名称,仅语法兼容,实际修改不会生效。 * **SQL SECURITY INVOKER** ​ 表明该存储过程将带着调用它的用户的权限执行。该参数可以省略。 ​ SQL SECURITY INVOKER和SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SQL SECURITY DEFINER** 声明该存储过程将以创建它的用户的权限执行。 SQL SECURITY DEFINER和AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** 语法兼容项。 ## 示例 ``` --指定 NO SQL openGauss=# ALTER PROCEDURE proc1() NO SQL; --指定 CONTAINS SQL openGauss=# ALTER PROCEDURE proc1() CONTAINS SQL; --指定 LANGUAGE SQL openGauss=# ALTER PROCEDURE proc1() CONTAINS SQL LANGUAGE SQL ; --指定 MODIFIES SQL DATA openGauss=# ALTER PROCEDURE proc1() CONTAINS SQL MODIFIES SQL DATA; --指定 SECURITY INVOKER openGauss=# ALTER PROCEDURE proc1() SQL SECURITY INVOKER; ``` ## 相关链接 [ALTER PROCEDURE](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_procedure.html) --- --- url: /zh/docs/latest/sql_reference/alter_procedure.md --- # ALTER PROCEDURE ## 功能描述 修改自定义存储过程的属性。 ## 注意事项 只有存储过程的所有者或者被授予了存储过程ALTER权限的用户才能执行ALTER PROCEDURE命令,系统管理员默认拥有该权限。针对所要修改属性的不同,还有以下权限约束: * 如果存储过程中涉及对临时表相关的操作,则无法使用ALTER PROCEDURE。 * 修改存储过程的所有者或修改存储过程的模式,当前用户必须是该存储过程的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 只有系统管理员和初始化用户可以将procedure的schema修改成public。 * 重命名存储过程时,不能与当前模式下已经存在的synonym产生命名冲突。 * 修改存储过程的模式时,不能与新模式下已经存在的synonym产生命名冲突。 * 重编译存储过程时,对于PACKAGE中定义的存储过程需要使用ALTER PACKAGE语句。 ## 语法格式 * 修改自定义存储过程的附加参数。 ``` ALTER PROCEDURE procedure_name ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ``` 其中附加参数action子句语法为。 ``` {CALLED ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER } | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter { { TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter | ALL} | COMMENT 'text' ``` * 修改自定义存储过程的名称。 ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) RENAME TO new_name; ``` * 修改自定义存储过程的所属者。 ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) OWNER TO new_owner; ``` * 修改自定义存储过程的模式。 ``` ALTER PROCEDURE proname ( [ { [ argname ] [ argmode ] argtype} [, ...] ] ) SET SCHEMA new_schema; ``` * 重编译存储过程。 ``` ALTER PROCEDURE procedure_name COMPILE; ``` ## 参数说明 * **procedure\_name** 要修改的存储过程名称。 取值范围:已存在的存储过程名。 * **argmode** 标识该参数是输入、输出参数。 取值范围:IN/OUT/INOUT/VARIADIC。 * **argname** 参数名称。 取值范围:字符串,符合标识符命名规范。 * **argtype** 存储过程参数的类型。 * **CALLED ON NULL INPUT** 表明该存储过程的某些参数是NULL的时候可以按照正常的方式调用。缺省时与指定此参数的作用相同。 * **IMMUTABLE** 表示该存储过程在给出同样的参数值时总是返回同样的结果。 * **STABLE** 表示该存储过程不能修改数据库,对相同参数值,在同一次表扫描里,该函数的返回值不变,但是返回值可能在不同SQL语句之间变化。 * **VOLATILE** 表示该存储过程值可以在一次表扫描内改变,不会做任何优化。 * **LEAKPROOF** 表示该存储过程没有副作用,指出参数只包括返回值。LEAKPROOF只能由系统管理员设置。 * **EXTERNAL** (可选)目的是和SQL兼容,这个特性适合于所有函数,而不仅是外部函数。 * **SECURITY INVOKER** **AUTHID CURRENT\_USER** 表明该存储过程将以调用它的用户的权限执行。缺省时与指定此参数的作用相同。 SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SECURITY DEFINER** **AUTHID DEFINER** 声明该存储过程将以创建它的用户的权限执行。 AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **COST execution\_cost** 用来估计存储过程的执行成本。 execution\_cost以cpu\_operator\_cost为单位。 取值范围:正数。 * **ROWS result\_rows** 估计存储过程返回的行数。用于存储过程返回的是一个集合。 取值范围:正数,默认值是1000行。 * **configuration\_parameter** * **value** 把指定的数据库会话参数值设置为给定的值。如果value是DEFAULT或者RESET,则在新的会话中使用系统的缺省设置。OFF关闭设置。 取值范围:字符串。 * DEFAULT * OFF * RESET 指定默认值。 * **from current** 取当前会话中的值设置为configuration\_parameter的值。 * **new\_name** 存储过程的新名称。要修改存储过程的所属模式,必须拥有新模式的CREATE权限。 取值范围:字符串,符合标识符命名规范。 * **new\_owner** 存储过程的新所有者。要修改存储过程的所有者,新所有者必须拥有该存储过程所属模式的CREATE权限。 取值范围:已存在的用户角色。 * **new\_schema** 存储过程的新模式。 取值范围:已存在的模式。 * **COMMENT 'text'** 修改存储过程的注释。 ## 示例 请参见CREATE FUNCTION的[示例](create_function.md#zh-cn_topic_0283136560_zh-cn_topic_0237122104_zh-cn_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821)。 ## 相关链接 [CREATE PROCEDURE](create_procedure.md),[DROP PROCEDURE](drop_procedure.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_publication.md --- # ALTER PUBLICATION ## Function Description **ALTER PUBLICATION** alters the attributes of a publication. ## Precautions Only the owner of a publication and the system administrator can execute **ALTER PUBLICATION**. Only the direct or indirect members of the new owner role can change the owner. The new owner must have the **CREATE** permission on the current database. In addition, the new owner published by **FOR ALL TABLES** must be the system administrator. However, the system administrator can change the ownership of a publication while avoiding these restrictions. ## Syntax * Replace the currently published table with a specified table. ``` ALTER PUBLICATION name SET TABLE table_name [, ...] ``` * Add one or more tables to a publication. ``` ALTER PUBLICATION name ADD TABLE table_name [, ...] ``` * Delete one or more tables from a publication. ``` ALTER PUBLICATION name DROP TABLE table_name [, ...] ``` * Change all publication attributes specified in **CREATE PUBLICATION**. Retain previous settings for attributes that are not mentioned. ``` ALTER PUBLICATION name SET ( publication_parameter [= value] [, ... ] ) ``` * Change the owner of a publication. ``` ALTER PUBLICATION name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * Change the name of a publication. ``` ALTER PUBLICATION name RENAME TO new_name ``` ## **Parameter Description** * **name** Specifies the name of the publication to be modified. * **table\_name** Specifies the name of an existing table. * **SET ( publication\_parameter \[= value] \[, ... ] )** Modifies the publication parameters initially set by **CREATE PUBLICATION**. * **new\_owner** Specifies the username of the new owner of a publication. * **new\_name** Specifies the new name of a publication. ## Example For details, see [Example](create_publication.md#section109371845154215). ## Helpful Links [CREATE PUBLICATION](create_publication.md), [DROP PUBLICATION](drop_publication.md) --- --- url: /en/docs/latest/sql_reference/alter_publication.md --- # ALTER PUBLICATION ## Function **ALTER PUBLICATION** alters the attributes of a publication. ## Precautions Only the owner of a publication and the system administrator can execute **ALTER PUBLICATION**. Only the direct or indirect members of the new owner role can change the owner. The new owner must have the **CREATE** permission on the current database. In addition, the new owner published by **FOR ALL TABLES** must be the system administrator. However, the system administrator can change the ownership of a publication while avoiding these restrictions. ## Syntax * Replace the currently published table with a specified table. ``` ALTER PUBLICATION name SET TABLE table_name [, ...] ``` * Add one or more tables to a publication. ``` ALTER PUBLICATION name ADD TABLE table_name [, ...] ``` * Delete one or more tables from a publication. ``` ALTER PUBLICATION name DROP TABLE table_name [, ...] ``` * Change all publication attributes specified in **CREATE PUBLICATION**. Retain previous settings for attributes that are not mentioned. ``` ALTER PUBLICATION name SET ( publication_parameter [= value] [, ... ] ) ``` * Change the owner of a publication. ``` ALTER PUBLICATION name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * Change the name of a publication. ``` ALTER PUBLICATION name RENAME TO new_name ``` ## Parameter Description * **name** Specifies the name of the publication to be modified. * **table\_name** Specifies the name of an existing table. * **SET ( publication\_parameter \[= value] \[, ... ] )** Modifies the publication parameters initially set by **CREATE PUBLICATION**. * **new\_owner** Specifies the username of the new owner of a publication. * **new\_name** Specifies the new name of a publication. ## Examples For details, see [Examples](create_publication.md#section109371845154215). ## Helpful Links [CREATE PUBLICATION](create_publication.md) and [DROP PUBLICATION](drop_publication.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_publication.md --- # ALTER PUBLICATION ## 功能描述 更改发布PUBLICATION的属性。 ## 注意事项 发布的属主和系统管理员才能执行ALTER PUBLICATION。新所有者角色的直接或间接成员才可以改变所有者。新的所有者必须在当前数据库上拥有CREATE权限。此外,FOR ALL TABLES发布的新所有者必须是系统管理员。但是,系统管理员可以在避开这些限制的情况下更改发布的所有权。 ## 语法格式 * 用指定的表替换当前发布的表。 ``` ALTER PUBLICATION name SET TABLE table_name [, ...] ``` * 从发布中添加一个或多个表。 ``` ALTER PUBLICATION name ADD TABLE table_name [, ...] ``` * 从发布中删除一个或多个表。 ``` ALTER PUBLICATION name DROP TABLE table_name [, ...] ``` * 改变在CREATE PUBLICATION中指定的所有发布属性,未提及的属性保留其之前的设置。 ``` ALTER PUBLICATION name SET ( publication_parameter [= value] [, ... ] ) ``` * 更改发布的所有者。 ``` ALTER PUBLICATION name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * 更改发布的名称。 ``` ALTER PUBLICATION name RENAME TO new_name ``` ## **参数说明** * **name** 待修改的发布的名称。 * **table\_name** 现有表的名称。 * **SET ( publication\_parameter \[= value] \[, ... ] )。** 该子句修改最初由CREATE PUBLICATION设置的发布参数。 * **new\_owner** 发布的新所有者的用户名。 * **new\_name** 发布的新名称。 ## 示例 详情请参见[示例](create_publication.md#section109371845154215)。 ## 相关链接 [CREATE PUBLICATION](create_publication.md),[DROP PUBLICATION](drop_publication.md) --- --- url: /zh/docs/latest/sql_reference/alter_publication.md --- # ALTER PUBLICATION ## 功能描述 更改发布PUBLICATION的属性。 ## 注意事项 发布的属主和系统管理员才能执行ALTER PUBLICATION。新所有者角色的直接或间接成员才可以改变所有者。新的所有者必须在当前数据库上拥有CREATE权限。此外,FOR ALL TABLES发布的新所有者必须是系统管理员。但是,系统管理员可以在避开这些限制的情况下更改发布的所有权。 ## 语法格式 * 用指定的表替换当前发布的表。 ``` ALTER PUBLICATION name SET TABLE table_name [, ...] ``` * 从发布中添加一个或多个表。 ``` ALTER PUBLICATION name ADD TABLE table_name [, ...] ``` * 从发布中删除一个或多个表。 ``` ALTER PUBLICATION name DROP TABLE table_name [, ...] ``` * 改变在CREATE PUBLICATION中指定的所有发布属性,未提及的属性保留其之前的设置。 ``` ALTER PUBLICATION name SET ( publication_parameter [= value] [, ... ] ) ``` * 更改发布的所有者。 ``` ALTER PUBLICATION name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * 更改发布的名称。 ``` ALTER PUBLICATION name RENAME TO new_name ``` ## **参数说明** * **name** 待修改的发布的名称。 * **table\_name** 现有表的名称。 * **SET ( publication\_parameter \[= value] \[, ... ] )。** 该子句修改最初由CREATE PUBLICATION设置的发布参数。 * **new\_owner** 发布的新所有者的用户名。 * **new\_name** 发布的新名称。 ## 示例 详情请参见[示例](create_publication.md#section109371845154215)。 ## 相关链接 [CREATE PUBLICATION](create_publication.md),[DROP PUBLICATION](drop_publication.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_resource_label.md --- # ALTER RESOURCE LABEL ## Function **ALTER RESOURCE LABEL** modifies resource labels. ## Precautions Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. ## Syntax ``` ALTER RESOURCE LABEL label_name (ADD|REMOVE) label_item_list[, ...]*; ``` * label\_item\_list ``` resource_type(resource_path[, ...]*) ``` * resource\_type ``` TABLE | COLUMN | SCHEMA | VIEW | FUNCTION ``` ## Parameter Description * **label\_name** Specifies the resource label name. Value range: a string. It must comply with the naming convention. * **resource\_type** Specifies the type of database resources to be labeled. * **resource\_path** Specifies the path of database resources. ## Examples ``` -- Create basic table table_for_label. openGauss=# CREATE TABLE table_for_label(col1 int, col2 text); -- Create resource label table_label. openGauss=# CREATE RESOURCE LABEL table_label ADD COLUMN(table_for_label.col1); -- Attach resource label table_label to col2. openGauss=# ALTER RESOURCE LABEL table_label ADD COLUMN(table_for_label.col2) -- Remove table_label from an item. openGauss=# ALTER RESOURCE LABEL table_label REMOVE COLUMN(table_for_label.col1); ``` ## Helpful Links [CREATE RESOURCE LABEL](create_resource_label.md) and [DROP RESOURCE LABEL](drop_resource_label.md) --- --- url: /en/docs/latest/sql_reference/alter_resource_label.md --- # ALTER RESOURCE LABEL ## Function **ALTER RESOURCE LABEL** modifies resource labels. ## Precautions Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. ## Syntax ``` ALTER RESOURCE LABEL label_name (ADD|REMOVE) label_item_list[, ...]*; ``` * label\_item\_list ``` resource_type(resource_path[, ...]*) ``` * resource\_type ``` TABLE | COLUMN | SCHEMA | VIEW | FUNCTION ``` ## Parameter Description * **label\_name** Specifies the resource label name. Value range: a string. It must comply with the naming convention. * **resource\_type** Specifies the type of database resources to be labeled. * **resource\_path** Specifies the path of database resources. ## Examples ``` -- Create basic table table_for_label. openGauss=# CREATE TABLE table_for_label(col1 int, col2 text); -- Create resource label table_label. openGauss=# CREATE RESOURCE LABEL table_label ADD COLUMN(table_for_label.col1); -- Attach resource label table_label to col2. openGauss=# ALTER RESOURCE LABEL table_label ADD COLUMN(table_for_label.col2) -- Remove table_label from an item. openGauss=# ALTER RESOURCE LABEL table_label REMOVE COLUMN(table_for_label.col1); ``` ## Helpful Links [CREATE RESOURCE LABEL](create_resource_label.md) and [DROP RESOURCE LABEL](drop_resource_label.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_resource_label.md --- # ALTER RESOURCE LABEL ## 功能描述 修改资源标签。 ## 注意事项 只有poladmin,sysadmin或初始用户才能执行此操作。 ## 语法格式 ``` ALTER RESOURCE LABEL label_name (ADD|REMOVE) label_item_list[, ...]*; ``` * label\_item\_list: ``` resource_type(resource_path[, ...]*) ``` * resource\_type: ``` TABLE | COLUMN | SCHEMA | VIEW | FUNCTION ``` ## 参数说明 * **label\_name** 资源标签名称。 取值范围:字符串,要符合标识符的命名规范。 * **resource\_type** 指的是要标记的数据库资源类型。 * **resource\_path** 指的是描述具体的数据库资源的路径。 ## 示例 ``` --创建基本表table_for_label。 openGauss=# CREATE TABLE table_for_label(col1 int, col2 text); --创建资源标签table_label。 openGauss=# CREATE RESOURCE LABEL table_label ADD COLUMN(table_for_label.col1); --将col2添加至资源标签table_label中 openGauss=# ALTER RESOURCE LABEL table_label ADD COLUMN(table_for_label.col2); --将资源标签table_label中的一项移除 openGauss=# ALTER RESOURCE LABEL table_label REMOVE COLUMN(table_for_label.col1); ``` ## 相关链接 [CREATE RESOURCE LABEL](create_resource_label.md),,[DROP RESOURCE LABEL](drop_resource_label.md)。 --- --- url: /zh/docs/latest/sql_reference/alter_resource_label.md --- # ALTER RESOURCE LABEL ## 功能描述 修改资源标签。 ## 注意事项 只有poladmin、 sysadmin或初始用户才能执行此操作。 ## 语法格式 ``` ALTER RESOURCE LABEL label_name (ADD|REMOVE) label_item_list[, ...]*; ``` * label\_item\_list: ``` resource_type(resource_path[, ...]*) ``` * resource\_type: ``` TABLE | COLUMN | SCHEMA | VIEW | FUNCTION ``` ## 参数说明 * **label\_name** 资源标签名称。 取值范围:字符串,要符合标识符的命名规范。 * **resource\_type** 指的是要标记的数据库资源类型。 * **resource\_path** 指的是描述具体的数据库资源的路径。 ## 示例 ``` --创建基本表table_for_label。 openGauss=# CREATE TABLE table_for_label(col1 int, col2 text); --创建资源标签table_label。 openGauss=# CREATE RESOURCE LABEL table_label ADD COLUMN(table_for_label.col1); --将col2添加至资源标签table_label中 openGauss=# ALTER RESOURCE LABEL table_label ADD COLUMN(table_for_label.col2); --将资源标签table_label中的一项移除 openGauss=# ALTER RESOURCE LABEL table_label REMOVE COLUMN(table_for_label.col1); ``` ## 相关链接 [CREATE RESOURCE LABEL](create_resource_label.md),[DROP RESOURCE LABEL](drop_resource_label.md)。 --- --- url: /en/docs/latest-lite/sql_reference/alter_resource_pool.md --- # ALTER RESOURCE POOL ## Function **ALTER RESOURCE POOL** changes the Cgroup of a resource pool. ## Precautions Only a user with the **ALTER** permission on the current database can perform this operation. ## Syntax ``` ALTER RESOURCE POOL pool_name WITH ({MEM_PERCENT= pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='io_priority'}[, ... ]); ``` ## Parameter Description * **pool\_name** Specifies the name of a resource pool. The name of the resource pool is the name of an existing resource pool. Value range: a string. It must comply with the identifier naming convention. * **group\_name** Specifies the name of a Cgroup. > \[!NOTE]NOTE > > * You can use either double quotation marks ("") or single quotation marks ('') in the syntax when setting the name of a Cgroup. > * The value of **group\_name** is case-sensitive. > * If **group\_name** is not specified, the string "Medium" will be used by default in the syntax, indicating the **Medium** Timeshare Cgroup under **DefaultClass**. > * If a database administrator specifies a Workload Cgroup under **Class**, for example, **control\_group** set to **class1:workload1**, the resource pool will be associated with the **workload1** Cgroup under **class1**. The level of the Workload Cgroup can also be specified. For example, **control\_group** is set to **class1:workload1:1**. > * If a database user specifies the Timeshare Cgroup string (**Rush**, **High**, **Medium**, or **Low**) in the syntax, for example, **control\_group** is set to **High**, the resource pool will be associated with the **High** Timeshare Cgroup under **DefaultClass**. Value range: an existing Cgroup. * **stmt** Specifies the maximum number of statements that can be concurrently executed in a resource pool. Value range: numeric data ranging from –1 to 2147483647 * **dop** Specifies the maximum statement concurrency degree for a resource pool, equivalent to the number of threads that can be created for executing a statement. Value range: numeric data ranging from 1 to 64 * **memory\_size** Specifies the maximum memory size of a resource pool. Value range: a string from 1 KB to 2047 GB * **mem\_percent** Specifies the proportion of available resource pool memory to the total memory or group user memory. In multi-tenant scenarios, the value of **mem\_percent** of group users or service users ranges from 1 to 100. The default value is **20**. In common scenarios, the value of **mem\_percent** of common users is an integer ranging from 0 to 100. The default value is **0**. > \[!NOTE]NOTE > When both **mem\_percent** and **memory\_limit** are specified, only **mem\_percent** takes effect. * **io\_limits** Specifies the upper limit of IOPS in a resource pool. The IOPS is counted by ones for column storage and by 10 thousands for row storage. * **io\_priority** Specifies the I/O priority for jobs that consume many I/O resources. It takes effect when the I/O usage reaches 90%. There are three priorities: **Low**, **Medium**, and **High**. If you do not want to control I/O resources, use the default value **None**. > \[!NOTE]NOTE > The settings of **io\_limits** and **io\_priority** are valid only for complex jobs, such as batch import (using **INSERT INTO SELECT**, **COPY FROM**, or **CREATE TABLE AS**), complex queries involving over 500 MB data on each DN, and **VACUUM FULL**. ## Examples The example assumes that the user has created the **class1** Cgroup and three Workload Cgroups under **class1**: **Low**, **wg1**, and **wg2**. ``` -- Create a resource pool. openGauss=# CREATE RESOURCE POOL pool1; -- Update a resource pool and set its Cgroup to a High Timeshare Workload Cgroup under DefaultClass. openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="High"); -- Update a resource pool and set its Cgroup to a Low Timeshare Workload Cgroup under class1. openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:Low"); -- Update a resource pool and set its Cgroup to a wg1 Workload Cgroup under class1. openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:wg1"); -- Update a resource pool and set its Cgroup to a wg2 Workload Cgroup under class1. openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:wg2:3"); -- Delete the resource pool pool1. openGauss=# DROP RESOURCE POOL pool1; ``` ## Helpful Links [CREATE RESOURCE POOL](create_resource_pool.md) and [DROP RESOURCE POOL](drop_resource_pool.md) --- --- url: /en/docs/latest/sql_reference/alter_resource_pool.md --- # ALTER RESOURCE POOL ## Function **ALTER RESOURCE POOL** changes the Cgroup of a resource pool. ## Precautions Only SYSADMIN and VCADMIN users can modify resource pools. ## Syntax ``` ALTER RESOURCE POOL pool_name WITH ({MEM_PERCENT= pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='io_priority'} [, ... ]); ``` ## Parameter Description * **pool\_name** Specifies the name of a resource pool. The name of the resource pool is the name of an existing resource pool. Value range: a string. It must comply with the identifier naming convention. * **group\_name** Specifies the name of a Cgroup. > \[!NOTE]NOTE > > * You can use either double quotation marks ("") or single quotation marks ('') in the syntax when setting the name of a Cgroup. > * The value of **group\_name** is case-sensitive. > * If **group\_name** is not specified, the string "Medium" will be used by default in the syntax, indicating the **Medium** Timeshare Cgroup under **DefaultClass**. > * If a database administrator specifies a Workload Cgroup under **Class**, for example, **control\_group** set to **class1:workload1**, the resource pool will be associated with the **workload1** Cgroup under **class1**. The level of the Workload Cgroup can also be specified. For example, **control\_group** is set to **class1:workload1:1**. > * If a database user specifies the Timeshare Cgroup string (**Rush**, **High**, **Medium**, or **Low**) in the syntax, for example, **control\_group** is set to **High**, the resource pool will be associated with the **High** Timeshare Cgroup under **DefaultClass**. Value range: an existing Cgroup. * **stmt** Specifies the maximum number of statements that can be concurrently executed in a resource pool. Value range: numeric data ranging from –1 to 2147483647 * **dop** Specifies the maximum statement concurrency degree for a resource pool, equivalent to the number of threads that can be created for executing a statement. Value range: numeric data ranging from 1 to 64 * **memory\_size** Specifies the maximum memory size of a resource pool. Value range: a string from 1 KB to 2047 GB * **mem\_percent** Specifies the proportion of available resource pool memory to the total memory or group user memory. In multi-tenant scenarios, the value of **mem\_percent** of group users or service users ranges from 1 to 100. The default value is **20**. In common scenarios, the value of **mem\_percent** of common users is an integer ranging from 0 to 100. The default value is **0**. > \[!NOTE]NOTE > When both **mem\_percent** and **memory\_limit** are specified, only **mem\_percent** takes effect. * **io\_limits** Specifies the upper limit of IOPS in a resource pool. The IOPS is counted by ones for column storage and by 10 thousands for row storage. * **io\_priority** Specifies the I/O priority for jobs that consume many I/O resources. It takes effect when the I/O usage reaches 90%. There are three priorities: **Low**, **Medium**, and **High**. If you do not want to control I/O resources, use the default value **None**. > \[!NOTE]NOTE > The settings of **io\_limits** and **io\_priority** are valid only for complex jobs, such as batch import (using **INSERT INTO SELECT**, **COPY FROM**, or **CREATE TABLE AS**), complex queries involving over 500 MB data on each DN, and **VACUUM FULL**. ## Examples The example assumes that the user has created the **class1** Cgroup and three Workload Cgroups under **class1**: **Low**, **wg1**, and **wg2**. ``` -- Create a resource pool. openGauss=# CREATE RESOURCE POOL pool1; -- Update a resource pool and set its Cgroup to a High Timeshare Workload Cgroup under DefaultClass. openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="High"); -- Update a resource pool and set its Cgroup to a Low Timeshare Workload Cgroup under class1. openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:Low"); -- Update a resource pool and set its Cgroup to a wg1 Workload Cgroup under class1. openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:wg1"); -- Update a resource pool and set its Cgroup to a wg2 Workload Cgroup under class1. openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:wg2:3"); -- Delete the resource pool pool1. openGauss=# DROP RESOURCE POOL pool1; ``` ## Helpful Links [CREATE RESOURCE POOL](create_resource_pool.md) and [DROP RESOURCE POOL](drop_resource_pool.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_resource_pool.md --- # ALTER RESOURCE POOL ## 功能描述 修改一个资源池,指定其他控制组。 ## 注意事项 只要用户对当前数据库有ALTER权限,就可以修改资源池。 ## 语法格式 ``` ALTER RESOURCE POOL pool_name WITH ({MEM_PERCENT= pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='io_priority'}[, ... ]); ``` ## 参数说明 * **pool\_name** 资源池名称。 资源池名称为已创建的资源池。 取值范围:字符串,要符合标识符的命名规范。 * **group\_name** 控制组名称。 > \[!NOTE]说明 > > * 设置控制组名称时,语法可以使用双引号,也可以使用单引号。 > * group\_name对大小写敏感。 > * 不指定group\_name时,默认指定的字符串为 "Medium",代表指定DefaultClass控制组的"Medium" Timeshare控制组。 > * 若数据库管理员指定自定义Class组下的Workload控制组,如control\_group的字符串为:"class1:workload1";代表此资源池指定到class1控制组下的workload1控制组。也可同时指定Workload控制组的层次,如control\_group的字符串为:"class1:workload1:1"。 > * 若数据库用户指定Timeshare控制组代表的字符串,即"Rush"、"High"、"Medium"或"Low"其中一种,如control\_group的字符串为"High";代表资源池指定到DefaultClass控制组下的"High" Timeshare控制组。 取值范围:已创建的控制组。 * **stmt** 资源池语句执行的最大并发数量。 取值范围:数值型,-1~2147483647‬。 * **dop** 资源池最大并发度,语句执行时能够创建的最多线程数量。 取值范围:数值型,1~64‬。 * **memory\_size** 资源池最大使用内存。 取值范围:字符串,内容范围1KB~2047GB。 * **mem\_percent** 资源池可用内存占全部内存或者组用户内存使用的比例。 在多租户场景下,组用户和业务用户的mem\_percent范围为1-100的整数,默认为20。 在普通场景下,普通用户的mem\_percent范围为0-100的整数,默认值为0。 > \[!NOTE]说明 > mem\_percent和memory\_limit同时指定时,只有mem\_percent起作用。 * **io\_limits** 资源池每秒可触发IO次数上限。 对于行存,以万次为单位计数,而列存则以正常次数计数。 * **io\_priority** IO利用率高达90%时,重消耗IO作业进行IO资源管控时关联的优先级等级。 包括三档可选:Low、Medium和High。不控制时可设置为None,默认为None。 > \[!NOTE]说明 > > io\_limits和io\_priority的设置都仅对复杂作业有效。包括批量导入(INSERT INTO SELECT,COPY FROM,CREATE TABLE AS等),单DN数据量大约超过500MB的复杂查询和VACUUM FULL等操作。 ## 示例 本示例假定用户已成功创建自定义的class1控制组及其下属的Low、wg1、wg2 三个Workload控制组。 ``` --创建一个资源池。 openGauss=# CREATE RESOURCE POOL pool1; --更新一个资源池,其控制组指定为"DefaultClass"组下属的"High" Timeshare Workload控制组。 openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="High"); --更新一个资源池,其控制组指定为"class1"组下属的"Low" Timeshare Workload控制组。 openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:Low"); --更新一个资源池,其控制组指定为"class1"组下属的"wg1" Workload控制组。 openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:wg1"); --更新一个资源池,其控制组指定为"class1"组下属的"wg2" Workload控制组。 openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:wg2:3"); --删除资源池pool1。 openGauss=# DROP RESOURCE POOL pool1; ``` ## 相关链接 [CREATE RESOURCE POOL](create_resource_pool.md),[DROP RESOURCE POOL](drop_resource_pool.md) --- --- url: /zh/docs/latest/sql_reference/alter_resource_pool.md --- # ALTER RESOURCE POOL ## 功能描述 修改一个资源池,指定其他控制组。 ## 注意事项 只有SYSADMIN、VCADMIN可以修改资源池。 ## 语法格式 ``` ALTER RESOURCE POOL pool_name WITH ({MEM_PERCENT= pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='io_priority'} [, ... ]); ``` ## 参数说明 * **pool\_name** 资源池名称。 资源池名称为已创建的资源池。 取值范围:字符串,要符合标识符的命名规范。 * **group\_name** 控制组名称。 > \[!NOTE]说明 > > * 设置控制组名称时,语法可以使用双引号,也可以使用单引号。 > * group\_name对大小写敏感。 > * 若数据库管理员指定自定义Class组下的Workload控制组,如control\_group的字符串为:“class1:workload1”;代表此资源池指定到class1控制组下的workload1控制组。也可同时指定Workload控制组的层次,如control\_group的字符串为:“class1:workload1:1”。 > * 若数据库用户指定Timeshare控制组代表的字符串,即“Rush”、“High”、“Medium”或“Low”其中一种,如control\_group的字符串为“High”;代表资源池指定到DefaultClass控制组下的“High” Timeshare控制组。 取值范围:已创建的控制组。 * **stmt** 资源池语句执行的最大并发数量。 取值范围:数值型,-1~2147483647‬。 * **dop** 资源池最大并发度,语句执行时能够创建的最多线程数量。 取值范围:数值型,1~64‬。 * **memory\_size** 资源池最大使用内存。 取值范围:字符串,内容范围1KB~2047GB。 * **mem\_percent** 资源池可用内存占全部内存或者组用户内存使用的比例。 在多租户场景下,组用户和业务用户的mem\_percent范围为1-100的整数,默认为20。 在普通场景下,普通用户的mem\_percent范围为0-100的整数,默认值为0。 > \[!NOTE]说明 > mem\_percent和memory\_limit同时指定时,只有mem\_percent起作用。 * **io\_limits** 资源池每秒可触发IO次数上限。 对于行存,以万次为单位计数,而列存则以正常次数计数。 * **io\_priority** IO利用率高达90%时,重消耗IO作业进行IO资源管控时关联的优先级等级。 包括三档可选:Low、Medium和High。不控制时可设置为None,默认为None。 > \[!NOTE]说明 > io\_limits和io\_priority的设置都仅对复杂作业有效。包括批量导入(INSERT INTO SELECT、COPY FROM、CREATE TABLE AS等),单DN数据量大约超过500MB的复杂查询和VACUUM FULL等操作。 ## 示例 本示例假定用户已成功创建自定义的class1控制组及其下属的Low、wg1、wg2 三个Workload控制组。 ``` --创建一个资源池。 openGauss=# CREATE RESOURCE POOL pool1; --更新一个资源池,其控制组指定为"DefaultClass"组下属的"High" Timeshare Workload控制组。 openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="High"); --更新一个资源池,其控制组指定为"class1"组下属的"Low" Timeshare Workload控制组。 openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:Low"); --更新一个资源池,其控制组指定为"class1"组下属的"wg1" Workload控制组。 openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:wg1"); --更新一个资源池,其控制组指定为"class1"组下属的"wg2" Workload控制组。 openGauss=# ALTER RESOURCE POOL pool1 WITH (CONTROL_GROUP="class1:wg2:3"); --删除资源池pool1。 openGauss=# DROP RESOURCE POOL pool1; ``` ## 相关链接 [CREATE RESOURCE POOL](create_resource_pool.md),[DROP RESOURCE POOL](drop_resource_pool.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_role.md --- # ALTER ROLE ## Function **ALTER ROLE** modifies role attributes. ## Precautions None ## Syntax * Modify the permissions of a role. ``` ALTER ROLE role_name [ [ WITH ] option [ ... ] ]; ``` The **option** clause for granting permissions is as follows: ``` {CREATEDB | NOCREATEDB} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {AUDITADMIN | NOAUDITADMIN} | {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {USEFT | NOUSEFT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password' [EXPIRED] | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY 'password' [ REPLACE 'old_password' | EXPIRED ] | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | PGUSER ``` * Rename a role. ``` ALTER ROLE role_name RENAME TO new_name; ``` * Lock or unlock. ``` ALTER ROLE role_name ACCOUNT { LOCK | UNLOCK }; ``` * Set parameters for a role. ``` ALTER ROLE role_name [ IN DATABASE database_name ] SET configuration_parameter {{ TO | = } { value | DEFAULT } | FROM CURRENT}; ``` * Reset parameters for a role. ``` ALTER ROLE role_name [ IN DATABASE database_name ] RESET {configuration_parameter|ALL}; ``` ## Parameter Description * **role\_name** Specifies a role name. Value range: an existing username * **IN DATABASE database\_name** Modifies the parameters of a role in a specified database. * **SET configuration\_parameter** Sets parameters for a role. Session parameters modified by **ALTER ROLE** apply to a specified role and take effect in the next session triggered by the role. Value range: For details about the values of **configuration\_parameter** and **value**, see [SET](set.md). **DEFAULT**: clears the value of **configuration\_parameter**. **configuration\_parameter** will inherit the default value of the new session generated for the role. **FROM CURRENT**: uses the value of **configuration\_parameter** of the current session. * **RESET configuration\_parameter/ALL** Clears the value of **configuration\_parameter**. The statement has the same effect as that of **SET configuration\_parameter TO DEFAULT**. Value range: **ALL** indicates that the values of all parameters are cleared. * **ACCOUNT LOCK | ACCOUNT UNLOCK** * **ACCOUNT LOCK**: locks an account to prevent it from logging in to the database. * **ACCOUNT UNLOCK**: unlocks an account and allows the account to log in to the database. * **PGUSER** In the current version, the **PGUSER** attribute of a role cannot be modified. * **PASSWORD/IDENTIFIED BY**'password' Resets or changes the user password. Except the initial user, other administrators and common users need to enter the correct old password when changing their own passwords. Only the initial user, the system administrator (sysadmin), or users who have the permission to create users (CREATEROLE) can reset the password of a common user without entering the old password. The initial user can reset passwords of system administrators. System administrators cannot reset passwords of other system administrators. * **EXPIRED** Invalidates the password. Only initial users, system administrators (sysadmin), and users who have the permission to create users (CREATEROLE) can invalidate user passwords. System administrators can invalidate their own passwords or the passwords of other system administrators. Any user cannot invalidate the password of the initial user. The user whose password is invalid can log in to the database but cannot perform the query operation. The query operation can be performed only after the password is changed or the administrator resets the password. For details about other parameters, see [Parameter Description](create_role.md#en-us_topic_0283136858_en-us_topic_0237122112_en-us_topic_0059778189_s5a43ec5742a742089e2c302063de7fe4) in **CREATE ROLE**. ## Examples See [Examples](create_role.md#en-us_topic_0283136858_en-us_topic_0237122112_en-us_topic_0059778189_s0dea2f90b8474387aff0ab3f366a611e) in **CREATE ROLE**. ## Helpful Links [CREATE ROLE](create_role.md), [DROP ROLE](drop_role.md), and [SET](set.md) --- --- url: /en/docs/latest/sql_reference/alter_role.md --- # ALTER ROLE ## Function **ALTER ROLE** modifies role attributes. ## Precautions None ## Syntax * Modify the permissions of a role. ``` ALTER ROLE role_name [ [ WITH ] option [ ... ] ]; ``` The **option** clause for granting permissions is as follows: ``` {CREATEDB | NOCREATEDB} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {AUDITADMIN | NOAUDITADMIN} | {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {USEFT | NOUSEFT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password' [EXPIRED] | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY 'password' [ REPLACE 'old_password' | EXPIRED ] | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | PGUSER ``` * Rename a role. ``` ALTER ROLE role_name RENAME TO new_name; ``` * Lock or unlock. ``` ALTER ROLE role_name ACCOUNT { LOCK | UNLOCK }; ``` * Set parameters for a role. ``` ALTER ROLE role_name [ IN DATABASE database_name ] SET configuration_parameter {{ TO | = } { value | DEFAULT } | FROM CURRENT}; ``` * Reset parameters for a role. ``` ALTER ROLE role_name [ IN DATABASE database_name ] RESET {configuration_parameter|ALL}; ``` ## Parameter Description * **role\_name** Specifies a role name. Value range: an existing username * **IN DATABASE database\_name** Modifies the parameters of a role in a specified database. * **SET configuration\_parameter** Sets parameters for a role. Session parameters modified by **ALTER ROLE** apply to a specified role and take effect in the next session triggered by the role. Value range: For details about the values of **configuration\_parameter** and **value**, see [SET](set.md). **DEFAULT**: clears the value of **configuration\_parameter**. **configuration\_parameter** will inherit the default value of the new session generated for the role. **FROM CURRENT**: uses the value of **configuration\_parameter** of the current session. * **RESET configuration\_parameter/ALL** Clears the value of **configuration\_parameter**. The statement has the same effect as that of **SET configuration\_parameter TO DEFAULT**. Value range: **ALL** indicates that the values of all parameters are cleared. * **ACCOUNT LOCK | ACCOUNT UNLOCK** * **ACCOUNT LOCK**: locks an account to prevent it from logging in to the database. * **ACCOUNT UNLOCK**: unlocks an account and allows the account to log in to the database. * **PGUSER** In the current version, the **PGUSER** attribute of a role cannot be modified. * **PASSWORD/IDENTIFIED BY**'password' Resets or changes the user password. Except the initial user, other administrators and common users need to enter the correct old password when changing their own passwords. Only the initial user, the system administrator (sysadmin), or users who have the permission to create users (CREATEROLE) can reset the password of a common user without entering the old password. The initial user can reset passwords of system administrators. System administrators cannot reset passwords of other system administrators. * **EXPIRED** Invalidates the password. Only initial users, system administrators (sysadmin), and users who have the permission to create users (CREATEROLE) can invalidate user passwords. System administrators can invalidate their own passwords or the passwords of other system administrators. The password of the initial user cannot be invalidated. The user whose password is invalid can log in to the database but cannot perform the query operation. The query operation can be performed only after the password is changed or the administrator resets the password. For details about other parameters, see [Parameter Description](create_role.md#en-us_topic_0283136858_en-us_topic_0237122112_en-us_topic_0059778189_s5a43ec5742a742089e2c302063de7fe4) in **CREATE ROLE**. ## Examples See [Examples](create_role.md#en-us_topic_0283136858_en-us_topic_0237122112_en-us_topic_0059778189_s0dea2f90b8474387aff0ab3f366a611e) in **CREATE ROLE**. ## Helpful Links [CREATE ROLE](create_role.md), [DROP ROLE](drop_role.md), and [SET](set.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_role.md --- # ALTER ROLE ## 功能描述 修改角色属性。 ## 注意事项 无。 ## 语法格式 * 修改角色的权限。 ``` ALTER ROLE role_name [ [ WITH ] option [ ... ] ]; ``` 其中权限项子句option为。 ``` {CREATEDB | NOCREATEDB} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {AUDITADMIN | NOAUDITADMIN} | {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {USEFT | NOUSEFT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password' [EXPIRED] | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY 'password' [ REPLACE 'old_password' | EXPIRED ] | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | PGUSER ``` * 修改角色的名称。 ``` ALTER ROLE role_name RENAME TO new_name; ``` * 锁定或解锁。 ``` ALTER ROLE role_name ACCOUNT { LOCK | UNLOCK }; ``` * 设置角色的配置参数。 ``` ALTER ROLE role_name [ IN DATABASE database_name ] SET configuration_parameter {{ TO | = } { value | DEFAULT } | FROM CURRENT}; ``` * 重置角色的配置参数。 ``` ALTER ROLE role_name [ IN DATABASE database_name ] RESET {configuration_parameter|ALL}; ``` ## 参数说明 * **role\_name** 现有角色名。 取值范围:已存在的用户名。 * **IN DATABASE database\_name** 表示修改角色在指定数据库上的参数。 * **SET configuration\_parameter** 设置角色的参数。ALTER ROLE中修改的会话参数只针对指定的角色,且在下一次该角色启动的会话中有效。 取值范围: configuration\_parameter和value的取值请参见[SET](set.md)。 DEFAULT:表示清除configuration\_parameter参数的值,configuration\_parameter参数的值将继承本角色新产生的SESSION的默认值。 FROM CURRENT:取当前会话中的值设置为configuration\_parameter参数的值。 * **RESET configuration\_parameter/ALL** 清除configuration\_parameter参数的值。与SET configuration\_parameter TO DEFAULT的效果相同。 取值范围:ALL表示清除所有参数的值。 * **ACCOUNT LOCK | ACCOUNT UNLOCK** * ACCOUNT LOCK:锁定帐户,禁止登录数据库。 * ACCOUNT UNLOCK:解锁帐户,允许登录数据库。 * **PGUSER** 当前版本不允许修改角色的PGUSER属性 * **PASSWORD/IDENTIFIED BY**'password' 重置或修改用户密码。除了初始用户外其他管理员或普通用户修改自己的密码需要输入正确的旧密码。只有初始用户、系统管理员(sysadmin)或拥有创建用户(CREATEROLE)权限的用户才可以重置普通用户密码,无需输入旧密码。初始用户可以重置系统管理员的密码,系统管理员不允许重置其他系统管理员的密码。 * **EXPIRED** 设置密码失效。只有初始用户、系统管理员(sysadmin)或拥有创建用户(CREATEROLE)权限的用户才可以设置用户密码失效,其中系统管理员也可以设置自己或其他系统管理员密码失效。任何用户都不允许设置初始用户密码失效。 密码失效的用户可以登录数据库但不能执行查询操作,只有修改密码或由管理员重置密码后才可以恢复正常查询操作。 其他参数请参见CREATE ROLE的[参数说明](create_role.md#zh-cn_topic_0283136858_zh-cn_topic_0237122112_zh-cn_topic_0059778189_s5a43ec5742a742089e2c302063de7fe4)。 ## 示例 请参见CREATE ROLE的[示例](create_role.md#zh-cn_topic_0283136858_zh-cn_topic_0237122112_zh-cn_topic_0059778189_s0dea2f90b8474387aff0ab3f366a611e)。 ## 相关链接 [CREATE ROLE](create_role.md),[DROP ROLE](drop_role.md),[SET](set.md) --- --- url: /zh/docs/latest/sql_reference/alter_role.md --- # ALTER ROLE ## 功能描述 修改角色属性。 ## 注意事项 无。 ## 语法格式 * 修改角色的权限。 ``` ALTER ROLE role_name [ [ WITH ] option [ ... ] ]; ``` 其中权限项子句option为: ``` {CREATEDB | NOCREATEDB} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {AUDITADMIN | NOAUDITADMIN} | {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {USEFT | NOUSEFT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password' [EXPIRED] | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY 'password' [ REPLACE 'old_password' | EXPIRED ] | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | PGUSER ``` * 修改角色的名称。 ``` ALTER ROLE role_name RENAME TO new_name; ``` * 锁定或解锁。 ``` ALTER ROLE role_name ACCOUNT { LOCK | UNLOCK }; ``` * 设置角色的配置参数。 ``` ALTER ROLE role_name [ IN DATABASE database_name ] SET configuration_parameter {{ TO | = } { value | DEFAULT } | FROM CURRENT}; ``` * 重置角色的配置参数。 ``` ALTER ROLE role_name [ IN DATABASE database_name ] RESET {configuration_parameter|ALL}; ``` ## 参数说明 * **role\_name** 现有角色名。 取值范围:已存在的用户名。 * **IN DATABASE database\_name** 表示修改角色在指定数据库上的参数。 * **SET configuration\_parameter** 设置角色的参数。ALTER ROLE中修改的会话参数只针对指定的角色,且在下一次该角色启动的会话中有效。 取值范围: configuration\_parameter和value的取值请参见[SET](set.md)。 DEFAULT:表示清除configuration\_parameter参数的值,configuration\_parameter参数的值将继承本角色新产生的SESSION的默认值。 FROM CURRENT:取当前会话中的值设置为configuration\_parameter参数的值。 * **RESET configuration\_parameter/ALL** 清除configuration\_parameter参数的值。与SET configuration\_parameter TO DEFAULT的效果相同。 取值范围:ALL表示清除所有参数的值。 * **ACCOUNT LOCK | ACCOUNT UNLOCK** * ACCOUNT LOCK:锁定帐户,禁止登录数据库。 * ACCOUNT UNLOCK:解锁帐户,允许登录数据库。 * **PGUSER** 当前版本不允许修改角色的PGUSER属性。 * **PASSWORD/IDENTIFIED BY**'password' 重置或修改用户密码。除了初始用户外其他管理员或普通用户修改自己的密码需要输入正确的旧密码。只有初始用户、系统管理员(sysadmin)或拥有创建用户(CREATEROLE)权限的用户才可以重置普通用户密码,无需输入旧密码。初始用户可以重置系统管理员的密码,系统管理员不允许重置其他系统管理员的密码。 * **EXPIRED** 设置密码失效。只有初始用户、系统管理员(sysadmin)或拥有创建用户(CREATEROLE)权限的用户才可以设置用户密码失效,其中系统管理员也可以设置自己或其他系统管理员密码失效。任何用户都不允许设置初始用户密码失效。 密码失效的用户可以登录数据库但不能执行查询操作,只有修改密码或由管理员重置密码后才可以恢复正常查询操作。 其他参数请参见CREATE ROLE的[参数说明](create_role.md#zh-cn_topic_0283136858_zh-cn_topic_0237122112_zh-cn_topic_0059778189_s5a43ec5742a742089e2c302063de7fe4)。 ## 示例 请参见CREATE ROLE的[示例](create_role.md#zh-cn_topic_0283136858_zh-cn_topic_0237122112_zh-cn_topic_0059778189_s0dea2f90b8474387aff0ab3f366a611e)。 ## 相关链接 [CREATE ROLE](create_role.md),[DROP ROLE](drop_role.md),[SET](set.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_row_level_security_policy.md --- # ALTER ROW LEVEL SECURITY POLICY ## Function **ALTER ROW LEVEL SECURITY POLICY** modifies an existing row-level access control policy, including the policy name and the users and expressions affected by the policy. ## Precautions Only the table owner or a system administrator can perform this operation. ## Syntax ``` ALTER [ ROW LEVEL SECURITY ] POLICY [ IF EXISTS ] policy_name ON table_name RENAME TO new_policy_name; ALTER [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ TO { role_name | PUBLIC } [, ...] ] [ USING ( using_expression ) ]; ``` ## Parameter Description * policy\_name Specifies the name of a row-level access control policy. * table\_name Specifies the name of a table to which a row-level access control policy is applied. * new\_policy\_name Specifies the new name of a row-level access control policy. * role\_name Specifies names of users affected by a row-level access control policy. PUBLIC indicates that the row-level access control policy will affect all users. * using\_expression Specifies an expression defined for a row-level access control policy. The return value is of the boolean type. ## Examples ``` -- Create the data table all_data. openGauss=# CREATE TABLE all_data(id int, role varchar(100), data varchar(100)); --Create a row-level access control policy to specify that the current user can view only their own data. openGauss=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING(role = CURRENT_USER); openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_rls" USING (((role)::name = "current_user"())) Has OIDs: no Location Nodes: ALL DATANODES Options: orientation=row, compression=no -- Change the name of the all_data_rls policy. openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_rls ON all_data RENAME TO all_data_new_rls; -- Change the users affected by the row-level access control policy. openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data TO alice, bob; openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_new_rls" TO alice,bob USING (((role)::name = "current_user"())) Has OIDs: no Location Nodes: ALL DATANODES Options: orientation=row, compression=no, enable_rowsecurity=true -- Modify the expression defined for the access control policy. openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data USING (id > 100 AND role = current_user); openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_new_rls" TO alice,bob USING (((id > 100) AND ((role)::name = "current_user"()))) Has OIDs: no Location Nodes: ALL DATANODES Options: orientation=row, compression=no, enable_rowsecurity=true ``` ## Helpful Links [CREATE ROW LEVEL SECURITY POLICY](create_row_level_security_policy.md) and [DROP ROW LEVEL SECURITY POLICY](drop_row_level_security_policy.md) --- --- url: /en/docs/latest/sql_reference/alter_row_level_security_policy.md --- # ALTER ROW LEVEL SECURITY POLICY ## Function **ALTER ROW LEVEL SECURITY POLICY** modifies an existing row-level access control policy, including the policy name and the users and expressions affected by the policy. ## Precautions Only the table owner or a system administrator can perform this operation. ## Syntax ``` ALTER [ ROW LEVEL SECURITY ] POLICY [ IF EXISTS ] policy_name ON table_name RENAME TO new_policy_name; ALTER [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ TO { role_name | PUBLIC } [, ...] ] [ USING ( using_expression ) ]; ``` ## Parameter Description * policy\_name Specifies the name of a row-level access control policy. * table\_name Specifies the name of a table to which a row-level access control policy is applied. * new\_policy\_name Specifies the new name of a row-level access control policy. * role\_name Specifies names of users affected by a row-level access control policy. PUBLIC indicates that the row-level access control policy will affect all users. * using\_expression Specifies an expression defined for a row-level access control policy. The return value is of the boolean type. ## Examples ``` -- Create the data table all_data. openGauss=# CREATE TABLE all_data(id int, role varchar(100), data varchar(100)); --Create a row-level access control policy to specify that the current user can view only their own data. openGauss=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING(role = CURRENT_USER); openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_rls" USING (((role)::name = "current_user"())) Has OIDs: no Location Nodes: ALL DATANODES Options: orientation=row, compression=no -- Change the name of the all_data_rls policy. openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_rls ON all_data RENAME TO all_data_new_rls; -- Change the users affected by the row-level access control policy. openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data TO alice, bob; openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_new_rls" TO alice,bob USING (((role)::name = "current_user"())) Has OIDs: no Location Nodes: ALL DATANODES Options: orientation=row, compression=no, enable_rowsecurity=true -- Modify the expression defined for the access control policy. openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data USING (id > 100 AND role = current_user); openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_new_rls" TO alice,bob USING (((id > 100) AND ((role)::name = "current_user"()))) Has OIDs: no Location Nodes: ALL DATANODES Options: orientation=row, compression=no, enable_rowsecurity=true ``` ## Helpful Links [CREATE ROW LEVEL SECURITY POLICY](create_row_level_security_policy.md) and [DROP ROW LEVEL SECURITY POLICY](drop_row_level_security_policy.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_row_level_security_policy.md --- # ALTER ROW LEVEL SECURITY POLICY ## 功能描述 对已存在的行访问控制策略(包括行访问控制策略的名称,行访问控制指定的用户,行访问控制的策略表达式)进行修改。 ## 注意事项 表的所有者或管理员用户才能进行此操作。 ## 语法格式 ``` ALTER [ ROW LEVEL SECURITY ] POLICY [ IF EXISTS ] policy_name ON table_name RENAME TO new_policy_name; ALTER [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ TO { role_name | PUBLIC } [, ...] ] [ USING ( using_expression ) ]; ``` ## 参数说明 * policy\_name 行访问控制策略名称。 * table\_name 行访问控制策略的表名。 * new\_policy\_name 新的行访问控制策略名称。 * role\_name 行访问控制策略应用的数据库用户,可以指定多个用户,PUBLIC表示应用到所有用户。 * using\_expression 行访问控制的表达式,返回值为boolean类型。 ## 示例 ``` --创建数据表all_data openGauss=# CREATE TABLE all_data(id int, role varchar(100), data varchar(100)); --创建行访问控制策略,当前用户只能查看用户自身的数据 openGauss=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING(role = CURRENT_USER); openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_rls" FOR ALL TO public USING (((role)::name = "current_user"())) Has OIDs: no Options: orientation=row, compression=no --修改行访问控制all_data_rls的名称 openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_rls ON all_data RENAME TO all_data_new_rls; --修改行访问控制策略影响的用户 openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data TO alice, bob; openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_new_rls" FOR ALL TO alice,bob USING (((role)::name = "current_user"())) Has OIDs: no Options: orientation=row, compression=no --修改行访问控制策略表达式 openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data USING (id > 100 AND role = current_user); openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_new_rls" FOR ALL TO alice,bob USING (((id > 100) AND ((role)::name = "current_user"()))) Has OIDs: no Options: orientation=row, compression=no ``` ## 相关链接 [CREATE ROW LEVEL SECURITY POLICY](create_row_level_security_policy.md),[DROP ROW LEVEL SECURITY POLICY](drop_row_level_security_policy.md) --- --- url: /zh/docs/latest/sql_reference/alter_row_level_security_policy.md --- # ALTER ROW LEVEL SECURITY POLICY ## 功能描述 对已存在的行访问控制策略(包括行访问控制策略的名称、行访问控制指定的用户、行访问控制的策略表达式)进行修改。 ## 注意事项 表的所有者或管理员用户才能进行此操作。 ## 语法格式 ``` ALTER [ ROW LEVEL SECURITY ] POLICY [ IF EXISTS ] policy_name ON table_name RENAME TO new_policy_name; ALTER [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ TO { role_name | PUBLIC } [, ...] ] [ USING ( using_expression ) ]; ``` ## 参数说明 * policy\_name 行访问控制策略名称。 * table\_name 行访问控制策略的表名。 * new\_policy\_name 新的行访问控制策略名称。 * role\_name 行访问控制策略应用的数据库用户,可以指定多个用户,PUBLIC表示应用到所有用户。 * using\_expression 行访问控制的表达式,返回值为boolean类型。 ## 示例 ``` --创建数据表all_data openGauss=# CREATE TABLE all_data(id int, role varchar(100), data varchar(100)); --创建行访问控制策略,当前用户只能查看用户自身的数据 openGauss=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING(role = CURRENT_USER); openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_rls" FOR ALL TO public USING (((role)::name = "current_user"())) Has OIDs: no Options: orientation=row, compression=no --修改行访问控制all_data_rls的名称 openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_rls ON all_data RENAME TO all_data_new_rls; --修改行访问控制策略影响的用户 openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data TO alice, bob; openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_new_rls" FOR ALL TO alice,bob USING (((role)::name = "current_user"())) Has OIDs: no Options: orientation=row, compression=no --修改行访问控制策略表达式 openGauss=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data USING (id > 100 AND role = current_user); openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_new_rls" FOR ALL TO alice,bob USING (((id > 100) AND ((role)::name = "current_user"()))) Has OIDs: no Options: orientation=row, compression=no ``` ## 相关链接 [CREATE ROW LEVEL SECURITY POLICY](create_row_level_security_policy.md),[DROP ROW LEVEL SECURITY POLICY](drop_row_level_security_policy.md) --- --- url: /en/docs/latest/sql_reference/alter_rule.md --- # ALTER RULE ## Function **ALTER RULE** modifies the definition of a rule. ## Precautions * You must be the owner of the table or view to which the specified rule is applied. * Currently, only the rule name can be modified. ## Syntax ``` ALTER RULE name ON table_name RENAME TO new_name ``` ## Parameter Description * name Name of the rule to be modified. * table\_name Name of the table to which the specified rule is applied. Value range: name of an existing table in the database * new\_name New name of a rule. ## Examples ``` ALTER RULE notify_all ON emp RENAME TO notify_me; ``` --- --- url: /en/docs/latest-lite/sql_reference/alter_schema.md --- # ALTER SCHEMA ## Function **ALTER SCHEMA** alters the attributes of a schema. ## Precautions * Only the owner of a schema or users granted with the ALTER permission on the schema can run the **ALTER SCHEMA** command. The system administrator has this permission by default. To change the owner of a schema, you must be the owner of the schema or system administrator and a member of the new owner role. * Only the initial user is allowed to change the owner of the **pg\_catalog** system schema. ## Syntax * Alter the tamper-proof attribute of a schema. ``` ALTER SCHEMA schema_name { WITH | WITHOUT } BLOCKCHAIN ``` * Rename a schema. ``` ALTER SCHEMA schema_name RENAME TO new_name; ``` * Change the owner of a schema. ``` ALTER SCHEMA schema_name OWNER TO new_owner; ``` ## Parameter Description * **schema\_name** Specifies the name of an existing schema. Value range: an existing schema name. * **RENAME TO new\_name** Rename a schema. If a non-administrator user wants to change the schema name, the user must have the **CREATE** permission on the database. **new\_name**: new name of the schema. Value range: a string. It must comply with the identifier naming convention. * **OWNER TO new\_owner** Change the owner of a schema. To do this as a non-administrator, you must be a direct or indirect member of the new owner role, and that role must have the **CREATE** permission on the database. **new\_owner**: new owner of the schema. Value range: an existing username or role name. * **{ WITH | WITHOUT } BLOCKCHAIN** Alters the tamper-proof attribute of a schema. Common row-store tables with the tamper-proof attribute are tamper-proof history tables, excluding foreign tables, temporary tables, and system catalogs. The tamper-proof attribute can be altered only when no table is contained in the schema. In addition, the tamper-proof attribute of the temporary table schema, **toast table** schema, **dbe\_perf** schema, and **blockchain** schema cannot be modified. ## Examples ``` --Create the ds schema. openGauss=# CREATE SCHEMA ds; --Rename the current schema ds to ds_new. openGauss=# ALTER SCHEMA ds RENAME TO ds_new; --Create user jack. openGauss=# CREATE USER jack PASSWORD 'xxxxxxxxx'; --Change the owner of ds_new to jack. openGauss=# ALTER SCHEMA ds_new OWNER TO jack; --Delete user jack and schema ds_new. openGauss=# DROP SCHEMA ds_new; openGauss=# DROP USER jack; ``` ## Helpful Links [CREATE SCHEMA](create_schema.md) and [DROP SCHEMA](drop_schema.md) --- --- url: /en/docs/latest/sql_reference/alter_schema.md --- # ALTER SCHEMA ## Function **ALTER SCHEMA** alters the attributes of a schema. ## Precautions * Only the owner of a schema or users granted with the **ALTER** permission on the schema can run the **ALTER SCHEMA** command. The system administrator has this permission by default. To change the owner of a schema, you must be the owner of the schema or system administrator and a member of the new owner role. * Only the initial user is allowed to change the owner of the **pg\_catalog** system schema. ## Syntax * Alter the tamper-proof attribute of a schema. ``` ALTER SCHEMA schema_name { WITH | WITHOUT } BLOCKCHAIN ``` * Rename a schema. ``` ALTER SCHEMA schema_name RENAME TO new_name; ``` * Change the owner of a schema. ``` ALTER SCHEMA schema_name OWNER TO new_owner; ``` ## Parameter Description * **schema\_name** Specifies the name of an existing schema. Value range: an existing schema name. * **RENAME TO new\_name** Rename a schema. If a non-administrator user wants to change the schema name, the user must have the **CREATE** permission on the database. **new\_name**: new name of the schema. Value range: a string. It must comply with the identifier naming convention. * **OWNER TO new\_owner** Change the owner of a schema. To do this as a non-administrator, you must be a direct or indirect member of the new owner role, and that role must have the **CREATE** permission on the database. **new\_owner**: new owner of the schema. Value range: an existing username or role name. * **{ WITH | WITHOUT } BLOCKCHAIN** Alters the tamper-proof attribute of a schema. Common row-store tables with the tamper-proof attribute are tamper-proof history tables, excluding foreign tables, temporary tables, and system catalogs. The tamper-proof attribute can be altered only when no table is contained in the schema. In addition, the temporary table mode is not supported. Alter the tamper-proof attribute in the **toast table** schema, **dbe\_perf** schema, and **blockchain** schema. ## Examples ``` -- Create the ds schema. openGauss=# CREATE SCHEMA ds; -- Rename the current schema ds to ds_new. openGauss=# ALTER SCHEMA ds RENAME TO ds_new; -- Create user jack. openGauss=# CREATE USER jack PASSWORD 'xxxxxxxxx'; -- Change the owner of ds_new to jack. openGauss=# ALTER SCHEMA ds_new OWNER TO jack; -- Delete user jack and schema ds_new. openGauss=# DROP SCHEMA ds_new; openGauss=# DROP USER jack; ``` ## Helpful Links [CREATE SCHEMA](create_schema.md) and [DROP SCHEMA](drop_schema.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_schema.md --- # ALTER SCHEMA ## 功能描述 修改模式属性。 ## 注意事项 * 只有模式的所有者或者被授予了模式ALTER权限的用户有权限执行ALTER SCHEMA命令,系统管理员默认拥有此权限。但要修改模式的所有者,当前用户必须是该模式的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 对于系统模式pg\_catalog,只允许初始用户修改模式的所有者。 ## 语法格式 * 修改模式的防篡改属性。 ``` ALTER SCHEMA schema_name { WITH | WITHOUT } BLOCKCHAIN ``` * 修改模式的名称。 ``` ALTER SCHEMA schema_name RENAME TO new_name; ``` * 修改模式的所有者。 ``` ALTER SCHEMA schema_name OWNER TO new_owner; ``` - 修改模式的默认字符集和字符序。 ``` ALTER SCHEMA schema_name [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ]; ``` ## 参数说明 * **schema\_name** 现有模式的名称。 取值范围:已存在的模式名。 * **RENAME TO new\_name** 修改模式的名称。非系统管理员要改变模式的名称,则该用户必须在此数据库上有CREATE权限。 new\_name:模式的新名称。 取值范围:字符串,要符合标识符命名规范。 * **OWNER TO new\_owner** 修改模式的所有者。非系统管理员要改变模式的所有者,该用户还必须是新的所有角色的直接或间接成员, 并且该成员必须在此数据库上有CREATE权限。 new\_owner:模式的新所有者。 取值范围:已存在的用户名/角色名。 * **{ WITH | WITHOUT } BLOCKCHAIN** 修改模式的防篡改属性。具有防篡改属性模式下的普通行存表均为防篡改历史表,不包括外表,临时表,系统表。当该模式下不包含任何表时才可修改防篡改属性。另外,不支持临时表模式、toast表模式、dbe\_perf模式、blockchain模式修改防篡改属性。 * **default\_charset** 仅在sql\_compatibility='B'时支持该语法。修改模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **default\_collate** 仅在sql\_compatibility='B'时支持该语法。修改模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 支持字符序参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](create_table_1.md#table8163190152)。 ## 示例 ``` --创建模式ds。 openGauss=# CREATE SCHEMA ds; --将当前模式ds更名为ds_new。 openGauss=# ALTER SCHEMA ds RENAME TO ds_new; --创建用户jack。 openGauss=# CREATE USER jack PASSWORD 'xxxxxxxxx'; --将DS_NEW的所有者修改为jack。 openGauss=# ALTER SCHEMA ds_new OWNER TO jack; --将DS_NEW的默认字符集修改为utf8mb4,默认字符序修改为utf8mb4_bin。 openGauss=# ALTER SCHEMA ds_new CHARACTER SET utf8mb4 COLLATE utf8mb4_bin; --删除用户jack和模式ds_new。 openGauss=# DROP SCHEMA ds_new; openGauss=# DROP USER jack; ``` ## 相关链接 [CREATE SCHEMA](create_schema.md),[DROP SCHEMA](drop_schema.md) --- --- url: /zh/docs/latest/sql_reference/alter_schema.md --- # ALTER SCHEMA ## 功能描述 修改模式属性。 ## 注意事项 * 只有模式的所有者或者被授予了模式ALTER权限的用户有权限执行ALTER SCHEMA命令,系统管理员默认拥有此权限。但要修改模式的所有者,当前用户必须是该模式的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 对于系统模式pg\_catalog,只允许初始用户修改模式的所有者。 ## 语法格式 * 修改模式的防篡改属性。 ``` ALTER SCHEMA schema_name { WITH | WITHOUT } BLOCKCHAIN ``` * 修改模式的名称。 ``` ALTER SCHEMA schema_name RENAME TO new_name; ``` * 修改模式的所有者。 ``` ALTER SCHEMA schema_name OWNER TO new_owner; ``` - 修改模式的默认字符集和字符序。 ``` ALTER SCHEMA schema_name [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ]; ``` ## 参数说明 * **schema\_name** 现有模式的名称。 取值范围:已存在的模式名。 * **RENAME TO new\_name** 修改模式的名称。非系统管理员要改变模式的名称,则该用户必须在此数据库上有CREATE权限。 new\_name:模式的新名称。 取值范围:字符串,要符合标识符命名规范。 * **OWNER TO new\_owner** 修改模式的所有者。非系统管理员要改变模式的所有者,该用户还必须是新的所有角色的直接或间接成员, 并且该成员必须在此数据库上有CREATE权限。 new\_owner:模式的新所有者。 取值范围:已存在的用户名/角色名。 * **{ WITH | WITHOUT } BLOCKCHAIN** 修改模式的防篡改属性。具有防篡改属性模式下的普通行存表均为防篡改历史表,不包括外表、临时表、系统表。当该模式下不包含任何表时才可修改防篡改属性。另外,不支持临时表模式。toast表模式、dbe\_perf模式、blockchain模式修改防篡改属性。 * **default\_charset** 仅在sql\_compatibility='B'时支持该语法。修改模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **default\_collate** 仅在sql\_compatibility='B'时支持该语法。修改模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 支持字符序参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](create_table.md#table8163190152)。 ## 示例 ``` --创建模式ds。 openGauss=# CREATE SCHEMA ds; --将当前模式ds更名为ds_new。 openGauss=# ALTER SCHEMA ds RENAME TO ds_new; --创建用户jack。 openGauss=# CREATE USER jack PASSWORD 'xxxxxxxxx'; --将DS_NEW的所有者修改为jack。 openGauss=# ALTER SCHEMA ds_new OWNER TO jack; --将DS_NEW的默认字符集修改为utf8mb4,默认字符序修改为utf8mb4_bin。 openGauss=# ALTER SCHEMA ds_new CHARACTER SET utf8mb4 COLLATE utf8mb4_bin; --删除用户jack和模式ds_new。 openGauss=# DROP SCHEMA ds_new; openGauss=# DROP USER jack; ``` ## 相关链接 [CREATE SCHEMA](create_schema.md),[DROP SCHEMA](drop_schema.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_sequence.md --- # ALTER SEQUENCE ## Function **ALTER SEQUENCE** modifies the parameters of an existing sequence. ## Precautions * Only the owner of a sequence, a user granted the ALTER permission on a sequence, or a user granted the ALTER ANY SEQUENCE permission on a sequence can run the **ALTER SEQUENCE** command. The system administrator has this permission by default. To modify a sequence owner, you must be the sequence owner or system administrator and a member of the new owner role. * In the current version, you can modify only the step, the maximum value, the minimum value, the start value, the number of cached values, cycle, restart, the owner and the owning column. To modify other parameters, delete the sequence and create it again. Then, use the **Setval** function to restore parameter values. * **ALTER SEQUENCE MAXVALUE** cannot be used in functions and stored procedures. * After the maximum value of a sequence is changed, the cache of the sequence in all sessions is cleared. * If the LARGE identifier is used when a sequence is created, the LARGE identifier must be used when the sequence is altered. * The **ALTER SEQUENCE** statement blocks the invocation of **nextval**, **setval**, **currval**, and **lastval**. ## Syntax * Change the parameters of a sequence. ``` ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE ] [MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE ] [ RESTART [ WITH ] restart ] [ OWNED BY { table_name.column_name | NONE } ] ; ``` * Change the owner of a sequence. ``` ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name OWNER TO new_owner; ``` ## Parameter Description * name Specifies the name of the sequence to be modified. * IF EXISTS Sends a notice instead of an error when you are modifying a nonexisting sequence. * INCREMENT Specifies the step for the sequence. * MINVALUE minvalue | NO MINVALUE| NOMINVALUE Specifies the minimum value of the sequence. If **MINVALUE** is not declared, or **NO MINVALUE** is declared, the default value of the ascending sequence is **1**, and that of the descending sequence is **-263+1** or **-2127+1** if it's also a LARGE sequence. **NOMINVALUE** is equivalent to **NO MINVALUE**. * MAXVALUE maxvalue | NO MAXVALUE| NOMAXVALUE Specifies the maximum value of the sequence. If **MAXVALUE** is not declared, or **NO MAXVALUE** is declared, the default value of the ascending sequence is **263-1** or **2127-1** if it's also a LARGE sequence, and that of the descending sequence is **-1**. **NOMAXVALUE** is equivalent to **NO MAXVALUE**. * START Specifies the start value of the sequence. * CACHE Specifies the number of sequences stored in the memory for quick access purposes. If this parameter is not specified, the old cache value is retained. * CYCLE Recycles sequences after the number of sequences reaches **maxvalue** or **minvalue**. If **NO CYCLE** is specified, any invocation of **nextval** would return an error after the number of sequences reaches **maxvalue** or **minvalue**. **NOCYCLE** is equivalent to **NO CYCLE**. If **CYCLE** is specified, the sequence uniqueness cannot be ensured. * RESTART Specifies the nextval of the sequence. If the value of restart is not specified, the sequence will restart from its start value by default. * OWNED BY Associates a sequence with a specified column included in a table. In this way, the sequence will be deleted when you delete its associated column or the table where the column belongs to. If the sequence has been associated with another table before you use this option, the new association will overwrite the old one. The associated table and sequence must be owned by the same user and in the same schema. If **OWNED BY NONE** is used, all existing associations will be deleted. * new\_owner Specifies the username of the new owner of the sequence. To change the owner, you must also be a direct or indirect member of the new role, and this role must have **CREATE** permission on the sequence's schema. ## Examples ``` -- Create an ascending sequence named serial, which starts from 101. openGauss=# CREATE SEQUENCE serial START 101; -- Create a table and specify default values for the sequence. openGauss=# CREATE TABLE T1(C1 bigint default nextval('serial')); -- Change the owning column of serial to T1.C1. openGauss=# ALTER SEQUENCE serial OWNED BY T1.C1; --Change the step of serial to 2 openGauss=# ALTER SEQUENCE serial INCREMENT 2; --Change the minimum value of serial to 90 openGauss=# ALTER SEQUENCE serial MINVALUE 90; --Change the maximum value of serial to 200 openGauss=# ALTER SEQUENCE serial MAXVALUE 200; --Change the start value of serial to 90 openGauss=# ALTER SEQUENCE serial START 90; --Change the number of cached value of serial to 10 openGauss=# ALTER SEQUENCE serial CACHE 10; --Change serial to be a cycle openGauss=# ALTER SEQUENCE serial CYCLE; --Change serial to restart from 100 openGauss=# ALTER SEQUENCE serial RESTART 100; -- Delete a sequence and a table. openGauss=# DROP SEQUENCE serial cascade; openGauss=# DROP TABLE T1; ``` ## Helpful Links [CREATE SEQUENCE](create_sequence.md) and [DROP SEQUENCE](drop_sequence.md) --- --- url: /en/docs/latest/sql_reference/alter_sequence.md --- # ALTER SEQUENCE ## Function **ALTER SEQUENCE** modifies the parameters of an existing sequence. ## Precautions * Only the owner of a sequence, a user granted the ALTER permission on a sequence, or a user granted the ALTER ANY SEQUENCE permission on a sequence can run the **ALTER SEQUENCE** command. The system administrator has this permission by default. To modify a sequence owner, you must be the sequence owner or system administrator and a member of the new owner role. * In the current version, you can modify only the step, the maximum value, the minimum value, the start value, the number of cached values, cycle, restart, the owner and the owning column. To modify other parameters, delete the sequence and create it again. Then, use the **Setval** function to restore parameter values. * **ALTER SEQUENCE MAXVALUE** cannot be used in functions and stored procedures. * After the maximum value of a sequence is changed, the cache of the sequence in all sessions is cleared. * If the LARGE identifier is used when a sequence is created, the LARGE identifier must be used when the sequence is altered. * The **ALTER SEQUENCE** statement blocks the invocation of **nextval**, **setval**, **currval**, and **lastval**. ## Syntax * Change the parameters of a sequence. ``` ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE ] [MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE ] [ RESTART [ WITH ] restart ] [ OWNED BY { table_name.column_name | NONE } ] ; ``` * Change the owner of a sequence. ``` ALTER SEQUENCE [ IF EXISTS ] name OWNER TO new_owner; ``` * Change the cache level of a sequence to global or session level. ``` ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name [ SESSION | GLOBAL ]; ``` ## Parameter Description * name Specifies the name of the sequence to be modified. * IF EXISTS Sends a notice instead of an error when you are modifying a nonexisting sequence. * INCREMENT Specifies the step for the sequence. * MINVALUE minvalue | NO MINVALUE| NOMINVALUE Specifies the minimum value of the sequence. If **MINVALUE** is not declared, or **NO MINVALUE** is declared, the default value of the ascending sequence is **1**, and that of the descending sequence is **-263+1** or **-2127+1** if it's also a LARGE sequence. **NOMINVALUE** is equivalent to **NO MINVALUE**. * MAXVALUE maxvalue | NO MAXVALUE| NOMAXVALUE Specifies the maximum value of the sequence. If **MAXVALUE** is not declared, or **NO MAXVALUE** is declared, the default value of the ascending sequence is **263-1** or **2127-1** if it's also a LARGE sequence, and that of the descending sequence is **-1**. **NOMAXVALUE** is equivalent to **NO MAXVALUE**. * START Specifies the start value of the sequence. * CACHE Specifies the number of sequences stored in the memory for quick access purposes. If this parameter is not specified, the old cache value is retained. * CYCLE Recycles sequences after the number of sequences reaches **maxvalue** or **minvalue**. If **NO CYCLE** is specified, any invocation of **nextval** would return an error after the number of sequences reaches **maxvalue** or **minvalue**. **NOCYCLE** is equivalent to **NO CYCLE**. If **CYCLE** is specified, the sequence uniqueness cannot be ensured. * RESTART Specifies the nextval of the sequence. If the value of restart is not specified, the sequence will restart from its start value by default. * OWNED BY Associates a sequence with a specified column included in a table. In this way, the sequence will be deleted when you delete its associated column or the table where the column belongs to. If the sequence has been associated with another table before you use this option, the new association will overwrite the old one. The associated table and sequence must be owned by the same user and in the same schema. If **OWNED BY NONE** is used, all existing associations will be deleted. * new\_owner Specifies the username of the new owner of the sequence. To change the owner, you must also be a direct or indirect member of the new role, and this role must have **CREATE** permission on the sequence's schema. ## Examples ``` -- Create an ascending sequence named serial, which starts from 101. openGauss=# CREATE SEQUENCE serial START 101; -- Create a table and specify default values for the sequence. openGauss=# CREATE TABLE T1(C1 bigint default nextval('serial')); -- Change the owning column of serial to T1.C1. openGauss=# ALTER SEQUENCE serial OWNED BY T1.C1; --Change the step of serial to 2 openGauss=# ALTER SEQUENCE serial INCREMENT 2; --Change the minimum value of serial to 90 openGauss=# ALTER SEQUENCE serial MINVALUE 90; --Change the maximum value of serial to 200 openGauss=# ALTER SEQUENCE serial MAXVALUE 200; --Change the start value of serial to 90 openGauss=# ALTER SEQUENCE serial START 90; --Change the number of cached value of serial to 10 openGauss=# ALTER SEQUENCE serial CACHE 10; --Change serial to be a cycle openGauss=# ALTER SEQUENCE serial CYCLE; --Change serial to restart from 100 openGauss=# ALTER SEQUENCE serial RESTART 100; --Change the cache level openGauss=# CREATE SEQUENCE seq_1 CACHE 100 GLOBAL; --global level cache openGauss=# ALTER SEQUENCE seq_1 SESSION; --change to session level cache -- Delete a sequence and a table. openGauss=# DROP SEQUENCE seq_1; openGauss=# DROP SEQUENCE serial cascade; openGauss=# DROP TABLE T1; ``` ## Helpful Links [CREATE SEQUENCE](create_sequence.md) and [DROP SEQUENCE](drop_sequence.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_sequence.md --- # ALTER SEQUENCE ## 功能描述 修改一个现有的序列的参数。 ## 注意事项 * 序列的所有者或者被授予了序列ALTER权限的用户或者被授予了ALTER ANY SEQUENCE权限的用户才能执行ALTER SEQUENCE命令,系统管理员默认拥有该权限。但要修改序列的所有者,当前用户必须是该序列的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 当前版本仅支持修改步长、最大值、最小值、起始值、缓冲值、是否循环、重新开始、归属列和拥有者。若要修改其他参数,可以删除重建,并用Setval函数恢复当前值。 * ALTER SEQUENCE MAXVALUE不支持在函数和存储过程中使用。 * 修改序列的最大值后,会清空该序列在所有会话的cache。 * 如果Sequence被创建时使用了LARGE标识,则ALTER时也需要使用LARGE标识。 * ALTER SEQUENCE会阻塞nextval、setval、currval和lastval的调用。 * D模式下不支持序列重命名语法。序列重命名只修改了序列在元数据系统表pg\_class的名称,未修改序列关系中保存的旧名称信息(sequence\_name)。 ## 语法格式 * 修改序列属性 ```EBNF ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE ] [MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE ] [ RESTART [ WITH ] restart ] [ OWNED BY { table_name.column_name | NONE } ] ; ``` * 修改序列的拥有者 ```EBNF ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name OWNER TO new_owner; ``` * 修改序列的名称 ```EBNF ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name RENAME TO new_name; ``` ## 参数说明 * name 将要修改的序列名称。 * IF EXISTS 当序列不存在时使用该选项不会出现错误消息,仅有一个通知。 * INCREMENT 指定序列的步长。 * MINVALUE minvalue | NO MINVALUE| NOMINVALUE 指定序列的最小值。如果没有声明minvalue或者声明了NO MINVALUE,则递增序列的缺省值为1,递减序列的缺省值为-263+1(Large序列为-2127+1)。NOMINVALUE等价于NO MINVALUE * MAXVALUE maxvalue | NO MAXVALUE| NOMAXVALUE 指定序列的最大值。如果没有声明maxvalue或者声明了NO MAXVALUE,则递增序列的缺省值为263-1(Large序列为2127-1),递减序列的缺省值为-1。NOMAXVALUE等价于NO MAXVALUE * START 指定序列的起始值。 * CACHE 为了快速访问,而在内存中预先存储序列号的个数。如果没有指定,将保持旧的缓冲值。 * CYCLE 用于使序列达到maxvalue或者minvalue后可循环并继续下去。 如果声明了NO CYCLE,则在序列达到其最大值后任何对nextval的调用都会返回一个错误。 NOCYCLE的作用等价于NO CYCLE。 若修改序列为CYCLE,则不能保证序列的唯一性。 * RESTART 用于更改序列的当前值,指定的当前值将作为下次调用nextval的结果返回。缺省值为序列的起始值。 * OWNED BY 将序列和一个表的指定字段进行关联。这样,在删除那个字段或其所在表的时候会自动删除已关联的序列。 如果序列已经和表有关联后,使用这个选项后新的关联关系会覆盖旧的关联。 关联的表和序列的所有者必须是同一个用户,并且在同一个模式中。 使用OWNED BY NONE将删除任何已经存在的关联。 * new\_owner 序列新所有者的用户名。用户要修改序列的所有者,必须是新角色的直接或者间接成员,并且那个角色必须有序列所在模式上的CREATE权限。 * new\_name 序列重命名后的名称。 ## 示例 ```sql --创建一个名为serial的递增序列,从101开始。 openGauss=# CREATE SEQUENCE serial START 101; --创建一个表,定义默认值。 openGauss=# CREATE TABLE T1(C1 bigint default nextval('serial')); --将序列serial的归属列变为T1.C1。 openGauss=# ALTER SEQUENCE serial OWNED BY T1.C1; --修改序列步长为2 openGauss=# ALTER SEQUENCE serial INCREMENT 2; --修改序列最小值为90 openGauss=# ALTER SEQUENCE serial MINVALUE 90; --修改序列最大值为200 openGauss=# ALTER SEQUENCE serial MAXVALUE 200; --修改序列起始值为90 openGauss=# ALTER SEQUENCE serial START 90; --修改序列缓冲值为10 openGauss=# ALTER SEQUENCE serial CACHE 10; --修改序列循环 openGauss=# ALTER SEQUENCE serial CYCLE; --修改序列从100重新开始 openGauss=# ALTER SEQUENCE serial RESTART 100; --重命名序列 openGauss=# ALTER SEQUENCE serial RENAME TO serial1; --删除序列和表。 openGauss=# DROP SEQUENCE serial1 cascade; openGauss=# DROP TABLE T1; ``` ## 相关链接 [CREATE SEQUENCE](create_sequence.md),[DROP SEQUENCE](drop_sequence.md) --- --- url: /zh/docs/latest/ograc/sql_reference/alter_sequence.md --- # ALTER SEQUENCE ## 功能描述 修改一个现有的序列的参数。 ## 注意事项 * 在修改序列的某些属性(如最小值和最大值)时,需要确保新设置的值在逻辑上是合理的,例如最小值应该小于最大值。 * 如果序列已经达到了其最大值并且设置为循环(CYCLE),则在下次获取值时将从最小值重新开始。如果未设置循环且达到最大值,再获取值时会报错。 ## 语法格式 * 修改序列属性 ``` ALTER SEQUENCE [schema.]sequence_name [ INCREMENT BY increment ] [ MINVALUE minvalue | NOMINVALUE ] [ MAXVALUE maxvalue | NOMAXVALUE ] [ CACHE cachevalue | NOCACHE ] [ CYCLE | NOCYCLE ]; ``` ## 参数说明 * schema 用户名。默认是当前用户。 * sequence\_name 将要修改的序列名称。 * INCREMENT 指定序列的步长。当设置的步长大于0,则序列递增;步长小于0,则序列递减。默认值为1。 * MINVALUE minvalue | NOMINVALUE 指定序列的最小值。如果没有声明minvalue或者声明了NOMINVALUE,则递增序列的默认值为1,递减序列的默认值为-263+1。 * MAXVALUE maxvalue | NOMAXVALUE 指定序列的最大值。如果没有声明maxvalue或者声明了NOMAXVALUE,则递减序列的默认值为-1,递增序列的默认值为263-1。 * CACHE cachevalue | NOCACHE 为了快速访问,而在内存中预先存储序列号的个数。如果没有指定,默认值为NOCACHE,默认序列号个数为1。 * CYCLE | NOCYCLE 用于使序列达到maxvalue或者minvalue后可循环并继续下去。 如果声明了NOCYCLE,则在序列达到其最大值后任何对nextval的调用都会返回一个错误。 若修改序列为CYCLE,则不能保证序列的唯一性。 默认值为NOCYCLE。 ## 示例 ``` -- 创建一个名为serial的递增序列,从101开始。 SQL> CREATE SEQUENCE serial START WITH 101; -- 修改序列步长为2 SQL> ALTER SEQUENCE serial INCREMENT BY 2; -- 修改序列最小值为90 SQL> ALTER SEQUENCE serial MINVALUE 90; -- 修改序列最大值为200 SQL> ALTER SEQUENCE serial MAXVALUE 200; -- 修改序列缓冲值为10 SQL> ALTER SEQUENCE serial CACHE 10; -- 修改序列循环 SQL> ALTER SEQUENCE serial CYCLE; -- 删除序列 SQL> DROP SEQUENCE serial; ``` --- --- url: /zh/docs/latest/sql_reference/alter_sequence.md --- # ALTER SEQUENCE ## 功能描述 修改一个现有的序列的参数。 ## 注意事项 * 序列的所有者或者被授予了序列ALTER权限的用户或者被授予了ALTER ANY SEQUENCE权限的用户才能执行ALTER SEQUENCE命令,系统管理员默认拥有该权限。但要修改序列的所有者,当前用户必须是该序列的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 当前版本仅支持修改步长、最大值、最小值、起始值、缓冲值、是否循环、重新开始、归属列和拥有者。若要修改其他参数,可以删除重建,并用Setval函数恢复当前值。 * ALTER SEQUENCE MAXVALUE不支持在函数和存储过程中使用。 * 修改序列的最大值后,会清空该序列在所有会话的cache。 * 如果Sequence被创建时使用了LARGE标识,则ALTER时也需要使用LARGE标识。 * ALTER SEQUENCE会阻塞nextval、setval、currval和lastval的调用。 * D模式下不支持序列重命名语法。序列重命名只修改了元数据系统表pg\_class的名称,未修改序列关系自身的名称(sequence\_name)。 ## 语法格式 * 修改序列属性 ```EBNF ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE ] [MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE ] [ RESTART [ WITH ] restart ] [ OWNED BY { table_name.column_name | NONE } ] ; ``` * 修改序列的拥有者 ```EBNF ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name OWNER TO new_owner; ``` * 修改序列的名称 ```EBNF ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name RENAME TO new_name; ``` * 修改序列缓存为global或session级别 ``` ALTER [ LARGE ] SEQUENCE [ IF EXISTS ] name [ SESSION | GLOBAL ]; ``` ## 参数说明 * name 将要修改的序列名称。 * IF EXISTS 当序列不存在时使用该选项不会出现错误消息,仅有一个通知。 * INCREMENT 指定序列的步长。 * MINVALUE minvalue | NO MINVALUE| NOMINVALUE 指定序列的最小值。如果没有声明minvalue或者声明了NO MINVALUE,则递增序列的缺省值为1,递减序列的缺省值为-263+1(Large序列为-2127+1)。NOMINVALUE等价于NO MINVALUE * MAXVALUE maxvalue | NO MAXVALUE| NOMAXVALUE 指定序列的最大值。如果没有声明maxvalue或者声明了NO MAXVALUE,则递增序列的缺省值为263-1(Large序列为2127-1),递减序列的缺省值为-1。NOMAXVALUE等价于NO MAXVALUE * START 指定序列的起始值。 * CACHE 为了快速访问,而在内存中预先存储序列号的个数。如果没有指定,将保持旧的缓冲值。 * CYCLE 用于使序列达到maxvalue或者minvalue后可循环并继续下去。 如果声明了NO CYCLE,则在序列达到其最大值后任何对nextval的调用都会返回一个错误。 NOCYCLE的作用等价于NO CYCLE。 若修改序列为CYCLE,则不能保证序列的唯一性。 * RESTART 用于更改序列的当前值,指定的当前值将作为下次调用nextval的结果返回。缺省值为序列的起始值。 * OWNED BY 将序列和一个表的指定字段进行关联。这样,在删除那个字段或其所在表的时候会自动删除已关联的序列。 如果序列已经和表有关联后,使用这个选项后新的关联关系会覆盖旧的关联。 关联的表和序列的所有者必须是同一个用户,并且在同一个模式中。 使用OWNED BY NONE将删除任何已经存在的关联。 * new\_owner 序列新所有者的用户名。用户要修改序列的所有者,必须是新角色的直接或者间接成员,并且那个角色必须有序列所在模式上的CREATE权限。 * new\_name 序列重命名后的名称。 ## 示例 ```sql --创建一个名为serial的递增序列,从101开始。 openGauss=# CREATE SEQUENCE serial START 101; --创建一个表,定义默认值。 openGauss=# CREATE TABLE T1(C1 bigint default nextval('serial')); --将序列serial的归属列变为T1.C1。 openGauss=# ALTER SEQUENCE serial OWNED BY T1.C1; --修改序列步长为2 openGauss=# ALTER SEQUENCE serial INCREMENT 2; --修改序列最小值为90 openGauss=# ALTER SEQUENCE serial MINVALUE 90; --修改序列最大值为200 openGauss=# ALTER SEQUENCE serial MAXVALUE 200; --修改序列起始值为90 openGauss=# ALTER SEQUENCE serial START 90; --修改序列缓冲值为10 openGauss=# ALTER SEQUENCE serial CACHE 10; --修改序列循环 openGauss=# ALTER SEQUENCE serial CYCLE; --修改序列从100重新开始 openGauss=# ALTER SEQUENCE serial RESTART 100; --重命名序列 openGauss=# ALTER SEQUENCE serial RENAME TO serial1; --修改序列的cache为全局或session openGauss=# CREATE SEQUENCE seq_1 CACHE 100 GLOBAL; --创建缓存为global级别的序列 openGauss=# ALTER SEQUENCE seq_1 SESSION; --修改序列的缓存为session级别 --删除序列和表。 openGauss=# DROP SEQUENCE seq_1; openGauss=# DROP SEQUENCE serial cascade; openGauss=# DROP TABLE T1; ``` ## 相关链接 [CREATE SEQUENCE](create_sequence.md),[DROP SEQUENCE](drop_sequence.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_server.md --- # ALTER SERVER ## Function **ALTER SERVER** adds, modifies, or deletes the parameters of an existing server. You can query existing servers from the **pg\_foreign\_server** system catalog. ## Precautions Only the server owner or a user granted with the ALTER permission can run the **ALTER SERVER** command. The system administrator has this permission by default. To modify a server owner, you must be the server owner or system administrator and a member of the new owner role. ## Syntax * Change the parameters for a foreign server. ``` ALTER SERVER server_name [ VERSION 'new_version' ] [ OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ] ) ]; ``` ``` In **OPTIONS**, **ADD**, **SET**, and **DROP** are operations to be performed. If these operations are not specified, **ADD** operations will be performed by default. **option** and **value** are the parameters of the corresponding operation. ``` * Change the name of a foreign server. ``` ALTER SERVER server_name RENAME TO new_name; ``` ## Parameter Description * **server\_name** Specifies the name of the server to be modified. * **new\_version** Specifies the new version of the server. * **OPTIONS** Change options of the server. **ADD**, **SET**, and **DROP** are operations to be performed. If the operation is not set explicitly, **ADD** is used. The option name must be unique, and the name and value are also validated with the foreign data wrapper library of the server. * Options supported by oracle\_fdw are as follows: * **dbserver** Connection string of the remote Oracle database. * **isolation\_level** (default value: **serializable**) Oracle database transaction isolation level. Value range: serializable, read\_committed, read\_only * Options supported by mysql\_fdw are as follows: * **host** (default value: **127.0.0.1**) IP address of the MySQL server or MariaDB. * **port** (default value: **3306**) Listening port number of the MySQL server or MariaDB. * The options supported by postgres\_fdw are the same as those supported by libpq. For details, see [Link Parameters](../developer_guide/link_parameters_libpq.md). Note that the following options cannot be modified: * **user** and **password** The username and password are specified when the user mapping is created. * **client\_encoding** The encoding mode of the local server is automatically obtained and set. * **application\_name** This option is always set to **postgres\_fdw**. In addition to the connection parameters supported by libpq, the following options are provided: * **use\_remote\_estimate** Controls whether postgres\_fdw issues the EXPLAIN command to obtain the estimated run time. The default value is **false**. * **fdw\_startup\_cost** Estimates the startup time required for a foreign table scan, including the time to establish a connection, analyzes the request at the remote server, and generates a plan. The default value is **100**. * **fdw\_typle\_cost** Specifies the additional consumption when each tuple is scanned on a remote server. The value specifies the extra consumption of data transmission between servers. The default value is **0.01**. * **new\_name** Specifies the new name of the server. > \[!NOTE]NOTE > In the Lite scenario, openGauss does not support the change of **obs\_server** contained in the **ALTER SERVER** syntax. ## Helpful Links [CREATE SERVER](create_server.md) and [DROP SERVER](drop_server.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-alter-server.md --- # ALTER SERVER ## Function Adds, modifies, or deletes parameters of an existing server. You can query existing servers from the **pg\_foreign\_server** system catalog. ## Precautions * This section describes only the new syntax of Dolphin. The original syntax of openGauss is not deleted or modified. * Compared with the original openGauss, Dolphin modifies the `ALTER SERVER` syntax as follows: 1. If **fdw\_name** of the modified server is set to **mysql\_fdw**, the following **option** values are added: DATABASE, USER, PASSWORD, SOCKET, and OWNER. 2. If **fdw\_name** of the modified server is set to **mysql\_fdw**, no operation is specified, and the **option** value of the server already exists, then the operation is set to **SET**. ## Syntax * Change the parameters for a foreign server. ``` ALTER SERVER server_name [ VERSION 'new_version' ] [ OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ] ) ]; ``` * Change the name of a foreign server. ``` ALTER SERVER server_name RENAME TO new_name; ``` ## Parameter Description * **OPTIONS** Specifies options for the server. **ADD**, **SET**, and **DROP** are operations to be performed. If the operation is not set explicitly, **ADD** is used. The option name must be unique, and the name and value are also validated with the foreign data wrapper library of the server. * The options supported by mysql\_fdw are as follows: * **host** (default value: **127.0.0.1**) IP address of the MySQL server or MariaDB. * **port** (default value: **3306**) Listening port number of the MySQL server or MariaDB. * **user** (default value: empty) User name for connecting to MySQL Server or MariaDB. If this option is specified and the user mapping from the current user to the specified server does not exist, openGauss automatically creates the user mapping from the current user to the new server. If this option is specified and the user mapping from the current user to the specified server already exists, openGauss modifies the **option** value of the user mapping. * **password** (default value: empty) Password for connecting to MySQL Server or MariaDB. If this option is specified and the user mapping from the current user to the specified server does not exist, openGauss automatically creates the user mapping from the current user to the new server. If this option is specified and the user mapping from the current user to the specified server already exists, openGauss modifies the **option** value of the user mapping. * **database** (default value: empty) This option has no actual meaning and is used only for syntax compatibility. You can specify the database to be connected to MySQL Server or MariaDB by referring to [CREATE FOREIGN TABLE](https://docs.opengauss.org/en/docs/latest/sql_reference/create_foreign_table.html) and [ALTER FOREIGN TABLE](https://docs.opengauss.org/en/docs/latest/sql_reference/alter_foreign_table.html). * **owner** (default value: empty) This option has no actual meaning and is used only for syntax compatibility. * **socket** (default value: empty) This option has no actual meaning and is used only for syntax compatibility. ## Examples Modify a server. ``` -- The user mapping from the current user to the specified server does not exist. openGauss=# alter server server_test options(user 'my_user', password 'mypassword'); WARNING: USER MAPPING for current user to server server_test created. ALTER SERVER -- The user mapping from the current user to the specified server already exists. openGauss=# alter server server_test options(port '3308', user 'my_user'); WARNING: USER MAPPING for current user to server server_test altered. ALTER SERVER ``` ## Helpful Links [CREATE SERVER](dolphin-create-server.md) and [DROP SERVER](https://docs.opengauss.org/en/docs/latest/sql_reference/drop_server.html) --- --- url: /en/docs/latest/sql_reference/alter_server.md --- # ALTER SERVER ## Function **ALTER SERVER** adds, modifies, or deletes the parameters of an existing server. You can query existing servers from the **pg\_foreign\_server** system catalog. ## Precautions Only the server owner or a user granted with the ALTER permission can run the **ALTER SERVER** command. The system administrator has this permission by default. To modify a server owner, you must be the server owner or system administrator and a member of the new owner role. ## Syntax * Change the parameters for a foreign server. ``` ALTER SERVER server_name [ VERSION 'new_version' ] [ OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ] ) ]; ``` ``` In **OPTIONS**, **ADD**, **SET**, and **DROP** are operations to be performed. If these operations are not specified, **ADD** operations will be performed by default. **option** and **value** are the parameters of the corresponding operation. ``` * Change the name of a foreign server. ``` ALTER SERVER server_name RENAME TO new_name; ``` ## Parameter Description * **server\_name** Specifies the name of the server to be modified. * **new\_version** Specifies the new version of the server. * **OPTIONS** Change options of the server. **ADD**, **SET**, and **DROP** are operations to be performed. If the operation is not set explicitly, **ADD** is used. The option name must be unique, and the name and value are also validated with the foreign data wrapper library of the server. * Options supported by oracle\_fdw are as follows: * **dbserver** Connection string of the remote Oracle database. * **isolation\_level** (default value: **serializable**) Oracle database transaction isolation level. Value range: serializable, read\_committed, read\_only * Options supported by mysql\_fdw are as follows: * **host** (default value: **127.0.0.1**) IP address of the MySQL server or MariaDB. * **port** (default value: **3306**) Listening port number of the MySQL server or MariaDB. * The options supported by postgres\_fdw are the same as those supported by libpq. For details, see [Connection Characters](../developer_guide/link_parameters_libpq.md). Note that the following options cannot be modified: * **user** and **password** The user name and password are specified when the user mapping is created. * **client\_encoding** The encoding mode of the local server is automatically obtained and set. * **application\_name** This option is always set to **postgres\_fdw**. In addition to the connection parameters supported by libpq, the following options are provided: * **use\_remote\_estimate** Controls whether postgres\_fdw issues the EXPLAIN command to obtain the estimated run time. The default value is **false**. * **fdw\_startup\_cost** Estimates the startup time required for a foreign table scan, including the time to establish a connection, analyze the request at the remote server, and generate a plan. The default value is **100**. * **fdw\_typle\_cost** Specifies the additional consumption when each tuple is scanned on a remote server. The value specifies the extra consumption of data transmission between servers. The default value is **0.01**. * **new\_name** Specifies the new name of the server. ## Helpful Links [CREATE SERVER](create_server.md) and [DROP SERVER](drop_server.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-ALTER-SERVER.md --- # ALTER SERVER ## 功能描述 增加、修改和删除一个现有server的参数。已有server可以从pg\_foreign\_server系统表中查询。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 * 相比于原始的openGauss,dolphin对于`ALTER SERVER`语法的修改主要为: 1. 对于修改的server其fdw\_name为mysql\_fdw时,增加可选OPTIONS:DATABASE, USER, PASSWORD, SOCKET, OWNER。 2. 对于修改的server其fdw\_name为mysql\_fdw时,若option未指定执行动作,且server的option已存在,则将本次语句的动作更改为SET。 ## 语法格式 * 修改外部服务的参数。 ``` ALTER SERVER server_name [ VERSION 'new_version' ] [ OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ] ) ]; ``` * 修改外部服务的名称。 ``` ALTER SERVER server_name RENAME TO new_name; ``` ## 参数说明 * **OPTIONS** 更改该服务器的选项。ADD、SET和 DROP指定要执行的动作。如果没有显式地指定操作, 将会假定为ADD。选项名称必须唯一,名称和值也会使用该服务器的外部数据包装器库进行验证。 * mysql\_fdw支持的options包括: * **host** (默认值为 127.0.0.1) MySQL Server/MariaDB的地址。 * **port** (默认值为 3306) MySQL Server/MariaDB侦听的端口号。 * **user** (默认为空) MySQL Server/MariaDB用于连接的用户名。若OPTIONS指定此选项,且不存在当前用户到给定server的用户映射,openGauss将自动创建当前用户到新建server的用户映射;若OPTIONS指定此选项,且已存在当前用户到给定server的用户映射,openGauss将修改该用户映射的对应option值。 * **password**(默认为空) MySQL Server/MariaDB用于连接的用户密码。若OPTIONS指定此选项,且不存在当前用户到给定server的用户映射,openGauss将自动创建当前用户到新建server的用户映射;若OPTIONS指定此选项,且已存在当前用户到给定server的用户映射,openGauss将修改该用户映射的对应option值。 * **database** (默认为空) 无实际意义,仅做语法兼容。指定MySQL Server/MariaDB连接的数据库请在[CREATE FOREIGN TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_foreign_table.html)或[ALTER FOREIGN TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_foreign_table.html)中完成。 * **owner** (默认为空) 无实际意义,仅做语法兼容。 * **socket** (默认为空) 无实际意义,仅做语法兼容。 ## 示例 修改server。 ``` -- 当前用户到给定server的用户映射不存在时 openGauss=# alter server server_test options(user 'my_user', password 'mypassword'); WARNING: USER MAPPING for current user to server server_test created. ALTER SERVER -- 当前用户到给定server的用户映射已存在时 openGauss=# alter server server_test options(port '3308', user 'my_user'); WARNING: USER MAPPING for current user to server server_test altered. ALTER SERVER ``` ## 相关链接 [CREATE SERVER](dolphin-CREATE-SERVER.md),[DROP SERVER](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/drop_server.html) --- --- url: /zh/docs/latest-lite/sql_reference/alter_server.md --- # ALTER SERVER ## 功能描述 增加、修改和删除一个现有server的参数。已有server可以从pg\_foreign\_server系统表中查询。 ## 注意事项 只有SERVER的所有者或者被授予了SERVER的ALTER权限的用户才可以执行ALTER SERVER命令,系统管理员默认拥有该权限。但要修改SERVER的所有者,当前用户必须是该SERVER的所有者或者系统管理员,且该用户是新所有者角色的成员。 ## 语法格式 * 修改外部服务的参数。 ``` ALTER SERVER server_name [ VERSION 'new_version' ] [ OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ] ) ]; ``` ``` 在OPTIONS选项里,ADD、SET和DROP指定要执行的操作,未指定时默认为ADD操作。option和value为对应操作的参数。 ``` * 修改外部服务的名称。 ``` ALTER SERVER server_name RENAME TO new_name; ``` ## 参数说明 * **server\_name** 所修改的server的名称。 * **new\_version** 修改后server的新版本名称。 * **OPTIONS** 更改该服务器的选项。ADD、SET和 DROP指定要执行的动作。如果没有显式地指定操作, 将会假定为ADD。选项名称必须唯一,名称和值也会使用该服务器的外部数据包装器库进行验证。 * oracle\_fdw支持的options包括: * **dbserver** 远端oracle数据库的连接字符串。 * **isolation\_level** (默认值为serializable) oracle数据库的事务隔离级别。 取值范围:serializable, read\_committed , read\_only * mysql\_fdw支持的options包括: * **host** (默认值为 127.0.0.1) MySQL Server/MariaDB的地址。 * **port** (默认值为 3306) MySQL Server/MariaDB侦听的端口号。 * postgres\_fdw支持的options同libpq支持的连接参数一致,可参考[链接参数](../developer_guide/link_parameters_libpq.md)。需要注意的是,以下几个options不支持修改: * **user**和**password** 用户名和密码将在创建user mapping时指定 * **client\_encoding** 将自动获取本地server的编码方式并设置该值 * **application\_name** 总是设置成postgres\_fdw 除了libpq支持的连接参数外,还额外提供3个options: * **use\_remote\_estimate** 控制postgres\_fdw是否发出EXPLAIN命令以获取运行消耗估算。默认值为false。 * **fdw\_startup\_cost** 执行一个外表扫描时的启动耗时估算。这个值通常包含建立连接、远端对请求的分析和生成计划的耗时。默认值为100。 * **fdw\_typle\_cost** 在远端服务器上对每一个元组进行扫描时的额外消耗。这个值通常表示数据在server间传输的额外消耗。默认值为0.01。 * **new\_name** 修改后server的新名称。 > \[!NOTE]说明 > 轻量版场景下,openGauss不支持ALTER SERVER语法中obs\_server。 ## 相关链接 [CREATE SERVER](create_server.md),[DROP SERVER](drop_server.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-ALTER-SERVER.md --- # ALTER SERVER ## 功能描述 增加、修改和删除一个现有server的参数。已有server可以从pg\_foreign\_server系统表中查询。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 * 相比于原始的openGauss,dolphin对于`ALTER SERVER`语法的修改主要为: 1. 对于修改的server其fdw\_name为mysql\_fdw时,增加可选OPTIONS:DATABASE, USER, PASSWORD, SOCKET, OWNER。 2. 对于修改的server其fdw\_name为mysql\_fdw时,若option未指定执行动作,且server的option已存在,则将本次语句的动作更改为SET。 ## 语法格式 * 修改外部服务的参数。 ``` ALTER SERVER server_name [ VERSION 'new_version' ] [ OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ] ) ]; ``` * 修改外部服务的名称。 ``` ALTER SERVER server_name RENAME TO new_name; ``` ## 参数说明 * **OPTIONS** 更改该服务器的选项。ADD、SET和 DROP指定要执行的动作。如果没有显式地指定操作, 将会假定为ADD。选项名称必须唯一,名称和值也会使用该服务器的外部数据包装器库进行验证。 * mysql\_fdw支持的options包括: * **host** (默认值为 127.0.0.1) MySQL Server/MariaDB的地址。 * **port** (默认值为 3306) MySQL Server/MariaDB侦听的端口号。 * **user** (默认为空) MySQL Server/MariaDB用于连接的用户名。若OPTIONS指定此选项,且不存在当前用户到给定server的用户映射,openGauss将自动创建当前用户到新建server的用户映射;若OPTIONS指定此选项,且已存在当前用户到给定server的用户映射,openGauss将修改该用户映射的对应option值。 * **password** (默认为空) MySQL Server/MariaDB用于连接的用户密码。若OPTIONS指定此选项,且不存在当前用户到给定server的用户映射,openGauss将自动创建当前用户到新建server的用户映射;若OPTIONS指定此选项,且已存在当前用户到给定server的用户映射,openGauss将修改该用户映射的对应option值。 * **database** (默认为空) 无实际意义,仅做语法兼容。指定MySQL Server/MariaDB连接的数据库请在[CREATE FOREIGN TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_foreign_table.html)或[ALTER FOREIGN TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_foreign_table.html)中完成。 * **owner** (默认为空) 无实际意义,仅做语法兼容。 * **socket** (默认为空) 无实际意义,仅做语法兼容。 ## 示例 修改server。 ``` -- 当前用户到给定server的用户映射不存在时 openGauss=# alter server server_test options(user 'my_user', password 'mypassword'); WARNING: USER MAPPING for current user to server server_test created. ALTER SERVER -- 当前用户到给定server的用户映射已存在时 openGauss=# alter server server_test options(port '3308', user 'my_user'); WARNING: USER MAPPING for current user to server server_test altered. ALTER SERVER ``` ## 相关链接 [CREATE SERVER](dolphin-CREATE-SERVER.md),[DROP SERVER](https://docs.opengauss.org/zh/docs/latest/sql_reference/drop_server.html) --- --- url: /zh/docs/latest/sql_reference/alter_server.md --- # ALTER SERVER ## 功能描述 增加、修改和删除一个现有server的参数。已有server可以从pg\_foreign\_server系统表中查询。 ## 注意事项 只有SERVER的所有者或者被授予了SERVER的ALTER权限的用户才可以执行ALTER SERVER命令,系统管理员默认拥有该权限。但要修改SERVER的所有者,当前用户必须是该SERVER的所有者或者系统管理员,且该用户是新所有者角色的成员。 ## 语法格式 * 修改外部服务的参数。 ``` ALTER SERVER server_name [ VERSION 'new_version' ] [ OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ] ) ]; ``` ``` 在OPTIONS选项里,ADD、SET和DROP指定要执行的操作,未指定时默认为ADD操作。option和value为对应操作的参数。 ``` * 修改外部服务的名称。 ``` ALTER SERVER server_name RENAME TO new_name; ``` ## 参数说明 * **server\_name** 所修改的server的名称。 * **new\_version** 修改后server的新版本名称。 * **OPTIONS** 更改该服务器的选项。ADD、SET和 DROP指定要执行的动作。如果没有显式地指定操作, 将会假定为ADD。选项名称必须唯一,名称和值也会使用该服务器的外部数据包装器库进行验证。 * oracle\_fdw支持的options包括: * **dbserver** 远端oracle数据库的连接字符串。 * **isolation\_level** (默认值为serializable) oracle数据库的事务隔离级别。 取值范围:serializable、 read\_committed 、 read\_only * mysql\_fdw支持的options包括: * **host** (默认值为 127.0.0.1) MySQL Server/MariaDB的地址。 * **port** (默认值为 3306) MySQL Server/MariaDB侦听的端口号。 * postgres\_fdw支持的options同libpq支持的连接参数一致,可参考[链接参数](../developer_guide/link_parameters_libpq.md)。需要注意的是,以下几个options不支持修改: * **user**和**password** 用户名和密码将在创建user mapping时指定。 * **client\_encoding** 将自动获取本地server的编码方式并设置该值。 * **application\_name** 总是设置成postgres\_fdw。 除了libpq支持的连接参数外,还额外提供3个options: * **use\_remote\_estimate** 控制postgres\_fdw是否发出EXPLAIN命令以获取运行消耗估算。默认值为false。 * **fdw\_startup\_cost** 执行一个外表扫描时的启动耗时估算。这个值通常包含建立连接、远端对请求的分析和生成计划的耗时。默认值为100。 * **fdw\_typle\_cost** 在远端服务器上对每一个元组进行扫描时的额外消耗。这个值通常表示数据在server间传输的额外消耗。默认值为0.01。 * **new\_name** 修改后server的新名称。 ## 相关链接 [CREATE SERVER](create_server.md),[DROP SERVER](drop_server.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_session.md --- # ALTER SESSION ## Function **ALTER SESSION** defines or modifies the conditions or parameters that affect the current session. Modified session parameters are kept until the current session is disconnected. ## Precautions * If the **START TRANSACTION** statement is not executed before the **SET TRANSACTION** statement, the transaction is ended instantly and the statement does not take effect. * You can use the **transaction\_mode(s)** method declared in the **START TRANSACTION** statement to avoid using the **SET TRANSACTION** statement. ## Syntax * Set transaction parameters of a session. ``` ALTER SESSION SET [ SESSION CHARACTERISTICS AS ] TRANSACTION { ISOLATION LEVEL { READ COMMITTED } | { READ ONLY | READ WRITE } } [, ...] ; ``` * Set other running parameters of a session. ``` ALTER SESSION SET {{config_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }} | TIME ZONE time_zone | CURRENT_SCHEMA schema | NAMES encoding_name | ROLE role_name PASSWORD 'password' | SESSION AUTHORIZATION { role_name PASSWORD 'password' | DEFAULT } | XML OPTION { DOCUMENT | CONTENT } } ; ``` ## Parameter Description For details about the descriptions of parameters related to **ALTER SESSION**, see [Parameter Description](set.md#en-us_topic_0283136841_en-us_topic_0237122186_en-us_topic_0059779029_s39823c7ebd854a9f9c761b3a32b1c3c3) of the SET syntax. ## Examples ``` -- Create the ds schema. openGauss=# CREATE SCHEMA ds; -- Set the search path of the schema. openGauss=# SET SEARCH_PATH TO ds, public; -- Set the time/date type to the traditional Postgres format (date before month). openGauss=# SET DATESTYLE TO postgres, dmy; -- Set the character code of the current session to UTF8. openGauss=# ALTER SESSION SET NAMES 'UTF8'; -- Set the time zone to Berkeley of California. openGauss=# SET TIME ZONE 'PST8PDT'; -- Set the time zone to Italy. openGauss=# SET TIME ZONE 'Europe/Rome'; -- Set the current schema. openGauss=# ALTER SESSION SET CURRENT_SCHEMA TO tpcds; -- Set XML OPTION to DOCUMENT. openGauss=# ALTER SESSION SET XML OPTION DOCUMENT; -- Create the role joe, and set the session role to joe. openGauss=# CREATE ROLE joe WITH PASSWORD 'xxxxxxxxx'; openGauss=# ALTER SESSION SET SESSION AUTHORIZATION joe PASSWORD 'xxxxxxxxx'; -- Switch to the default user. openGauss=> ALTER SESSION SET SESSION AUTHORIZATION default; -- Delete the ds schema. openGauss=# DROP SCHEMA ds; -- Delete the role joe. openGauss=# DROP ROLE joe; ``` ## Helpful Links [SET](set.md) --- --- url: /en/docs/latest/sql_reference/alter_session.md --- # ALTER SESSION ## Function **ALTER SESSION** defines or modifies the conditions or parameters that affect the current session. Modified session parameters are kept until the current session is disconnected. ## Precautions * If the **START TRANSACTION** statement is not executed before the **SET TRANSACTION** statement, the transaction is ended instantly and the statement does not take effect. * You can use the **transaction\_mode(s)** method declared in the **START TRANSACTION** statement to avoid using the **SET TRANSACTION** statement. ## Syntax * Set transaction parameters of a session. ``` ALTER SESSION SET [ SESSION CHARACTERISTICS AS ] TRANSACTION { ISOLATION LEVEL { READ COMMITTED } | { READ ONLY | READ WRITE } } [, ...] ; ``` * Set other running parameters of a session. ``` ALTER SESSION SET {{config_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }} | TIME ZONE time_zone | CURRENT_SCHEMA schema | NAMES encoding_name | ROLE role_name PASSWORD 'password' | SESSION AUTHORIZATION { role_name PASSWORD 'password' | DEFAULT } | XML OPTION { DOCUMENT | CONTENT } } ; ``` ## Parameter Description For details about the descriptions of parameters related to **ALTER SESSION**, see [Parameter Description](set.md#en-us_topic_0283136841_en-us_topic_0237122186_en-us_topic_0059779029_s39823c7ebd854a9f9c761b3a32b1c3c3) of the SET syntax. ## Examples ``` -- Create the ds schema. openGauss=# CREATE SCHEMA ds; -- Set the search path of the schema. openGauss=# SET SEARCH_PATH TO ds, public; -- Set the time/date type to the traditional Postgres format (date before month). openGauss=# SET DATESTYLE TO postgres, dmy; -- Set the character code of the current session to UTF8. openGauss=# ALTER SESSION SET NAMES 'UTF8'; -- Set the time zone to Berkeley of California. openGauss=# SET TIME ZONE 'PST8PDT'; -- Set the time zone to Italy. openGauss=# SET TIME ZONE 'Europe/Rome'; -- Set the current schema. openGauss=# ALTER SESSION SET CURRENT_SCHEMA TO tpcds; -- Set XML OPTION to DOCUMENT. openGauss=# ALTER SESSION SET XML OPTION DOCUMENT; -- Create the role joe, and set the session role to joe. openGauss=# CREATE ROLE joe WITH PASSWORD 'xxxxxxxxx'; openGauss=# ALTER SESSION SET SESSION AUTHORIZATION joe PASSWORD 'xxxxxxxxx'; -- Switch to the default user. openGauss=> ALTER SESSION SET SESSION AUTHORIZATION default; -- Delete the ds schema. openGauss=# DROP SCHEMA ds; -- Delete the role joe. openGauss=# DROP ROLE joe; ``` ## Helpful Links [SET](set.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_session.md --- # ALTER SESSION ## 功能描述 ALTER SESSION命令用于定义或修改那些对当前会话有影响的条件或参数。修改后的会话参数会一直保持,直到断开当前会话。 ## 注意事项 * 如果执行SET TRANSACTION之前没有执行START TRANSACTION,则事务立即结束,命令无法显示效果。 * 可以用START TRANSACTION里面声明所需要的transaction\_mode(s)的方法来避免使用SET TRANSACTION。 ## 语法格式 * 设置会话的事务参数。 ``` ALTER SESSION SET [ SESSION CHARACTERISTICS AS ] TRANSACTION { ISOLATION LEVEL { READ COMMITTED } | { READ ONLY | READ WRITE } } [, ...] ; ``` * 设置会话的其他运行时参数。 ``` ALTER SESSION SET {{config_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }} | TIME ZONE time_zone | CURRENT_SCHEMA schema | NAMES encoding_name | ROLE role_name PASSWORD 'password' | SESSION AUTHORIZATION { role_name PASSWORD 'password' | DEFAULT } | XML OPTION { DOCUMENT | CONTENT } } ; ``` ## 参数说明 修改会话涉及到的参数说明请参见SET语法中的[参数说明](set.md#zh-cn_topic_0283136841_zh-cn_topic_0237122186_zh-cn_topic_0059779029_s39823c7ebd854a9f9c761b3a32b1c3c3)。 ## 示例 ``` -- 创建模式ds。 openGauss=# CREATE SCHEMA ds; --设置模式搜索路径。 openGauss=# SET SEARCH_PATH TO ds, public; --设置日期时间风格为传统的POSTGRES风格(日在月前)。 openGauss=# SET DATESTYLE TO postgres, dmy; --设置当前会话的字符编码为UTF8。 openGauss=# ALTER SESSION SET NAMES 'UTF8'; --设置时区为加州伯克利。 openGauss=# SET TIME ZONE 'PST8PDT'; --设置时区为意大利。 openGauss=# SET TIME ZONE 'Europe/Rome'; --设置当前模式。 openGauss=# ALTER SESSION SET CURRENT_SCHEMA TO tpcds; --设置XML OPTION为DOCUMENT。 openGauss=# ALTER SESSION SET XML OPTION DOCUMENT; --创建角色joe,并设置会话的角色为joe。 openGauss=# CREATE ROLE joe WITH PASSWORD 'xxxxxxxxx'; openGauss=# ALTER SESSION SET SESSION AUTHORIZATION joe PASSWORD 'xxxxxxxxx'; --切换到默认用户。 openGauss=> ALTER SESSION SET SESSION AUTHORIZATION default; --删除ds模式。 openGauss=# DROP SCHEMA ds; --删除joe。 openGauss=# DROP ROLE joe; ``` ## 相关链接 [SET](set.md) --- --- url: /zh/docs/latest/ograc/sql_reference/alter_session.md --- # ALTER SESSION ## 功能描述 调整当前数据库会话的各项配置参数。 ## 注意事项 * 修改会话参数通常需要足够的权限,部分参数仅对当前会话生效。 * 开启 NOLOGGING 等高风险选项后,应主动触发检查点以保证数据持久化。 * 时区、日期格式等设置仅在当前会话内有效,断开后恢复默认值。 ## 语法格式 ```sql ALTER SESSION { SET { COMMIT_WAIT_LOGGING = { WAIT | NOWAIT } | COMMIT_MODE = { IMMEDIATE | BATCH } | _SHOW_EXPLAIN_PREDICATE = { TRUE | FALSE } | _OUTER_JOIN_OPTIMIZATION = { ON | OFF } | TIME_ZONE = '[+|-]hh:mm' | LOCK_WAIT_TIMEOUT = timeout | CURRENT_SCHEMA = schema_value | nls_param = nls_param_value | cbo_param = cbo_param_value } } | { ENABLE | DISABLE } { TRIGGERS | INTERACTIVE TIMEOUT | NOLOGGING | OPTINFO_LOG } ``` ## 参数说明 * **COMMIT\_WAIT\_LOGGING** = { WAIT | NOWAIT } 定义执行提交(COMMIT)操作的服务器进程是否需要等待日志写入器(Log Writer)将重做(Redo)信息完全写入到重做日志文件中。 默认值: WAIT * **WAIT**: 等待 服务器进程将等待确认。在绝大多数场景下,这是推荐且最稳妥的选项。 * **NOWAIT**: 不等待。 不关心重做信息是否已持久化到日志文件,事务立即完成提交。此选项能提升事务处理速度,但存在因系统故障导致数据丢失的风险。 * **COMMIT\_MODE** = { IMMEDIATE | BATCH } 指定日志写入器(Log Writer)处理重做信息的方式。 默认值: IMMEDIATE * **IMMEDIATE**: 立即提交 每次提交事务都立即触发一次日志写入磁盘操作。设置为IMMEDIATE可能会因为频繁的强制磁盘I/O而影响整体的事务吞吐性能。 * **BATCH**: 批量提交。 先将多个事务的重做信息缓存在内存中,当积累到一定量后再批量写入日志文件。设置为BATCH能提高性能,但在实例发生故障时,可能导致尚未写入日志的这批重做信息丢失。 * **\_SHOW\_EXPLAIN\_PREDICATE** = { TRUE | FALSE } 控制执行计划输出中是否包含谓语(过滤条件)信息。 * **TRUE**: 开启 开启后,生成的执行计划将显示相关的谓语条件。 * **FALSE**: 关闭 关闭后,执行计划中不显示谓语条件。 * **\_OUTER\_JOIN\_OPTIMIZATION** = { ON | OFF } 基于成本的优化器(CBO)外连接(Outer Join)重排序优化开关。 * **ON**: 开启 开启后,CBO会尝试对外连接操作进行重新排序以寻找更优的执行计划。 * **OFF**: 关闭 关闭后,CBO将不对外连接操作进行重排序优化。 * **TIME\_ZONE** = '\[+|-]hh:mm' 设定当前会话的时区。通过指定如'\[+|-]hh:mm'格式的字符串(需包含单引号)来设置会话时区相对于协调世界时(UTC,即格林尼治标准时间)的偏移量('+'表示时区早于UTC,'-'表示时区晚于UTC。例如,北京时间为'+08:00')。 要查询当前会话的时区设置,可以执行查询 `SELECT SESSIONTIMEZONE FROM DUAL;`。 默认值:建立会话的客户端操作系统的时区设置。 合法的时区偏移量范围为 -12:00 至 \[+]14:00。 * **LOCK\_WAIT\_TIMEOUT** = timeout 设置当前会话在请求被锁定的资源时,愿意等待的最长时间。 **timeout** 是等待时长,单位为毫秒。表示当会话检测到所需资源被锁定时,会等待指定的timeout时间,若在此期间锁未被释放,则会报出锁等待超时错误。 * **CURRENT\_SCHEMA** = schema\_value 切换当前会话的默认模式(Schema)。默认值为登录用户的模式。 * **若当前位于根租户中**: * 如果 `schema_value` 带有租户前缀,会话将切换至指定非根租户下的模式。 * 如果 `schema_value` 不带租户前缀,会话将切换至根租户下的一个模式。 * **若当前位于非根租户中**: * 如果 `schema_value` 带有租户前缀,该前缀必须与当前租户名一致,否则会报非法操作错误。 * 如果 `schema_value` 不带租户前缀,会话将切换至当前租户下的一个模式。 * **nls\_param** = nls\_param\_value 设置与国家语言支持(NLS)相关的会话参数。 * **nls\_param 可选范围如下**: * **NLS\_DATE\_FORMAT**: 默认值为 `"YYYY-MM-DD HH24:MI:SS"`。 * **NLS\_TIMESTAMP\_FORMAT**: 默认值为 `"YYYY-MM-DD HH24:MI:SS.FF"`。 * **NLS\_TIMESTAMP\_TZ\_FORMAT**: 默认值为 `"YYYY-MM-DD HH24:MI:SS.FF TZH:TZM"`。 * **NLS\_TIME\_FORMAT**: 默认值为 `"HH:MI:SS.FF AM"`。 * **NLS\_TIME\_TZ\_FORMAT**: 默认值为 `"HH:MI:SS.FF AM TZR"`。 * **cbo\_param** = cbo\_param\_value 设置基于成本的优化器(CBO)相关的调优参数。 cbo\_param 可选范围如下: * **CBO\_INDEX\_CACHING**: 整型,取值范围\[0, 100],默认值为0,单位为百分比。 * **CBO\_INDEX\_COST\_ADJ**: 整型,取值范围\[1, 10000],默认值为100,单位为百分比。 * **{ ENABLE | DISABLE } { TRIGGERS | INTERACTIVE TIMEOUT | NOLOGGING | OPTINFO\_LOG }**: * TRIGGERS * **ENABLE(启用)**: 当前会话下执行的 SQL 语句将激活相关的触发器。 * **DISABLE(禁用)**: 当前会话下执行的 SQL 语句不会激活触发器。 * INTERACTIVE TIMEOUT * **ENABLE(启用)**: 开启会话空闲超时检测。默认情况下,若会话连续 30 分钟无 SQL 请求,服务端将自动关闭该会话。 * **DISABLE(禁用)**: 关闭会话空闲超时检测。 * NOLOGGING * **ENABLE(启用)**: 当前会话下,执行插入操作时不记录重做(Redo)日志和回滚(Undo)日志。**警告**:此方式属于高风险操作,不建议常规使用。若必须使用,务必在 NOLOGGING 插入操作完成后,显式执行一次全量检查点(CHECKPOINT)保证数据持久化到磁盘,然后才能进行其他正常业务。否则,若数据库因断电等异常宕机,可能导致无法正常恢复。 * **DISABLE(禁用)**: 当前会话下,执行插入操作时会正常记录重做日志和回滚日志。 * OPTINFO\_LOG * **ENABLE(启用)**: 在当前会话下开启优化器详细日志。执行计划生成的详细过程将被记录到 `log/opt/zengine.opt` 日志文件中。系统默认会在 2 分钟后自动关闭此日志。如需继续使用,需重新执行此命令开启。 * **DISABLE(禁用)**: 在当前会话下关闭优化器详细日志。 ## 示例 * 设置会话在重做信息写入日志文件后再提交事务。 ```sql ALTER SESSION SET COMMIT_WAIT_LOGGING = WAIT; ``` * 设置日志写入器立即写入每个事务的重做信息。 ```sql ALTER SESSION SET COMMIT_MODE = IMMEDIATE; ``` * 将当前会话时区设置为东八区(北京时间)。 ```sql ALTER SESSION SET TIME_ZONE = '+08:00'; ``` * 设置会话的日期显示格式。 ```sql ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'; ``` * 如果存在用户user1,将当前会话的默认模式切换到user1。 ```sql ALTER SESSION SET current_schema = user1; ``` * 开启执行计划中的谓语信息显示。 ```sql ALTER SESSION SET _SHOW_EXPLAIN_PREDICATE = TRUE; ``` * 设置会话锁等待超时时间为0毫秒(即不等待,立即报错)。 ```sql ALTER SESSION SET LOCK_WAIT_TIMEOUT = 0; ``` * 启用当前会话的触发器。 ```sql ALTER SESSION ENABLE TRIGGERS; ``` * 禁用会话空闲超时检测。 ```sql ALTER SESSION DISABLE INTERACTIVE TIMEOUT; ``` * 启用当前会话的NOLOGGING插入模式。 ```sql ALTER SESSION ENABLE NOLOGGING; ``` --- --- url: /zh/docs/latest/sql_reference/alter_session.md --- # ALTER SESSION ## 功能描述 ALTER SESSION命令用于定义或修改那些对当前会话有影响的条件或参数。修改后的会话参数会一直保持,直到断开当前会话。 ## 注意事项 * 如果执行SET TRANSACTION之前没有执行START TRANSACTION,则事务立即结束,命令无法显示效果。 * 可以用START TRANSACTION里面声明所需要的transaction\_mode(s)的方法来避免使用SET TRANSACTION。 ## 语法格式 * 设置会话的事务参数。 ``` ALTER SESSION SET [ SESSION CHARACTERISTICS AS ] TRANSACTION { ISOLATION LEVEL { READ COMMITTED } | { READ ONLY | READ WRITE } } [, ...] ; ``` * 设置会话的其他运行时参数。 ``` ALTER SESSION SET {{config_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }} | TIME ZONE time_zone | CURRENT_SCHEMA schema | NAMES encoding_name | ROLE role_name PASSWORD 'password' | SESSION AUTHORIZATION { role_name PASSWORD 'password' | DEFAULT } | XML OPTION { DOCUMENT | CONTENT } } ; ``` ## 参数说明 修改会话涉及到的参数说明请参见SET语法中的[参数说明](set.md#zh-cn_topic_0283136841_zh-cn_topic_0237122186_zh-cn_topic_0059779029_s39823c7ebd854a9f9c761b3a32b1c3c3)。 ## 示例 ``` -- 创建模式ds。 openGauss=# CREATE SCHEMA ds; --设置模式搜索路径。 openGauss=# SET SEARCH_PATH TO ds, public; --设置日期时间风格为传统的POSTGRES风格(日在月前)。 openGauss=# SET DATESTYLE TO postgres, dmy; --设置当前会话的字符编码为UTF8。 openGauss=# ALTER SESSION SET NAMES 'UTF8'; --设置时区为加州伯克利。 openGauss=# SET TIME ZONE 'PST8PDT'; --设置时区为意大利。 openGauss=# SET TIME ZONE 'Europe/Rome'; --设置当前模式。 openGauss=# ALTER SESSION SET CURRENT_SCHEMA TO tpcds; --设置XML OPTION为DOCUMENT。 openGauss=# ALTER SESSION SET XML OPTION DOCUMENT; --创建角色joe,并设置会话的角色为joe。 openGauss=# CREATE ROLE joe WITH PASSWORD 'xxxxxxxxx'; openGauss=# ALTER SESSION SET SESSION AUTHORIZATION joe PASSWORD 'xxxxxxxxx'; --切换到默认用户。 openGauss=> ALTER SESSION SET SESSION AUTHORIZATION default; --删除ds模式。 openGauss=# DROP SCHEMA ds; --删除joe。 openGauss=# DROP ROLE joe; ``` ## 相关链接 [SET](set.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_subscription.md --- # ALTER SUBSCRIPTION ## Function Description **ALTER SUBSCRIPTION** alters the attributes of a subscription specified in **CREATE SUBSCRIPTION**. ## Precautions Only the owner of a subscription can execute **ALTER SUBSCRIPTION**, and the new owner must be a system administrator. ## Syntax * Update the connection information of a subscription. ``` ALTER SUBSCRIPTION name CONNECTION 'conninfo' ``` * Update the name of the publication on the publisher side. ``` ALTER SUBSCRIPTION name SET PUBLICATION publication_name [, ...] ``` * Update the name of the publication on the publisher side. ``` ALTER SUBSCRIPTION name REFRESH PUBLICATION [ WITH ( refresh_option [= value] [, ... ] ) ] ``` * Enable a subscription. ``` ALTER SUBSCRIPTION name ENABLE ``` * Update the attributes defined in **CREATE SUBSCRIPTION**. ``` ALTER SUBSCRIPTION name SET ( subscription_parameter [= value] [, ... ] ) ``` * Update the owner of a subscription. ``` ALTER SUBSCRIPTION name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * Change the name of a subscription. ``` ALTER SUBSCRIPTION name RENAME TO new_name ``` ## Parameter Description * **name** Specifies the name of the subscription whose attributes are to be altered. * **CONNECTION 'conninfo'** Alters the connection attributes initially set by **CREATE SUBSCRIPTION**. * **ENABLE (boolean)** Specifies whether a subscription should be actively replicated, or whether it should be just set but not started. The default value is **true**. * **SET ( subscription\_parameter \[= value] \[, ... ] )** Modifies the parameters set by **CREATE SUBSCRIPTION**. The allowed parameters are **slot\_name** and **synchronous\_commit**. * If **enabled** is set to **false** during subscription creation, **slot\_name** is forcibly set to **NONE**, that is, null. In this case, the replication slot does not exist even if the value of **slot\_name** is specified. * Change the value of **enabled** from **false** to **true**. When the subscription is enabled, the publication side is connected to create a replication slot. If you do not specify the value of **slot\_name**, the default value (subscription name) is used. * If **enabled** is set to **true**, the subscription is in the normal state. In this case, **slot\_name** cannot be left empty, but the name of the replication slot can be changed to a valid name. * **REFRESH PUBLICATION** Obtains the missing table information from the publisher. Tables added to the subscription publication are copied since the last REFRESH PUBLICATION or CREATE SUBSCRIPTION call. The refresh\_option specifies additional options for the refresh operation. The options are as follows: copy\_data (boolean) Determines whether to copy existing data in the publication that is being subscribed to after copy starts. The default value is **true**. (Tables previously subscribed to will not be copied.) * **new\_owner** Specifies the username of the new owner of a subscription. * **new\_name** Specifies the new name of a subscription. ## Example For details, see [Examples](create_subscription.md#section1399192015610). ## Helpful Links [CREATE SUBSCRIPTION](create_subscription.md), [DROP SUBSCRIPTION](drop_subscription.md) --- --- url: /en/docs/latest/sql_reference/alter_subscription.md --- # ALTER SUBSCRIPTION ## Function **ALTER SUBSCRIPTION** alters the attributes of a subscription specified in **CREATE SUBSCRIPTION**. ## Precautions Only the owner of a subscription can execute **ALTER SUBSCRIPTION**, and the new owner must be a system administrator. ## Syntax * Update the connection information of a subscription. ``` ALTER SUBSCRIPTION name CONNECTION 'conninfo' ``` * Update the name of a publication on the publisher side. ``` ALTER SUBSCRIPTION name SET PUBLICATION publication_name [, ...] ``` * Update the subscription list on the subscriber side. ``` ALTER SUBSCRIPTION name REFRESH PUBLICATION [ WITH ( refresh_option [= value] [, ... ] ) ] ``` * Enable a subscription. ``` ALTER SUBSCRIPTION name ENABLE ``` * Update the attributes defined in **CREATE SUBSCRIPTION**. ``` ALTER SUBSCRIPTION name SET ( subscription_parameter [= value] [, ... ] ) ``` * Update the owner of a subscription. ``` ALTER SUBSCRIPTION name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * Change the name of a subscription. ``` ALTER SUBSCRIPTION name RENAME TO new_name ``` ## Parameter Description * **name** Specifies the name of a subscription whose attributes are to be altered. * **CONNECTION 'conninfo'** Alters the connection attributes initially set by **CREATE SUBSCRIPTION**. * **ENABLE (boolean)** Specifies whether a subscription should be actively replicated, or whether it should be just set but not yet started. The default value is **true**. * **SET ( subscription\_parameter \[= value] \[, ... ] )** Modifies the parameters set by **CREATE SUBSCRIPTION**. The allowed parameters are **slot\_name** and **synchronous\_commit**. * If **enabled** is set to **false** during subscription creation, **slot\_name** is forcibly set to **NONE**, that is, null. In this case, the replication slot does not exist even if the value of **slot\_name** is specified. * Change the value of **enabled** from **false** to **true**. When the subscription is enabled, the publication side is connected to create a replication slot. If you do not specify the value of **slot\_name**, the default value (subscription name) is used. * If **enabled** is set to **true**, the subscription is in the normal state. In this case, **slot\_name** cannot be left empty, but the name of the replication slot can be changed to a valid name. * **REFRESH PUBLICATION** Obtains the missing table information from the publisher. Tables added to the subscription publication are copied since the last REFRESH PUBLICATION or CREATE SUBSCRIPTION call. refresh\_option specifies additional options for the refresh operation. The options are as follows: copy\_data (boolean) Determines whether to copy existing data in the publication that is being subscribed to after copy starts. The default value is **true**. (Tables previously subscribed to will not be copied.) * **new\_owner** Specifies the username of the new owner of a subscription. * **new\_name** Specifies the new name of a subscription. ## Examples For details, see [Examples](create_subscription.md#section1399192015610). ## Helpful Links [CREATE SUBSCRIPTION](create_subscription.md) and [DROP SUBSCRIPTION](drop_subscription.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_subscription.md --- # ALTER SUBSCRIPTION ## 功能描述 ALTER SUBSCRIPTION可以修改在CREATE SUBSCRIPTION中指定的订阅属性。 ## 注意事项 订阅的所有者才能执行ALTER SUBSCRIPTION,并且新的所有者必须是系统管理员。 ## 语法格式 * 更新订阅的连接信息。 ``` ALTER SUBSCRIPTION name CONNECTION 'conninfo' ``` * 更新订阅的发布端的发布名称。 ``` ALTER SUBSCRIPTION name SET PUBLICATION publication_name [, ...] ``` * 更新订阅的发布端的发布名称。 ``` ALTER SUBSCRIPTION name REFRESH PUBLICATION [ WITH ( refresh_option [= value] [, ... ] ) ] ``` * 激活订阅。 ``` ALTER SUBSCRIPTION name ENABLE ``` * 禁用订阅。 ``` ALTER SUBSCRIPTION name DISABLE ``` * 更新CREATE SUBSCRIPTION中定义的属性。 ``` ALTER SUBSCRIPTION name SET ( subscription_parameter [= value] [, ... ] ) ``` * 更新订阅的属主。 ``` ALTER SUBSCRIPTION name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * 修改订阅的名称。 ``` ALTER SUBSCRIPTION name RENAME TO new_name ``` ## 参数说明 * **name** 要修改属性的订阅的名称。 * **CONNECTION 'conninfo'** 该子句修改最初由CREATE SUBSCRIPTION设置的连接属性。 * **ENABLE** 启用先前禁用的订阅,在事务结束时启动逻辑复制工作。 * **DISABLE** 禁用正在运行的订阅,在事务结束时停止逻辑复制工作。 * **SET ( subscription\_parameter \[= value] \[, ... ] )** 该子句修改原先由CREATE SUBSCRIPTION设置的参数。允许的选项是slot\_name和synchronous\_commit。 * 如果创建订阅时设置enabled为false,则slot\_name将被强制设置为NONE,即空值,即使用户指定了slot\_name的值,复制槽也不存在。 * 将enabled参数的值由false改为true,如果是第一次启用订阅,将会连接发布端创建复制槽,此时如果用户未指定slot\_name参数的值,则会使用默认值,即对应的订阅的名称。 * 将enabled参数的值由true改为false,将会禁用订阅,暂停数据同步。 * 当enabled为true,即订阅处于正常使用状态,不能修改slot\_name为空,但可以修改复制槽的名称为其他非空合法名称。 除了修改原先由CREATE SUBSCRIPTION设置的参数外,还允许设置skiplsn,说明如下。 * **skiplsn (string)** 如果设置了skiplsn,则后续commit\_lsn为该lsn的事务将会被跳过。 * **syncconninfo(bolean)** 如果设置为syncconninfo=false,则发布端主备切换后不会同步连接信息。 * **REFRESH PUBLICATION** 从发布端获取缺少的表信息。这将开始复制自上次调用REFRESH PUBLICATION或从CREATE SUBSCRIPTION以来添加到订阅发布中的表。 refresh\_option指定了刷新操作的附加选项。支持的选项有: copy\_data (boolean) 指定在复制启动后是否应复制正在订阅的发布中的现有数据。默认值是true。(以前订阅的表不会被复制) * **new\_owner** 订阅的新所有者的用户名。 * **new\_name** 订阅的新名称。 ## 示例 请参见[示例](create_subscription.md#section1399192015610)。 ## 相关链接 [CREATE SUBSCRIPTION](create_subscription.md),[DROP SUBSCRIPTION](drop_subscription.md) --- --- url: /zh/docs/latest/sql_reference/alter_subscription.md --- # ALTER SUBSCRIPTION ## 功能描述 ALTER SUBSCRIPTION可以修改在CREATE SUBSCRIPTION中指定的订阅属性。 ## 注意事项 订阅的所有者才能执行ALTER SUBSCRIPTION,并且新的所有者必须是系统管理员。 ## 语法格式 * 更新订阅的连接信息。 ``` ALTER SUBSCRIPTION name CONNECTION 'conninfo' ``` * 更新订阅的发布端的发布名称。 ``` ALTER SUBSCRIPTION name SET PUBLICATION publication_name [, ...] ``` * 更新订阅的订阅列表。 ``` ALTER SUBSCRIPTION name REFRESH PUBLICATION [ WITH ( refresh_option [= value] [, ... ] ) ] ``` * 激活订阅。 ``` ALTER SUBSCRIPTION name ENABLE ``` * 禁用订阅。 ``` ALTER SUBSCRIPTION name DISABLE ``` * 更新CREATE SUBSCRIPTION中定义的属性。 ``` ALTER SUBSCRIPTION name SET ( subscription_parameter [= value] [, ... ] ) ``` * 更新订阅的属主。 ``` ALTER SUBSCRIPTION name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * 修改订阅的名称。 ``` ALTER SUBSCRIPTION name RENAME TO new_name ``` ## 参数说明 * **name** 要修改属性的订阅的名称。 * **CONNECTION 'conninfo'** 该子句修改最初由CREATE SUBSCRIPTION设置的连接属性。 * **ENABLE** 启用先前禁用的订阅,在事务结束时启动逻辑复制工作。 * **DISABLE** 禁用正在运行的订阅,在事务结束时停止逻辑复制工作。 * **SET ( subscription\_parameter \[= value] \[, ... ] )** 该子句修改原先由CREATE SUBSCRIPTION设置的参数。允许的选项是slot\_name和synchronous\_commit。 * 如果创建订阅时设置enabled为false,则slot\_name将被强制设置为NONE,即空值,即使用户指定了slot\_name的值,复制槽也不存在。 * 将enabled参数的值由false改为true,如果是第一次启用订阅,将会连接发布端创建复制槽,此时如果用户未指定slot\_name参数的值,则会使用默认值,即对应的订阅的名称。 * 将enabled参数的值由true改为false,将会禁用订阅,暂停数据同步。 * 当enabled为true,即订阅处于正常使用状态,不能修改slot\_name为空,但可以修改复制槽的名称为其他非空合法名称。 除了修改原先由CREATE SUBSCRIPTION设置的参数外,还允许设置skiplsn,说明如下。 * **skiplsn (string)** 如果设置了skiplsn,则后续commit\_lsn为该lsn的事务将会被跳过。 * **syncconninfo(bolean)** 如果设置为syncconninfo=false,则发布端主备切换后不会同步连接信息。 * **REFRESH PUBLICATION** 从发布端获取缺少的表信息。这将开始复制自上次调用REFRESH PUBLICATION或从CREATE SUBSCRIPTION以来添加到订阅发布中的表。 refresh\_option指定了刷新操作的附加选项。支持的选项有: copy\_data (boolean) 指定在复制启动后是否应复制正在订阅的发布中的现有数据。默认值是true。(以前订阅的表不会被复制) * **new\_owner** 订阅的新所有者的用户名。 * **new\_name** 订阅的新名称。 ## 示例 请参见[示例](create_subscription.md#section1399192015610)。 ## 相关链接 [CREATE SUBSCRIPTION](create_subscription.md),[DROP SUBSCRIPTION](drop_subscription.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_synonym.md --- # ALTER SYNONYM ## Function **ALTER SYNONYM** modifies the attributes of the **SYNONYM** object. ## Precautions * Currently, only the owner of the **SYNONYM** object can be changed. * Only the system administrator has the permission to modify the owner of the **SYNONYM** object. * The new owner must have the **CREATE** permission on the schema where the **SYNONYM** object resides. ## Syntax ``` ALTER SYNONYM synonym_name OWNER TO new_owner; ``` ## Parameter Description * **synonym** Specifies the name of the synonym to be modified, which can contain the schema name. Value range: a string. It must comply with the identifier naming convention. * **new\_owner** Specifies the new owner of the **SYNONYM** object. Value range: a string. It must be a valid username. ## Examples ``` -- Create synonym t1. openGauss=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1; -- Create user u1. openGauss=# CREATE USER u1 PASSWORD 'xxxxxx'; -- Change the owner of synonym t1 to u1. openGauss=# ALTER SYNONYM t1 OWNER TO u1; -- Delete synonym t1. openGauss=# DROP SYNONYM t1; -- Delete user u1. openGauss=# DROP USER u1; ``` ## Helpful Links [CREATE SYNONYM](create_synonym.md) and [DROP SYNONYM](drop_synonym.md) --- --- url: /en/docs/latest/sql_reference/alter_synonym.md --- # ALTER SYNONYM ## Function **ALTER SYNONYM** modifies the attributes of the **SYNONYM** object. ## Precautions * Currently, only the owner of the **SYNONYM** object can be changed. * Only the system administrator has the permission to modify the owner of the **SYNONYM** object. * The new owner must have the **CREATE** permission on the schema where the **SYNONYM** object resides. ## Syntax ``` ALTER SYNONYM synonym_name OWNER TO new_owner; ``` ## Parameter Description * **synonym** Specifies the name of the synonym to be modified, which can contain the schema name. Value range: a string. It must comply with the identifier naming convention. * **new\_owner** Specifies the new owner of the **SYNONYM** object. Value range: a string. It must be a valid username. ## Examples ``` -- Create synonym t1. openGauss=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1; -- Create user u1. openGauss=# CREATE USER u1 PASSWORD 'user@111'; -- Change the owner of synonym t1 to u1. openGauss=# ALTER SYNONYM t1 OWNER TO u1; -- Delete synonym t1. openGauss=# DROP SYNONYM t1; -- Delete user u1. openGauss=# DROP USER u1; ``` ## Helpful Links [CREATE SYNONYM](create_synonym.md) and [DROP SYNONYM](drop_synonym.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_synonym.md --- # ALTER SYNONYM ## 功能描述 修改SYNONYM对象的属性。 ## 注意事项 * 目前仅支持修改SYNONYM对象的属主。 * 只有系统管理员有权限修改SYNONYM对象的属主信息。 * 新属主必须具有SYNONYM对象所在模式的CREATE权限。 ## 语法格式 ``` ALTER SYNONYM synonym_name OWNER TO new_owner; ``` ## 参数描述 * **synonym** 待修改的同义词名字,可以带模式名。 取值范围:字符串,需要符合标识符的命名规范。 * **new\_owner** 同义词对象的新所有者。 取值范围:字符串,有效的用户名。 ## 示例 ``` --创建系统管理员用户。 openGauss=# CREATE USER sysadmin WITH SYSADMIN PASSWORD 'XXXXXXXX'; --切换管理员用户。 openGauss=# \c - sysadmin --创建同义词t1。 openGauss=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1; --创建新用户u1。 gaussdbopenGauss=# CREATE USER u1 PASSWORD 'XXXXXXXX'; --给新用户赋权限。 openGauss=# GRANT ALL ON SCHEMA sysadmin TO u1; --修改同义词t1的owner为u1。 openGauss=# ALTER SYNONYM t1 OWNER TO u1; --删除同义词t1。 openGauss=# DROP SYNONYM t1; --收回用户u1权限。 openGauss=# REVOKE ALL ON SCHEMA sysadmin FROM u1; --删除用户u1。 openGauss=# DROP USER u1; ``` ## 相关链接 [CREATE SYNONYM](create_synonym.md),[DROP SYNONYM](drop_synonym.md) --- --- url: /zh/docs/latest/sql_reference/alter_synonym.md --- # ALTER SYNONYM ## 功能描述 修改SYNONYM对象的属性。 ## 注意事项 * 目前仅支持修改SYNONYM对象的属主。 * 只有系统管理员有权限修改SYNONYM对象的属主信息。 * 新属主必须具有SYNONYM对象所在模式的CREATE权限。 ## 语法格式 ``` ALTER SYNONYM synonym_name OWNER TO new_owner; ``` ## 参数描述 * **synonym** 待修改的同义词名字,可以带模式名。 取值范围:字符串,需要符合标识符的命名规范。 * **new\_owner** 同义词对象的新所有者。 取值范围:字符串,有效的用户名。 ## 示例 ``` --创建系统管理员用户。 openGauss=# CREATE USER sysadmin WITH SYSADMIN PASSWORD 'XXXXXXXX'; --切换管理员用户。 openGauss=# \c - sysadmin --创建同义词t1。 openGauss=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1; --创建新用户u1。 gaussdbopenGauss=# CREATE USER u1 PASSWORD 'XXXXXXXX'; --给新用户赋权限。 openGauss=# GRANT ALL ON SCHEMA sysadmin TO u1; --修改同义词t1的owner为u1。 openGauss=# ALTER SYNONYM t1 OWNER TO u1; --删除同义词t1。 openGauss=# DROP SYNONYM t1; --收回用户u1权限。 openGauss=# REVOKE ALL ON SCHEMA sysadmin FROM u1; --删除用户u1。 openGauss=# DROP USER u1; ``` ## 相关链接 [CREATE SYNONYM](create_synonym.md),[DROP SYNONYM](drop_synonym.md) --- --- url: /zh/docs/latest/ograc/sql_reference/alter_system.md --- # ALTER SYSTEM ## 功能描述 修改数据库系统参数或执行特定的系统级操作。 ## 注意事项 执行该语句需要拥有 ALTER SYSTEM 系统权限。 ## 语法格式 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 | PBL} CONFIG | REFRESH SYSDBA PRIVILEGE | KILL SESSION 'session\_id,serial' | RESET STATISTIC | CHECKPOINT |{ ADD | DELETE } LSNR\_ADDR LISTENING\_IP |{ ADD | DELETE } HBA ENTRY hba\_conf\_entry | FLUSH {BUFFER | SQLPOOL} | DEBUG MODE debug\_parameter\_name = debug\_parameter\_value | DUMP CATALOG { TABLE table\_name | USER user\_name } \[ TO 'folders' ] | RECYCLE SHAREDPOOL \[FORCE] | REPAIR CATALOG } ## 参数说明 * **DUMP DATAFILE** ***file\_id*** **PAGE** ***page\_id*** 导出指定数据文件的特定页。 * ***file\_id*** 文件编号,取值范围\[0, 2147483648)。可通过查询DBA视图ADM\_DATA\_FILES中的FILE\_ID字段获取。 * ***page\_id*** 页编号,取值范围\[1, 2147483648),正整数,必须小于文件使用页数的高水位线。 高水位线可通过查询动态性能视图DV\_DATA\_FILES的HIGH\_WATER\_MARK字段获取。 * **SWITCH LOGFILE**: 切换当前日志文件。 * **SET** ***parameter\_name*** **=** ***parameter\_value*** **\[ SCOPE = { MEMORY | PFILE | BOTH } ]** 修改系统参数。SCOPE指定为PFILE和BOTH时,参数将被保存在Zenith.ini配置文件中。`SCOPE` 定义生效范围:\ • **MEMORY**:仅内存生效,重启失效。只适用于动态参数,不允许静态参数使用此模式设置。 • **PFILE**:仅写入配置文件,重启生效。动态参数与静态参数都一样可以。也是静态参数唯一可以使用的方式。 • **BOTH**:既写入到初始化参数文件,也在内存上修改,立即生效。同样也只适用于动态参数,静态参数则不允许。(默认) * **LOAD DICTIONARY FOR \[schema\_name].object\_name**: 加载对象到数据字典中。 * **INIT DICTIONARY**: 加载除系统表以外的entry(系统视图,动态视图,sequence,role等)。 前提:进入 restricted 模式,且确保已经通过 `ALTER SYSTEM LOAD DICTIONARY FOR [schema_name].object_name;` 加载所有系统表。 * **RELOAD {HBA | PBL} CONFIG**: 在线加载 oghba.conf 文件,使白名单配置生效。 在线加载 pbl.conf 文件,使弱口令配置生效。 * **REFRESH SYSDBA PRIVILEGE**: 在线刷新 SYSDBA 免密登录的密文和加密密钥。不影响已连接客户端,新连接将使用新密钥。 * **KILL SESSION** ***'******session\_id******,******serial******'*** 终止会话,session\_id是会话ID,serial是序列号ID。 * **RESET STATISTIC**: 清空动态视图DV\_SYS\_STATS的计数。 * **CHECKPOINT**: 为当前实例执行检查点,确保已提交事务的所有更改写入磁盘。 * **{ ADD | DELETE } LSNR\_ADDR** ***LISTENING\_IP*** 要增/删的监听 IP 地址(需引号包裹)。当前 最多支持 8 个监听 IP。 增加一个不存在网卡的IP地址作为浮动监听IP时,直接返回报错。 **注意**:删除正在使用的 IP 会导致相关连接中断并回滚事务。 * **{ ADD | DELETE } HBA ENTRY** ***hba\_conf\_entry*** 向用户白名单文件oghba.conf中增加或删除一条用户白名单。 * ***hba\_conf\_entry*** 格式为'type user address',参数说明请参考表1。 * **type**: 建立连接的类型。 * **host**: 普通 TCP 或 SSL 连接。 * **hostssl**: 仅 SSL 连接(若服务端开启 SSL 而客户端未配置,则拒绝连接)。 * **user**: 允许访问数据库的指定用户。`*` 表示所有用户。若用户名含特殊字符(如 #、\*、TAB),需用双引号包裹,如 "#abc"。单行仅能指定一个用户。 * **address**: 允许访问的 IP 地址范围(支持逗号分隔多个)。IP 地址支持 IPv4、IPv6 地址、或指定子网掩码长度表示一个子网网段。支持格式: * **IPv4/IPv6 单地址**: 192.168.1.111、20AB::9217:acff:feab:fcd0 * **子网掩码**: 192.168.2.0/24、20CD::2654:addf:3ab2:fed0/64 * **全网段**: *.*.*.* 或 0.0.0.0/0 * **FLUSH BUFFER**: 清空数据库缓存数据。 * **FLUSH SQLPOOL**: 清空SQL池缓存数据。 * **DEBUG MODE** ***debug\_parameter\_name*** **=** ***debug\_parameter\_value*** 调试参数名(仅限开发使用,用户禁止修改,否则会造成数据库异常)。立即生效,所有debug参数不会写入配置文件,仅保存在内存中,重启后可还原。 调试参数仅限开发调试使用,用户禁止修改,否则会造成数据库异常。     DUMP CATALOG TABLE *table\_name*     导出指定表的数据字典内存信息及关联索引信息。     DUMP CATALOG USER *user\_name*     导出指定用户的数据字典内存信息。     \[ TO '*folder*s']     指定dump输出目录(默认存放于 `trc` 文件夹)。     导出文件上限为 10 MB,超过10M则报错,需将文件删除后SYS 用户可导出所有用户信息;普通用户仅可导出自身信息;DBA 用户可导出普通用户和其他 DBA 用户信息。重新进行DUMP操作。     SYS用户可以DUMP所有用户的信息;普通用户只可以DUMP自己的信息;DBA用户可以DUMP普通用户和其他DBA用户下的信息。 * **RECYCLE SHAREDPOOL \[FORCE]**: 回收DC POOL/SQL POOL到共享区。 FORCE表示会强制把SQL POOL里面所有软解析标志为FALSE。 * **REPAIR CATALOG**: 修复核心系统表列定义不一致的场景(如升级后二进制记录与 data 中表结构不符)。 ## 示例 * 导出数据文件的指定页。 ```sql --删除表空间 DROP TABLESPACE IF EXISTS test_space; ``` ``` --创建表空间 CREATE TABLESPACE video_space DATAFILE 'test_dfile1' SIZE 32M; ``` ``` --查询FILE_ID SELECT FILE_NAME,FILE_ID FROM ADM_DATA_FILES WHERE FILE_NAME='/opt/ograc/data/data/test_dfile1'; ``` ``` --查询数据文件的高水位线 SELECT * FROM DV_DATA_FILES WHERE FILE_NAME='/opt/ograc/data/data/test_dfile1'; ``` ``` --导出数据文件第一页(假设 FILE_ID=17) ALTER SYSTEM DUMP datafile 17 PAGE 1; ``` 切换日志文件。 ``` ALTER SYSTEM SWITCH LOGFILE; ``` * 修改参数UNDO\_RETENTION\_TIME的值为1200秒,只在内存上修改(立即生效,重启失效)。 ``` --查询当前值 SHOW PARAMETER UNDO_RETENTION_TIME; ``` ``` --修改值 ALTER SYSTEM SET UNDO_RETENTION_TIME=1200 SCOPE=MEMORY; ``` * 加载表到数据字典中。 ``` --删除表education。 DROP TABLE IF EXISTS education; --创建表education。 CREATE TABLE education(staff_id INT, highest_degree CHAR(8) NOT NULL, graduate_school VARCHAR(64), graduate_date DATETIME, education_note VARCHAR(70)); --加载表education到数据字典中。 ALTER SYSTEM LOAD DICTIONARY FOR education; ``` * 加载除系统表以外的其余类型entry(系统视图,动态视图,sequence,role等)。 前提:已进入 restricted 模式并确保所有系统表已经通过ALTER SYSTEM LOAD DICTIONARY FOR \[schema\_name].object\_name 语句加载后。 ``` ALTER SYSTEM INIT DICTIONARY; ``` * 在线加载oghba.conf文件。 ``` ALTER SYSTEM RELOAD HBA CONFIG; ``` * 增加监听IP地址。 ``` ALTER SYSTEM ADD LSNR_ADDR '10.10.10.11'; ``` * 删除监听IP地址。 ```sql ALTER SYSTEM DELETE LSNR_ADDR '10.10.10.11'; ``` * 刷新 SYSDBA 免密登录的密文、加密密钥。 ```sql ALTER SYSTEM REFRESH SYSDBA PRIVILEGE; ``` * 清理动态视图DV\_SYS\_STATS统计信息。 ```sql ALTER SYSTEM RESET STATISTIC; ``` * 为当前实例执行检查点。 ```sql ALTER SYSTEM CHECKPOINT; ``` * 清空缓存数据。 清空数据库缓存数据。 ```sql ALTER SYSTEM FLUSH BUFFER; ```         清空SQL池缓存数据。 ```sql ALTER SYSTEM FLUSH SQLPOOL; ``` * 修改数据库调试参数。 ```sql ALTER SYSTEM DEBUG MODE _MRP_RES_LOGSIZE = 1G; ``` * 导出数据字典信息。 ``` ALTER SYSTEM DUMP CATALOG TABLE TEST; ALTER SYSTEM DUMP CATALOG USER TEST; ``` * --- --- url: /en/docs/latest-lite/sql_reference/alter_system_kill_session.md --- # ALTER SYSTEM KILL SESSION ## Function **ALTER SYSTEM KILL SESSION** ends a session. ## Precautions None ## Syntax ``` ALTER SYSTEM KILL SESSION 'session_sid, serial' [ IMMEDIATE ]; ``` ## Parameter Description * **session\_sid, serial** Specifies the SID and SERIAL of a session (To obtain the values, see the example.) * **IMMEDIATE** Specifies that a session will be ended instantly after the statement is executed. ## Examples ``` -- Query session information. openGauss=# SELECT sa.sessionid AS sid,0::integer AS serial#,ad.rolname AS username FROM pg_stat_get_activity(NULL) AS sa LEFT JOIN pg_authid ad ON(sa.usesysid = ad.oid)WHERE sa.application_name <> 'JobScheduler'; sid | serial# | username -----------------+---------+---------- 140131075880720 | 0 | omm 140131025549072 | 0 | omm 140131073779472 | 0 | omm 140131071678224 | 0 | omm 140131125774096 | 0 | 140131127875344 | 0 | 140131113629456 | 0 | 140131094742800 | 0 | (8 rows) -- End the session whose SID is 140131075880720. openGauss=# ALTER SYSTEM KILL SESSION '140131075880720,0' IMMEDIATE; ``` --- --- url: /en/docs/latest/sql_reference/alter_system_kill_session.md --- # ALTER SYSTEM KILL SESSION ## Function **ALTER SYSTEM KILL SESSION** ends a session. ## Precautions None ## Syntax ``` ALTER SYSTEM KILL SESSION 'session_sid, serial' [ IMMEDIATE ]; ``` ## Parameter Description * **session\_sid, serial** Specifies the SID and SERIAL of a session (To obtain the values, see the example.) * **IMMEDIATE** Specifies that a session will be ended instantly after the statement is executed. ## Examples ``` -- Query session information. openGauss=# SELECT sa.sessionid AS sid,0::integer AS serial#,ad.rolname AS username FROM pg_stat_get_activity(NULL) AS sa LEFT JOIN pg_authid ad ON(sa.usesysid = ad.oid)WHERE sa.application_name <> 'JobScheduler'; sid | serial# | username -----------------+---------+---------- 140131075880720 | 0 | omm 140131025549072 | 0 | omm 140131073779472 | 0 | omm 140131071678224 | 0 | omm 140131125774096 | 0 | 140131127875344 | 0 | 140131113629456 | 0 | 140131094742800 | 0 | (8 rows) -- End the session whose SID is 140131075880720. openGauss=# ALTER SYSTEM KILL SESSION '140131075880720,0' IMMEDIATE; ``` --- --- url: /zh/docs/latest-lite/sql_reference/alter_system_kill_session.md --- # ALTER SYSTEM KILL SESSION ## 功能描述 ALTER SYSTEM KILL SESSION命令用于结束一个会话。 ## 注意事项 无。 ## 语法格式 ``` ALTER SYSTEM KILL SESSION 'thread_id, session_id' [ IMMEDIATE ]; ``` ## 参数说明 * **thread\_id, session\_id** 会话对应的的线程ID和会话的SID * **IMMEDIATE** 表明会话将在命令执行后立即结束。 ## 示例 ``` -- 查询当前是否开启线程池模式 openGauss=# show enable_thread_pool; enable_thread_pool -------------------- off (1 row) -- 查询会话信息。 openGauss=# select pid, sessionid, usename, application_name from pg_stat_activity where usename = 'omm'; pid | sessionid | usename | application_name -----------------+-----------------+----------+------------------------ 140114517817088 | 140114517817088 | omm | gsql 140114743260928 | 140114743260928 | omm | WLMArbiter 140114791495424 | 140114791495424 | omm | workload 140114766329600 | 140114766329600 | omm | WorkloadMonitor 140115301627648 | 140115301627648 | omm | CfsShrinker 140115220821760 | 140115220821760 | omm | statement flush thread 140115240285952 | 140115240285952 | omm | Asp 140115336230656 | 140115336230656 | omm | TxnSnapCapturer 140115460486912 | 140115460486912 | omm | JobScheduler 140115380795136 | 140115380795136 | omm | ApplyLauncher 140115266434816 | 140115266434816 | omm | PercentileJob (11 rows) -- 结束当前gsql连接会话,当前会话会断开并重新连接 openGauss=# ALTER SYSTEM KILL SESSION '140114517817088, 140114517817088'; FATAL: terminating connection due to administrator command FATAL: terminating connection due to administrator command The connection to the server was lost. Attempting reset: Succeeded. ``` --- --- url: /zh/docs/latest/ograc/sql_reference/alter_system_kill_session.md --- # ALTER SYSTEM KILL SESSION ## 功能描述 终止指定数据库会话连接。 ## 注意事项 * **权限要求**:执行此操作需要拥有 `ALTER SYSTEM` 系统权限。 * **限制**: * 无法终止当前登录的自身会话。 * 无法终止系统保留的核心会话。 ## 语法格式 ```sql ALTER SYSTEM KILL SESSION 'session_id,serial#'; ``` ## 参数说明 * **session\_id**: 会话标识符(SID)。 * **serial#**: 会话序列号。 ## 示例 准备工作: ``` -- 删除用户(如果存在) DROP USER DDMUSER CASCADE; -- 创建用户 CREATE USER DDMUSER IDENTIFIED BY password; -- 授予基本权限 GRANT CONNECT, RESOURCE TO DDMUSER; -- 授予会话查看权限 GRANT SELECT ON DV_SESSIONS TO DDMUSER; -- 授予会话终止权限 GRANT ALTER SYSTEM TO DDMUSER; ``` 连接数据库进程: ``` -- 使用DDMUSER连接数据库 conn DDMUSER/password@127.0.0.1:1611 -- 查询DDMUSER用户的会话信息 SELECT SID, SPID, SERIAL#, USERNAME, CLIENT_IP FROM DV_SESSIONS WHERE USERNAME = 'DDMUSER'; SID SPID SERIAL# USERNAME CLIENT_IP ------------ ----------- ------------ ---------------------------------------------------------------- ---------------------------------------------------------------- 130 639782 185 DDMUSER 127.0.0.1 174 637288 184 DDMUSER 127.0.0.1 2 rows fetched. ``` 终止指定的非当前会话: ``` ALTER system kill session '174,184'; ``` 如果尝试执行结束当前会话会失败,错误信息:The current session cannot be killed。 --- --- url: /zh/docs/latest/sql_reference/alter_system_kill_session.md --- # ALTER SYSTEM KILL SESSION ## 功能描述 ALTER SYSTEM KILL SESSION命令用于结束一个会话。 ## 注意事项 无。 ## 语法格式 ``` ALTER SYSTEM KILL SESSION 'thread_id, session_id' [ IMMEDIATE ]; ``` ## 参数说明 * **thread\_id, session\_id** 会话对应的的线程ID和会话的SID * **IMMEDIATE** 表明会话将在命令执行后立即结束。 ## 示例 ``` -- 查询当前是否开启线程池模式 openGauss=# show enable_thread_pool; enable_thread_pool -------------------- off (1 row) -- 查询会话信息。 openGauss=# select pid, sessionid, usename, application_name from pg_stat_activity where usename = 'omm'; pid | sessionid | usename | application_name -----------------+-----------------+----------+------------------------ 140114517817088 | 140114517817088 | omm | gsql 140114743260928 | 140114743260928 | omm | WLMArbiter 140114791495424 | 140114791495424 | omm | workload 140114766329600 | 140114766329600 | omm | WorkloadMonitor 140115301627648 | 140115301627648 | omm | CfsShrinker 140115220821760 | 140115220821760 | omm | statement flush thread 140115240285952 | 140115240285952 | omm | Asp 140115336230656 | 140115336230656 | omm | TxnSnapCapturer 140115460486912 | 140115460486912 | omm | JobScheduler 140115380795136 | 140115380795136 | omm | ApplyLauncher 140115266434816 | 140115266434816 | omm | PercentileJob (11 rows) -- 结束当前gsql连接会话,当前会话会断开并重新连接 openGauss=# ALTER SYSTEM KILL SESSION '140114517817088, 140114517817088'; FATAL: terminating connection due to administrator command FATAL: terminating connection due to administrator command The connection to the server was lost. Attempting reset: Succeeded. ``` --- --- url: /en/docs/latest-lite/sql_reference/alter_system_set.md --- # ALTER SYSTEM SET ## Function **ALTER SYSTEM SET** sets GUC parameters of the POSTMASTER, SIGHUP, and BACKEND levels. This command writes parameters into the configuration file. The time to take effect varies according to the level. ## Precautions * This command can be used only by initial users and users with the **sysadmin** permission. * The effective time of GUC parameters at different levels is as follows: * The GUC parameters at the POSTMASTER level take effect only after the system is restarted. * The GUC parameters at the BACKEND level take effect only after the session is reconnected. * The GUC parameters at the SIGHUP level take effect immediately. (Actually, there is a slight delay to wait for the thread reloading the parameter.) * You can set the [**audit\_set\_parameter**](../database_reference/operation_auditing.md#en-us_topic_0283136929_en-us_topic_0237124747_en-us_topic_0059777487_sc59738d0efe94f909306fde1f3d04f1e) parameter to specify whether the operation is audited. * The operation can be synchronized to the standby server. * The operation is the same as **gs\_guc**, which does not pay attention to whether the database is a primary or standby node or whether the database is read-only. * The operation cannot be executed in a transaction because it cannot be rolled back. * The following parameters can be modified only by the initial user: ``` audit_copy_exec, audit_data_format, audit_database_process, audit_directory, audit_dml_state, audit_dml_state_select, audit_enabled, audit_file_remain_threshold, audit_file_remain_time, audit_function_exec, audit_grant_revoke, audit_login_logout, audit_resource_policy, audit_rotation_interval, audit_rotation_size, audit_set_parameter, audit_space_limit, audit_system_object, audit_user_locked, audit_user_violation, asp_log_directory, config_file, data_directory, enable_access_server_directory, enable_copy_server_files, external_pid_file, hba_file, ident_file, log_directory, perf_directory, query_log_directory, ssl_ca_file, ssl_cert_file, ssl_crl_file, ssl_key_file, stats_temp_directory, unix_socket_directory, unix_socket_group, unix_socket_permissions, krb_caseins_users, krb_server_keyfile, krb_srvname, allow_system_table_mods, enableSeparationOfDuty, modify_initial_password, password_encryption_type, password_policy ``` ## Syntax ``` ALTER SYSTEM SET parameter TO value; ``` ## Parameter Description * **parameter** GUC parameter * **value** GUC parameter value ## Examples ``` -- Set the SIGHUP-level parameter audit_enabled. openGauss=# alter system set audit_enabled to off; ALTER SYSTEM SET openGauss=# show audit_enabled; audit_enabled --------------- off (1 row) -- The setting of the POSTMASTER-level parameter enable_thread_pool takes effect after the system is restarted. openGauss=# alter system set enable_thread_pool to on; NOTICE: please restart the database for the POSTMASTER level parameter to take effect. ALTER SYSTEM SET ``` --- --- url: /en/docs/latest/sql_reference/alter_system_set.md --- # ALTER SYSTEM SET ## Function **ALTER SYSTEM SET** sets GUC parameters of the POSTMASTER, SIGHUP, and BACKEND levels. This command writes parameters into the configuration file. The time to take effect varies according to the level. ## Precautions * This command can be used only by initial users and users with the **sysadmin** permission. * The effective time of GUC parameters at different levels is as follows: * The GUC parameters at the POSTMASTER level take effect only after the system is restarted. * The GUC parameters at the BACKEND level take effect only after the session is reconnected. * The GUC parameters at the SIGHUP level take effect immediately. (Actually, there is a slight delay to wait for the thread reloading the parameter.) * You can set the [**audit\_set\_parameter**](../database_reference/operation_auditing.md#en-us_topic_0283136929_en-us_topic_0237124747_en-us_topic_0059777487_sc59738d0efe94f909306fde1f3d04f1e) parameter to specify whether the operation is audited. * The operation can be synchronized to the standby server. * The operation is the same as **gs\_guc**, which does not pay attention to whether the database is a primary or standby node or whether the database is read-only. * The operation cannot be executed in a transaction because it cannot be rolled back. * The following parameters can be modified only by the initial user: ``` audit_copy_exec, audit_data_format, audit_database_process, audit_directory, audit_dml_state, audit_dml_state_select, audit_enabled, audit_file_remain_threshold, audit_file_remain_time, audit_function_exec, audit_grant_revoke, audit_login_logout, audit_resource_policy, audit_rotation_interval, audit_rotation_size, audit_set_parameter, audit_space_limit, audit_system_object, audit_user_locked, audit_user_violation, asp_log_directory, config_file, data_directory, enable_access_server_directory, enable_copy_server_files, external_pid_file, hba_file, ident_file, log_directory, perf_directory, query_log_directory, ssl_ca_file, ssl_cert_file, ssl_crl_file, ssl_key_file, stats_temp_directory, unix_socket_directory, unix_socket_group, unix_socket_permissions, krb_caseins_users, krb_server_keyfile, krb_srvname, allow_system_table_mods, enableSeparationOfDuty, modify_initial_password, password_encryption_type, password_policy ``` ## Syntax ``` ALTER SYSTEM SET parameter TO value; ``` ## Parameter Description * **parameter** GUC parameter * **value** GUC parameter value ## Examples ``` -- Set the SIGHUP-level parameter audit_enabled. openGauss=# alter system set audit_enabled to off; ALTER SYSTEM SET openGauss=# show audit_enabled; audit_enabled --------------- off (1 row) -- The setting of the POSTMASTER-level parameter enable_thread_pool takes effect after the system is restarted. openGauss=# alter system set enable_thread_pool to on; NOTICE: please restart the database for the POSTMASTER level parameter to take effect. ALTER SYSTEM SET ``` --- --- url: /zh/docs/latest-lite/sql_reference/alter_system_set.md --- # ALTER SYSTEM SET ## 功能描述 ALTER SYSTEM SET命令用于设置POSTMASTER、SIGHUP、BACKEND级别的GUC参数。此命令会将参数写入配置文件,不同级别生效方式有所不同。 ## 注意事项 * 此命令仅限初始用户和拥有sysadmin权限的用户才可使用。 * 不同级别GUC参数生效时间如下: * POSTMASTER级别的GUC参数需要重启后才生效。 * BACKEND级别的GUC参数需要会话重新连接后才生效。 * SIGHUP级别的GUC参数立即生效(需要等待线程重新加载参数,实际略微有延迟)。 * 通过配置[audit\_set\_parameter](../database_reference/operation_auditing.md#zh-cn_topic_0283136929_zh-cn_topic_0237124747_zh-cn_topic_0059777487_sc59738d0efe94f909306fde1f3d04f1e)参数,可以配置此操作是否被审计。 * 操作可被备机同步。 * 同gs\_guc一致,并不关注数据库是主或备节点、是否只读。 * 不可在事务中执行,因为此操作无法被回滚。 * 部分参数只能由初始用户修改,具体如下: ``` audit_copy_exec, audit_data_format, audit_database_process, audit_directory, audit_dml_state, audit_dml_state_select, audit_enabled, audit_file_remain_threshold, audit_file_remain_time, audit_function_exec, audit_grant_revoke, audit_login_logout, audit_resource_policy, audit_rotation_interval, audit_rotation_size, audit_set_parameter, audit_space_limit, audit_system_object, audit_user_locked, audit_user_violation, asp_log_directory, config_file, data_directory, enable_access_server_directory, enable_copy_server_files, external_pid_file, hba_file, ident_file, log_directory, perf_directory, query_log_directory, ssl_ca_file, ssl_cert_file, ssl_enc_cert_file,ssl_crl_file, ssl_key_file,ssl_enc_key_file, stats_temp_directory, unix_socket_directory, unix_socket_group, unix_socket_permissions, krb_caseins_users, krb_server_keyfile, krb_srvname, allow_system_table_mods, enableSeparationOfDuty, modify_initial_password, password_encryption_type, password_policy ``` > \[!NOTE]说明 > 在兼容B模式下,ALTER SYSTEM SET命令设置可以设置SUSET, USERSET级别参数,条件如下: > > * 当前用户拥有sysadmin权限。 > > * 当前用户在B兼容数据库中。 > > * 只能设置带有插件属性参数。 > > 注意:本例外只对满足上述三个条件的GUC参数设置时级别做了特殊处理,并不会改变参数原有其他校验逻辑:比如只能由初始用户修改的参数。 ## 语法格式 ``` ALTER SYSTEM SET parameter TO value; ``` ## 参数说明 * **parameter** GUC参数名。 * **value** GUC参数值。 ## 示例 ``` --设置SIGHUP级别参数audit_enabled。 openGauss=# alter system set audit_enabled to off; ALTER SYSTEM SET openGauss=# show audit_enabled; audit_enabled --------------- off (1 row) --设置POSTMASTER级别参数 enable_thread_pool,将在重启之后生效。 openGauss=# alter system set enable_thread_pool to on; NOTICE: please restart the database for the POSTMASTER level parameter to take effect. ALTER SYSTEM SET ``` --- --- url: /zh/docs/latest/sql_reference/alter_system_set.md --- # ALTER SYSTEM SET ## 功能描述 ALTER SYSTEM SET命令用于设置POSTMASTER、SIGHUP、BACKEND级别的GUC参数。此命令会将参数写入配置文件,不同级别生效方式有所不同。 ## 注意事项 * 此命令仅限初始用户和拥有sysadmin权限的用户才可使用。 * 不同级别GUC参数生效时间如下: * POSTMASTER级别的GUC参数需要重启后才生效。 * BACKEND级别的GUC参数需要会话重新连接后才生效。 * SIGHUP级别的GUC参数立即生效(需要等待线程重新加载参数,实际略微有延迟)。 * 通过配置[audit\_set\_parameter](../database_reference/operation_auditing.md#zh-cn_topic_0283136929_zh-cn_topic_0237124747_zh-cn_topic_0059777487_sc59738d0efe94f909306fde1f3d04f1e)参数,可以配置此操作是否被审计。 * 操作可被备机同步(资源池化模式不支持参数同步)。 * 同gs\_guc一致,并不关注数据库是主或备节点、是否只读。 * 不可在事务中执行,因为此操作无法被回滚。 * 部分参数只能由初始用户修改,具体如下: ``` audit_copy_exec, audit_data_format, audit_database_process, audit_directory, audit_dml_state, audit_dml_state_select, audit_enabled, audit_file_remain_threshold, audit_file_remain_time, audit_function_exec, audit_grant_revoke, audit_login_logout, audit_resource_policy, audit_rotation_interval, audit_rotation_size, audit_set_parameter, audit_space_limit, audit_system_object, audit_user_locked, audit_user_violation, asp_log_directory, config_file, data_directory, enable_access_server_directory, enable_copy_server_files, external_pid_file, hba_file, ident_file, log_directory, perf_directory, query_log_directory, ssl_ca_file, ssl_cert_file, ssl_crl_file, ssl_key_file, stats_temp_directory, unix_socket_directory, unix_socket_group, unix_socket_permissions, krb_caseins_users, krb_server_keyfile, krb_srvname, allow_system_table_mods, enableSeparationOfDuty, modify_initial_password, password_encryption_type, password_policy ``` > \[!NOTE]说明 > 在兼容B模式下,ALTER SYSTEM SET命令设置可以设置SUSET, USERSET级别参数,条件如下: > > * 当前用户拥有sysadmin权限。 > > * 当前用户在B兼容数据库中。 > > * 只能设置带有插件属性参数。 > > 注意:本例外只对满足上述三个条件的GUC参数设置时级别做了特殊处理,并不会改变参数原有其他校验逻辑:比如只能由初始用户修改的参数。 ## 语法格式 ``` ALTER SYSTEM SET parameter TO value; ``` ## 参数说明 * **parameter** GUC参数名。 * **value** GUC参数值。 ## 示例 ``` --设置SIGHUP级别参数audit_enabled。 openGauss=# alter system set audit_enabled to off; ALTER SYSTEM SET openGauss=# show audit_enabled; audit_enabled --------------- off (1 row) --设置POSTMASTER级别参数 enable_thread_pool,将在重启之后生效。 openGauss=# alter system set enable_thread_pool to on; NOTICE: please restart the database for the POSTMASTER level parameter to take effect. ALTER SYSTEM SET ``` --- --- url: /en/docs/latest-lite/sql_reference/alter_table.md --- # ALTER TABLE ## Function **ALTER TABLE** modifies tables, including modifying table definitions, renaming tables, renaming specified columns in tables, renaming table constraints, setting table schemas, enabling or disabling row-level security policies, and adding or updating multiple columns. ## Precautions * The owner of a table, users granted with the **ALTER** permission on the table, or users granted with the **ALTER ANY TABLE** permission can run the **ALTER TABLE** statement. The system administrator has the permission to run the command by default. To modify the owner or schema of a table, you must be the table owner or system administrator and a member of the new owner role. * The tablespace of a partitioned table cannot be modified, but the tablespace of the partition can be modified. * The storage parameter **ORIENTATION** cannot be modified. * Currently, **SET SCHEMA** can only set schemas to user schemas. It cannot set a schema to a system internal schema. * Column-store tables support only the **PARTIAL CLUSTER KEY**, **UNIQUE**, and **PRIMARY KEY** table-level constraints, but do not support foreign key table-level constraints. * In a column-store table, you can perform **ADD COLUMN**, **ALTER TYPE**, **SET STATISTICS**, **DROP COLUMN** operations, and change table name and space. The types of new and modified columns should be the [Data Types](numeric_types.md) supported by column-store. The **USING** option of **ALTER TYPE** only supports constant expression and expression involved in the column. * The column constraints supported by column-store tables include **NULL**, **NOT NULL**, **DEFAULT** constant values, **UNIQUE**, and **PRIMARY KEY**. Only the **DEFAULT** value can be modified (by using **SET DEFAULT** and **DROP DEFAULT**). Currently, **NULL** and **NOT NULL** constraints cannot be modified. * Auto-increment columns cannot be added, or a column whose **DEFAULT** value contains the **nextval()** expression cannot be added. * Row-access control cannot be enabled for foreign tables and temporary tables. * When you delete a **PRIMARY KEY** constraint by constraint name, the **NOT NULL** constraint is not deleted. If necessary, manually delete the **NOT NULL** constraint. * When JDBC is used, the **DEFAULT** value can be set through **PrepareStatement**. ## Syntax * Modify the definition of a table. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name ) } action [, ... ]; ``` There are several clauses of **action**: ``` column_clause | ADD table_constraint [ NOT VALID ] | ADD table_constraint_using_index | VALIDATE CONSTRAINT constraint_name | DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ] | CLUSTER ON index_name | SET WITHOUT CLUSTER | SET ( {storage_parameter = value} [, ... ] ) | RESET ( storage_parameter [, ... ] ) | OWNER TO new_owner | SET TABLESPACE new_tablespace | SET {COMPRESS|NOCOMPRESS} | TO { GROUP groupname | NODE ( nodename [, ... ] ) } | ADD NODE ( nodename [, ... ] ) | DELETE NODE ( nodename [, ... ] ) | DISABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE REPLICA TRIGGER trigger_name | ENABLE ALWAYS TRIGGER trigger_name | DISABLE/ENABLE [ REPLICA | ALWAYS ] RULE | DISABLE ROW LEVEL SECURITY | ENABLE ROW LEVEL SECURITY | FORCE ROW LEVEL SECURITY | NO FORCE ROW LEVEL SECURITY | ENCRYPTION KEY ROTATION | SET WITH OIDS | SET WITHOUT OIDS | INHERIT parents | NO INHERIT parents | OF type_name | NOT OF | REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING } | AUTO_INCREMENT [ = ] value | COMMENT {=| } 'text' ``` \[!NOTE]NOTE * **ADD table\_constraint \[ NOT VALID ]** Adds a table constraint. * **ADD table\_constraint\_using\_index** Adds a primary key constraint or unique constraint to a table based on the existing unique index. * **VALIDATE CONSTRAINT constraint\_name** Validates a check-class constraint created with the **NOT VALID** option, and scans the entire table to ensure that all rows meet the constraint. Nothing happens if the constraint is already marked valid. * **DROP CONSTRAINT \[ IF EXISTS ] constraint\_name \[ RESTRICT | CASCADE ]** Deletes a table constraint. * **CLUSTER ON index\_name** Selects the default index for future CLUSTER operations. Actually, the table is not re-clustered. * **SET WITHOUT CLUSTER** Deletes the most recently used **CLUSTER** index from the table. This affects future **CLUSTER** operations that do not specify an index. * **SET ( {storage\_parameter = value} \[, ... ] )** Changes one or more storage parameters for the table. * **RESET ( storage\_parameter \[, ... ] )** Resets one or more storage parameters to their defaults. As with **SET**, a table rewrite might be needed to update the table entirely. * **OWNER TO new\_owner** Changes the owner of a table, sequence, or view to the specified user. * **SET TABLESPACE new\_tablespace** Changes the table's tablespace to the specified tablespace and moves the data files associated with the table to the new tablespace. Indexes on the table, if any, are not moved; but they can be moved separately with additional **SET TABLESPACE** option in **ALTER INDEX**. * **SET {COMPRESS|NOCOMPRESS}** Sets the compression feature of a table. The table compression feature affects only the storage mode of data inserted in a batch subsequently and does not affect storage of existing data. Setting the table compression feature will result in the fact that there are both compressed and uncompressed data in the table. Row-store tables do not support compression. * **TO { GROUP groupname | NODE ( nodename \[, ... ] ) }** The syntax is only available in extended mode (when GUC parameter **support\_extended\_features** is **on**). Exercise caution when enabling the mode. It is mainly used for tools like internal dilatation tools. Common users should not use the mode. * **ADD NODE ( nodename \[, ... ] )** It is only available for internal scale-out tools. Common users should not use the syntax. * **DELETE NODE ( nodename \[, ... ] )** It is only available for internal scale-in tools. Common users should not use the syntax. * **DISABLE TRIGGER \[ trigger\_name | ALL | USER ]** Disables a single trigger specified by **trigger\_name**, disables all triggers, or disables only user triggers (excluding internally generated constraint triggers, for example, deferrable unique constraint triggers and exclusion constraints triggers). Exercise caution when using this function because data integrity cannot be ensured as expected if the triggers are not executed. * **| ENABLE TRIGGER \[ trigger\_name | ALL | USER ]** Enables a single trigger specified by **trigger\_name**, enables all triggers, or enables only user triggers. * **| ENABLE REPLICA TRIGGER trigger\_name** Determines that the trigger firing mechanism is affected by the configuration variable [session\_replication\_role](../database_reference/statement_behavior.md#en-us_topic_0283136752_en-us_topic_0237124732_en-us_topic_0059779117_sffbd1c48d86b4c3fa3287167a7810216). When the replication role is **origin** (default value) or **local**, a simple trigger is fired. When **ENABLE REPLICA** is configured for a trigger, it is fired only when the session is in replica mode. * **| ENABLE ALWAYS TRIGGER trigger\_name** Determines that all triggers are fired regardless of the current replication mode. * **| DISABLE/ENABLE \[ REPLICA | ALWAYS ] RULE** Enables or disables a rule for tables. Disabled rules are still visible in the system, but are not applied during query rewriting. The **ON SELECT** rule cannot be disabled because it is related to the view implementation. Rules configured as **ENABLE REPLICA** are enabled only when the session is in replica mode, while those configured as **ENABLE ALWAYS** can be enabled regardless of the replica mode. Rule triggering is also affected by configuration variables in [session\_replication\_role](../database_reference/statement_behavior.md#en-us_topic_0283136752_en-us_topic_0237124732_en-us_topic_0059779117_sffbd1c48d86b4c3fa3287167a7810216), which is similar to the preceding trigger setting. * **| DISABLE/ENABLE ROW LEVEL SECURITY** Enables or disables row-level access control for a table. If row-level access control is enabled for a data table but no row-level access control policy is defined, the row-level access to the data table is not affected. If row-level access control for a table is disabled, the row-level access to the table is not affected even if a row-level access control policy has been defined. For details, see [CREATE ROW LEVEL SECURITY POLICY](create_row_level_security_policy.md). * **| NO FORCE/FORCE ROW LEVEL SECURITY** Forcibly enables or disables row-level access control for a table. By default, the table owner is not affected by the row-level access control feature. However, if row-level access control is forcibly enabled, the table owner (excluding system administrators) will be affected. System administrators are not affected by any row-level access control policies. * **SET WITH OIDS** Adds an OID system column to a data table. If the OID already exists in the table, the syntax does not change anything. * **SET WITHOUT OIDS** Deletes an OID system column from a data table. If there is no OID in the table, the syntax does not change anything. * **INHERIT parent\_table** Adds the target data table to a specified parent data table as a new child data table. After that, the query for the parent data table will contain the data in the target data table. Before being added as a child data table, the target data table must contain all the columns in the parent data table. These columns must have matching data categories, and if they have NOT NULL constraints in the parent data table, they must also have NOT NULL constraints in the child data table. For all CHECK constraints in the parent data table, there must be corresponding constraints in the child data table, unless the parent data table is marked as non-inheritable. * **NO INHERIT parent\_table** Generates the target data table from the child data table of a specified parent data table. Queries for the parent data table will no longer contain records generated from the target data table. * **OF type\_name** Joins a table to a composite type, which is similar to table creation by using the **CREATE TABLE OF** option. The name and type of a table column must exactly match those defined in the composite type, but the OID system column can be different. The table cannot be inherited from any other table. These restrictions ensure that the **CREATE TABLE OF** option allows the same table definition. * **NOT OF** Removes the association between a table and a type. * **REPLICA IDENTITY { DEFAULT | USING INDEX index\_name | FULL | NOTHING }** Specifies the record level of old tuples in UPDATE and DELETE statements on a table in logical replication scenarios. * **DEFAULT** records the old value of the primary key column. If there is no primary key, **DEFAULT** does not record the old value. * **USING INDEX** records the old values of columns covered by the named indexes. These values must be unique, non-local, and non-deferrable, and contain the values of columns marked **NOT NULL**. * **FULL** records the old values of all columns in the row. * **NOTHING** does not record information in old rows. In logical replication scenarios, when the UPDATE and DELETE statements of a table are parsed, the parsed old tuples consist of the information recorded in this method. For tables with primary keys, this option can be set to **DEFAULT** or **FULL**. For a table without a primary key, set this parameter to **FULL**. Otherwise, the old tuple will be parsed as empty during decoding. You are not advised to set this parameter to **NOTHING** in common scenarios because old tuples are always parsed as empty. Even if **DEFAULT** or **USING INDEX** is specified, the old values of the columns in the current Ustore table may contain the old values of all columns in the row. This configuration option takes effect only when the old values involve TOAST values. For the ustore table, the **NOTHING** option is invalid, and the actual effect is the same as that of **FULL**. * **AUTO\_INCREMENT \[ = ] value** Sets the next auto-increment value of the auto-increment column. The configured value takes effect only when it is greater than the current auto-increment counter. The value must be a non-negative integer and cannot be greater than 2127-1. This clause takes effect only when **sql\_compatibility** is set to **B**. * **COMMENT 'text'** Comments a table object. * There are several clauses of **column\_clause**: ``` ADD [ COLUMN ] column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] [ COMMENT {=| } 'text' ] | MODIFY column_name data_type | MODIFY [ COLUMN ] column_name [ COMMENT 'text'] | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL | DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ] | ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ] | ALTER [ COLUMN ] column_name { SET DEFAULT expression | DROP DEFAULT } | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS [PERCENT] integer | ADD STATISTICS (( column_1_name, column_2_name [, ...] )) | DELETE STATISTICS (( column_1_name, column_2_name [, ...] )) | ALTER [ COLUMN ] column_name SET ( {attribute_option = value} [, ... ] ) | ALTER [ COLUMN ] column_name RESET ( attribute_option [, ... ] ) | ALTER [ COLUMN ] column_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN } ``` \[!NOTE]NOTE * **ADD \[ COLUMN ] column\_name data\_type \[ compress\_mode ] \[ COLLATE collation ] \[ column\_constraint \[ ... ] ] \[ COMMENT {=| } 'text']** Adds a column to a table. If a column is added with **ADD COLUMN**, all existing rows in the table are initialized with the column's default value (**NULL** if no **DEFAULT** clause is specified). * **ADD ( { column\_name data\_type \[ compress\_mode ] } \[, ...] )** Adds columns in the table. * **MODIFY \[ COLUMN ] column\_name \[ COMMENT {=| } 'text']** Comments a column. * **MODIFY ( { column\_name data\_type | column\_name \[ CONSTRAINT constraint\_name ] NOT NULL \[ ENABLE ] | column\_name \[ CONSTRAINT constraint\_name ] NULL } \[, ...] )** Modifies the data type of an existing column in the table. * **DROP \[ COLUMN ] \[ IF EXISTS ] column\_name \[ RESTRICT | CASCADE ]** Drops a column from a table. Indexes and constraints related to the column are automatically dropped. If an object not belonging to the table depends on the column, **CASCADE** must be specified, such as a view. The **DROP COLUMN** statement does not physically remove the column, but simply makes it invisible to SQL operations. Subsequent **INSERT** and **UPDATE** operations in the table will store a **NULL** value for the column. Therefore, column deletion takes a short period of time but does not immediately release the tablespace on the disks, because the space occupied by the deleted column is not recycled. The space will be recycled when **VACUUM** is executed. * **ALTER \[ COLUMN ] column\_name \[ SET DATA ] TYPE data\_type \[ COLLATE collation ] \[ USING expression ]** Modifies the type of a column in a table. Indexes and simple table constraints on the column will automatically use the new data type by reparsing the originally supplied expression. **ALTER TYPE** requires an entire table be rewritten. This is an advantage sometimes, because it frees up unnecessary space from a table. For example, to recycle the space occupied by a deleted column, the fastest method is to use the following statement. ``` ALTER TABLE table ALTER COLUMN anycol TYPE anytype; ``` In this statement, **anycol** indicates any column existing in the table and **anytype** indicates the type of the prototype of the column. **ALTER TYPE** does not change the table except that the table is forcibly rewritten. In this way, the data that is no longer used is deleted. * **ALTER \[ COLUMN ] column\_name { SET DEFAULT expression | DROP DEFAULT }** Sets or removes the default value for a column. The default values only apply to subsequent **INSERT** operations; they do not cause rows already in the table to change. Defaults can also be created for views, in which case they are inserted into **INSERT** statements on the view before the view's **ON INSERT** rule is applied. * **ALTER \[ COLUMN ] column\_name { SET | DROP } NOT NULL** Changes whether a column is marked to allow null values or to reject null values. You can only use **SET NOT NULL** when the column contains no null values. * **ALTER \[ COLUMN ] column\_name SET STATISTICS \[PERCENT] integer** Specifies the per-column statistics-gathering target for subsequent **ANALYZE** operations. The target can be set in the range from 0 to 10000. Set it to **–1** to revert to using the default system statistics target. * **{ADD | DELETE} STATISTICS ((column\_1\_name, column\_2\_name \[, ...]))** Adds or deletes the declaration of collecting multi-column statistics to collect multi-column statistics as needed when **ANALYZE** is performed for a table or a database. If the GUC parameter **enable\_functional\_dependency** is disabled, the statistics about a maximum of 32 columns can be collected at a time. If the GUC parameter **enable\_functional\_dependency** is enabled, the statistics about a maximum of 4 columns can be collected at a time. You are not allowed to add or delete such declaration for system catalogs or foreign tables. * **ALTER \[ COLUMN ] column\_name SET ( {attribute\_option = value} \[, ... ] )** **ALTER \[ COLUMN ] column\_name RESET ( attribute\_option \[, ... ] )** Sets or resets per-attribute options. Currently, the only defined per-attribute options are **n\_distinct** and **n\_distinct\_inherited**. **n\_distinct** affects statistics of a table, while **n\_distinct\_inherited** affects the statistics of the table and its subtables. Currently, only **SET/RESET n\_distinct** is supported, and **SET/RESET n\_distinct\_inherited** is forbidden. * **ALTER \[ COLUMN ] column\_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }** Sets the storage mode for a column. This clause specifies whether this column is held inline or in a secondary TOAST table, and whether the data should be compressed. It is set only for row-store tables and is invalid for column-store tables. If it is set for column-store tables, an error will be displayed when the statement is executed. **SET STORAGE** itself does not change anything in the table. It sets the strategy to be pursued during future table updates. * **column\_constraint** is as follows: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ idx_name ] [ USING method ] ( { { column_name | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] }[, ... ] ) index_parameters | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | FOREIGN KEY [ idx_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * **compress\_mode** of a column is as follows: ``` [ DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS ] ``` * **table\_constraint\_using\_index** used to add the primary key constraint or unique constraint based on the unique index is as follows: ``` [ CONSTRAINT constraint_name ] { UNIQUE | PRIMARY KEY } USING INDEX index_name [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT 'text' ] ``` * **table\_constraint** is as follows: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ idx_name ][ USING method ] ( { { column_name | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | PARTIAL CLUSTER KEY ( column_name [, ... ] } FOREIGN KEY [ idx_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` **index\_parameters** is as follows: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * Rename a table. The renaming does not affect stored data. ``` ALTER TABLE [ IF EXISTS ] table_name RENAME TO new_table_name; ``` * Rename the specified column in the table. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME [ COLUMN ] column_name TO new_column_name; ``` * Rename the constraint of the table. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name ) } RENAME CONSTRAINT constraint_name TO new_constraint_name; ``` * Set the schema of the table. ``` ALTER TABLE [ IF EXISTS ] table_name SET SCHEMA new_schema; ``` > \[!NOTE]NOTE > > * The schema setting moves the table into another schema. Associated indexes and constraints owned by table columns are migrated as well. Currently, the schema for sequences cannot be changed. If the table has sequences, delete the sequences, and create them again or delete the ownership between the table and sequences. In this way, the table schema can be changed. > * To change the schema of a table, you must also have the **CREATE** permission on the new schema. To add the table as a new child of a parent table, you must own the parent table as well. To alter the owner, you must also be a direct or indirect member of the new owning role, and that role must have the **CREATE** permission on the table's schema. These restrictions enforce that the user can only recreate and delete the table. However, a system administrator can alter the ownership of any table anyway. > * All the actions except for **RENAME** and **SET SCHEMA** can be combined into a list of multiple alterations to apply in parallel. For example, it is possible to add several columns or alter the type of several columns in a single statement. This is useful with large tables, since only one pass over the tables need be made. > * Adding a **CHECK** or **NOT NULL** constraint will scan the table to validate that existing rows meet the constraint. > * Adding a column with a non-**NULL** default or changing the type of an existing column will rewrite the entire table. Rewriting a large table may take much time and temporarily needs doubled disk space. * Add columns. ``` ALTER TABLE [ IF EXISTS ] table_name ADD ( { column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ]} [, ...] ); ``` * Update columns. ``` ALTER TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ``` ## Parameter Description * **IF EXISTS** Sends a notice instead of an error if no tables have identical names. The notice prompts that the table you are querying does not exist. * **table\_name \[\*] | ONLY table\_name | ONLY ( table\_name )** **table\_name** is the name of the table that you need to modify. If **ONLY** is specified, only the table is modified. If **ONLY** is not specified, the table and all subtables are modified. You can add the asterisk (\*) option following the table name to specify that all subtables are scanned, which is the default operation. * **constraint\_name** * Specifies the name of an existing constraint to drop in the DROP CONSTRAINT operation. * Specifies the name of a new constraint in the ADD CONSTRAINT operation. > \[!TIP]NOTICE > For a new constraint, constraint\_name is optional in B-compatible mode (**sql\_compatibility = 'B'**). For other modes, constraint\_name must be added. * **index\_name** Specifies the name of an index. > \[!TIP]NOTICE > In the ADD CONSTRAINT operation: > > * index\_name is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * For foreign key constraints, if constraint\_name and index\_name are specified at the same time, constraint\_name is used as the index name. > * For a unique key constraint, if both constraint\_name and index\_name are specified, index\_name is used as the index name. * **USING method** Specifies the name of the index method to be used. For details about the value range, see [USING method](create_index.md). > \[!TIP]NOTICE > In the ADD CONSTRAINT operation: > > * The USING method is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * In B-compatible mode, if USING method is not specified, the default index method is btree for ASTORE or ubtree for USTORE. * **ASC | DESC** **ASC** specifies an ascending (default) sort order. **DESC** specifies a descending sort order. > \[!TIP]NOTICE > In ADD CONSTRAINT, ASC|DESC is supported only in B-compatible databases (sql\_compatibility = 'B'). * **expression** Specifies an expression index constraint created based on one or more columns of the table. The expression index must be written with surrounding parentheses. > \[!TIP]NOTICE > Expression indexes are supported only in B-compatible databases (that is, sql\_compatibility = 'B'). * **storage\_parameter** Specifies the name of a storage parameter. The following option is added for creating an index: * parallel\_workers (int type) Value range: \[0,32]. The value **0** indicates that concurrency is disabled. Number of bgworker threads started when an index is created. For example, **2** indicates that two bgworker threads are started to create indexes concurrently. If this parameter is not set, the number of started bgworker threads is related to the table size. Generally, the number of started bgworker threads does not exceed four. * hasuids (Boolean type) Default value: **off** If this parameter is set to **on**, a unique table-level ID is allocated to a tuple when the tuple is updated. * **new\_owner** Specifies the name of the new table owner. * **new\_tablespace** Specifies the new name of the tablespace to which the table belongs. * column\_name, column\_1\_name, column\_2\_name Specifies the name of a new or existing column. * **data\_type** Specifies the type of a new column or a new type of an existing column. * **compress\_mode** Compression option of a table field. The clause specifies the compression algorithm preferentially used by the column. Row-store tables do not support compression. * **collation** Specifies the collation rule name of a column. The optional **COLLATE** clause specifies a collation for the new column; if omitted, the collation is the default for the new column. You can run the **select \* from pg\_collation;** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **USING expression** Specifies how to compute the new column value from the old; if omitted, the default conversion is an assignment cast from old data type to new. A **USING** clause must be provided if there is no implicit or assignment cast from the old to new type. > \[!NOTE]NOTE > **USING** in **ALTER TYPE** can specify any expression involving the old values of the row; that is, it can refer to any columns other than the one being cast. This allows general casting to be done with the **ALTER TYPE** syntax. Because of this flexibility, the **USING** expression is not applied to the column's default value (if any); the result might not be a constant expression as required for a default. This means that when there is no implicit or assignment cast from old to new type, **ALTER TYPE** might fail to convert the default even though a **USING** clause is supplied. In such cases, drop the default with **DROP DEFAULT**, perform the **ALTER TYPE**, and then use **SET DEFAULT** to add a suitable new default. Similar considerations apply to indexes and constraints involving the column. * **NOT NULL | NULL** Sets whether the column allows null values. * **integer** Specifies the constant value of a signed integer. When using **PERCENT**, the range of **integer** is from 0 to 100. * **attribute\_option** Specifies an attribute option. * **PLAIN | EXTERNAL | EXTENDED | MAIN** Specifies a column-store mode. * **PLAIN** must be used for fixed-length values (such as integers). It must be inline and uncompressed. * **MAIN** is for inline, compressible data. * **EXTERNAL** is for external, uncompressed data. Use of **EXTERNAL** will make substring operations on **text** and **bytea** values run faster, at the penalty of increased storage space. * **EXTENDED** is for external, compressed data. **EXTENDED** is the default for most data types that support non-**PLAIN** storage. * **CHECK ( expression )** New rows or rows to be updated must satisfy for an expression to be true. If any row produces a false result, an error is raised and the database is not modified. A check constraint specified as a column constraint should reference only the column's values, while an expression in a table constraint can reference multiple columns. Currently, **CHECK ( expression )** does not include subqueries and cannot use variables apart from the current column. * **DEFAULT default\_expr** Assigns a default data value for a column. The data type of the default expression must match the data type of the column. The default expression will be used in any insert operation that does not specify a value for the column. If there is no default value for a column, then the default value is null. * **AUTO\_INCREMENT** Specifies an auto-increment column. For details, see [AUTO\_INCREMENT](create_table.md). * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** Specifies that a group of one or more columns of a table can contain only unique values. * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** Specifies that a column or columns of a table can contain only unique (non-duplicate) and non-null values. * **REFERENCES reftable \[ ( refcolum ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (column constraint)** **FOREIGN KEY ( column\_name \[, ... ] ) REFERENCES reftable \[ ( refcolumn \[, ... ] ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (table constraint)** The foreign key constraint requires that the group consisting of one or more columns in the new table should contain and match only the referenced column values in the referenced table. If **refcolum** is omitted, the primary key of **reftable** is used. The referenced column should be the only column or primary key in the referenced table. A foreign key constraint cannot be defined between a temporary table and a permanent table. There are three types of matching between a reference column and a referenced column: * **MATCH FULL**: A column with multiple foreign keys cannot be **NULL** unless all foreign key columns are **NULL**. * **MATCH SIMPLE** (default): Any unexpected foreign key column can be **NULL**. * **MATCH PARTIAL**: This option is not supported currently. In addition, when you perform certain operations on the data in the referenced table, the operations are performed on the corresponding columns in the new table. **ON DELETE**: specifies the operations to be executed after a referenced row in the referenced table is deleted. **ON UPDATE**: specifies the operation to be performed when the referenced column data in the referenced table is updated. The possible actions of the **ON DELETE** and **ON UPDATE** clauses are as follows: * **NO ACTION** (default): When a foreign key is deleted or updated, an error indicating that the foreign key constraint is violated is created. If the constraint is deferrable and there are still any referenced rows, this error will occur when the constraint is checked. * **RESTRICT**: When a foreign key is deleted or updated, an error indicating that the foreign key constraint is violated is created. It is the same as **NO ACTION** except that the action cannot be delayed. * **CASCADE**: deletes any row that references the deleted row from the new table, or update the field value of the referenced row in the new table to the new value of the referenced column. * **SET NULL**: sets the referenced field to **NULL**. * **SET DEFAULT**: sets referenced fields to their default values. * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(default): Enable constraints, create indexes, and enforce constraints on both existing data and newly added data. * ENABLE NOVALIDATE: Enable constraints and create indexes. For CHECK constraints, the constraints are only enforced for newly added data, regardless of the existing data in the table. For UNIQUE and PRIMARY KEY, indexes need to be established, so the constraints will be enforced for the existing data. * DISABLE( NOVALIDATE)(default): Disable constraints, delete indexes, and operations such as modifying the data of the constraint columns can be performed. * DISABLE VALIDATE: Disable constraints and delete indexes. Insertion, update and deletion operations on the table cannot be performed. * **DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE** Sets whether the constraint can be deferrable. * **DEFERRABLE**: deferrable to the end of the transaction and checked using **SET CONSTRAINTS**. * **NOT DEFERRABLE**: checks immediately after the execution of each command. * **INITIALLY IMMEDIATE**: checks immediately after the execution of each statement. * **INITIALLY DEFERRED**: checks when the transaction ends. > \[!NOTE]NOTE > Ustore tables do not support the **DEFERRABLE** and **INITIALLY DEFERRED** constraints. * **PARTIAL CLUSTER KEY** Specifies a partial cluster key for storage. When importing data to a column-store table, you can perform local data sorting by specified columns (single or multiple). * **WITH ( {storage\_parameter = value} \[, ... ] )** Specifies an optional storage parameter for a table or an index. * **tablespace\_name** Specifies the name of the tablespace where the index locates. * **COMPRESS|NOCOMPRESS** * **NOCOMPRESS**: If the **NOCOMPRESS** keyword is specified, the existing compression feature of the table will not be changed. * **COMPRESS**: If the **COMPRESS** keyword is specified, the table compression feature will be triggered by batch tuple insertion. Row-store tables do not support compression. * **new\_table\_name** Specifies the new table name. * **new\_column\_name** Specifies the new name of a specific column in a table. * **new\_constraint\_name** Specifies the new name of a table constraint. * **new\_schema** Specifies the new schema name. * **CASCADE** Automatically drops objects that depend on the dropped column or constraint (for example, views referencing the column). * **RESTRICT** Refuses to drop the column or constraint if there are any dependent objects. This is the default processing. * **schema\_name** Specifies the schema name of a table. ## Examples See [Examples](create_table.md#en-us_topic_0283137629_en-us_topic_0237122117_en-us_topic_0059778169_s86758dcf05d442d2a9ebd272e76ed1b8) in **CREATE TABLE**. ## Helpful Links [CREATE TABLE](create_table.md) and [DROP TABLE](drop_table.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-alter-table.md --- # ALTER TABLE ## Function Modifies tables, including modifying table definitions, renaming tables, renaming specified columns in tables, renaming table constraints, setting table schemas, enabling or disabling row-level security policies, and adding or updating multiple columns. ## Precautions * This section describes only the new syntax of Dolphin. The original syntax of openGauss is not deleted or modified. * If a statement contains multiple subcommands, the DROP INDEX and RENAME INDEX commands are executed first. The two commands have the same priority. ## Syntax * **ALTER TABLE** modifies the definition of a table. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name ) } action [, ... ]; ``` The **action** can be one of the following clauses: ``` column_clause | {DISABLE | ENABLE} KEYS | DROP INDEX index_name [ RESTRICT | CASCADE ] | DROP PRIMARY KEY [ RESTRICT | CASCADE ] | DROP FOREIGN KEY foreign_key_name [ RESTRICT | CASCADE ] | RENAME INDEX index_name to new_index_name | ADD table_indexclause | MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP ``` * Recreate a table. ``` ALTER TABLE table_name FORCE; ``` * Rename a table. The renaming does not affect stored data. ``` ALTER TABLE [ IF EXISTS ] table_name RENAME { TO | AS } new_table_name; ``` * Add the ON UPDATE attribute to the timestamp column of the table. ```sql ALTER TABLE table_name MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP; ``` * Delete the ON UPDATE attribute from the timestamp column of the table. ```sql ALTER TABLE table_name MODIFY column_name column_type; ``` * **ADD table\_indexclause** Add an index to the table. ``` {INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option]... ``` Values of index\_type are as follows: ``` USING {BTREE | HASH | GIN | GIST | PSORT | UBTREE} ``` Values of key\_part are as follows: ``` {col_name[(length)] | (expr)} [ASC | DESC] ``` The index\_option parameter is as follows: ``` index_option:{ COMMENT 'string' | index_type } ``` The sequence and quantity of COMMENT and index\_type can be random, but only the last value of the same column takes effect. ## Parameter Description * **{DISABLE | ENABLE} KEYS** Disables or enables all non-unique indexes of a table. * **DROP INDEX index\_name \[ RESTRICT | CASCADE ]** Deletes the index of a table. * **DROP PRIMARY KEY \[ RESTRICT | CASCADE ]** Deletes the primary key of a table. * **DROP FOREIGN KEY foreign\_key\_name \[ RESTRICT | CASCADE ]** Deletes the foreign key of a table. * **RENAME INDEX index\_name to new\_index\_name** Renames an index of a table. > \[!NOTE]NOTE > > For details about the involved parameters, see [ALTER TABLE](https://docs.opengauss.org/en/docs/latest/sql_reference/alter_table.html). ## Examples \--- Create tables, foreign keys, and non-unique indexes. ``` openGauss=# CREATE TABLE alter_table_tbl1 (a INT PRIMARY KEY, b INT); openGauss=# CREATE TABLE alter_table_tbl2 (c INT PRIMARY KEY, d INT); openGauss=# ALTER TABLE alter_table_tbl2 ADD CONSTRAINT alter_table_tbl_fk FOREIGN KEY (d) REFERENCES alter_table_tbl1 (a); openGauss=# CREATE INDEX alter_table_tbl_b_ind ON alter_table_tbl1(b); ``` \--- Disable and enable non-unique indexes. ``` openGauss=# ALTER TABLE alter_table_tbl1 DISABLE KEYS; openGauss=# ALTER TABLE alter_table_tbl1 ENABLE KEYS; ``` \--- Delete the index. ``` openGauss=# ALTER TABLE alter_table_tbl1 DROP KEY alter_table_tbl_b_ind; ``` \--- Deletes a primary key. ``` openGauss=# ALTER TABLE alter_table_tbl2 DROP PRIMARY KEY; ``` \--- Delete a foreign key. ``` openGauss=# ALTER TABLE alter_table_tbl2 DROP FOREIGN KEY alter_table_tbl_fk; ``` \--- Recreate a table. ``` openGauss=# ALTER TABLE alter_table_tbl1 FORCE; ``` \--- Rename the index. ``` openGauss=# CREATE INDEX alter_table_tbl_b_ind ON alter_table_tbl1(b); openGauss=# ALTER TABLE alter_table_tbl1 RENAME INDEX alter_table_tbl_b_ind TO new_alter_table_tbl_b_ind; ``` \--- Delete a table. ``` openGauss=# DROP TABLE alter_table_tbl1, alter_table_tbl2; ``` ## Helpful Links [ALTER TABLE](https://docs.opengauss.org/en/docs/latest/sql_reference/alter_table.html) --- --- url: /en/docs/latest/sql_reference/alter_table.md --- # ALTER TABLE ## Function **ALTER TABLE** modifies tables, including modifying table definitions, renaming tables, renaming specified columns in tables, renaming table constraints, setting table schemas, enabling or disabling row-level security policies, and adding or updating multiple columns. ## Precautions * The owner of a table, users granted with the **ALTER** permission on the table, or users granted with the **ALTER ANY TABLE** permission can run the **ALTER TABLE** statement. The system administrator has the permission to run the command by default. To modify the owner or schema of a table, you must be the table owner or system administrator and a member of the new owner role. * The tablespace of a partitioned table cannot be modified, but the tablespace of the partition can be modified. * The storage parameter **ORIENTATION** cannot be modified. * Currently, **SET SCHEMA** can only set schemas to user schemas. It cannot set a schema to a system internal schema. * Column-store tables support only the **PARTIAL CLUSTER KEY**, **UNIQUE**, and **PRIMARY KEY** table-level constraints, but do not support foreign key table-level constraints. * In a column-store table, you can perform **ADD COLUMN**, **ALTER TYPE**, **SET STATISTICS**, **DROP COLUMN** operations, and change table name and space. The types of new and modified columns should be the [Data Types](numeric_types.md) supported by column-store. The **USING** option of **ALTER TYPE** only supports constant expression and expression involved in the column. * The column constraints supported by column-store tables include **NULL**, **NOT NULL**, **DEFAULT** constant values, **UNIQUE**, and **PRIMARY KEY**. Only the **DEFAULT** value can be modified (by using **SET DEFAULT** and **DROP DEFAULT**). Currently, **NULL** and **NOT NULL** constraints cannot be modified. * Auto-increment columns cannot be added, or a column whose **DEFAULT** value contains the **nextval()** expression cannot be added. * Row-access control cannot be enabled for foreign tables and temporary tables. * When you delete a **PRIMARY KEY** constraint by constraint name, the **NOT NULL** constraint is not deleted. If necessary, manually delete the **NOT NULL** constraint. * When JDBC is used, the **DEFAULT** value can be set through **PrepareStatement**. ## Syntax * Modify the definition of a table. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name ) } action [, ... ]; ``` There are several clauses of **action**: ``` column_clause | ADD table_constraint [ NOT VALID ] | ADD table_constraint_using_index | VALIDATE CONSTRAINT constraint_name | DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ] | CLUSTER ON index_name | SET WITHOUT CLUSTER | SET ( {storage_parameter = value} [, ... ] ) | RESET ( storage_parameter [, ... ] ) | OWNER TO new_owner | SET TABLESPACE new_tablespace | SET {COMPRESS|NOCOMPRESS} | TO { GROUP groupname | NODE ( nodename [, ... ] ) } | ADD NODE ( nodename [, ... ] ) | DELETE NODE ( nodename [, ... ] ) | DISABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE REPLICA TRIGGER trigger_name | ENABLE ALWAYS TRIGGER trigger_name | DISABLE/ENABLE [ REPLICA | ALWAYS ] RULE | DISABLE ROW LEVEL SECURITY | ENABLE ROW LEVEL SECURITY | FORCE ROW LEVEL SECURITY | NO FORCE ROW LEVEL SECURITY | ENCRYPTION KEY ROTATION | SET WITH OIDS | SET WITHOUT OIDS | INHERIT parents | NO INHERIT parents | OF type_name | NOT OF | REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING } | AUTO_INCREMENT [ = ] value | COMMENT {=| } 'text' ``` ## Parameter Description * **ADD table\_constraint \[ NOT VALID ]** Adds a table constraint. * **ADD table\_constraint\_using\_index** Adds a primary key constraint or unique constraint to a table based on the existing unique index. * **VALIDATE CONSTRAINT constraint\_name** Validates a check-class constraint created with the **NOT VALID** option, and scans the entire table to ensure that all rows meet the constraint. Nothing happens if the constraint is already marked valid. * **DROP CONSTRAINT \[ IF EXISTS ] constraint\_name \[ RESTRICT | CASCADE ]** Deletes a table constraint. * **CLUSTER ON index\_name** Selects the default index for future CLUSTER operations. Actually, the table is not re-clustered. * **SET WITHOUT CLUSTER** Deletes the most recently used **CLUSTER** index from the table. This affects future **CLUSTER** operations that do not specify an index. * **SET ( {storage\_parameter = value} \[, ... ] )** Changes one or more storage parameters for the table. * **RESET ( storage\_parameter \[, ... ] )** Resets one or more storage parameters to their defaults. As with **SET**, a table rewrite might be needed to update the table entirely. * **OWNER TO new\_owner** Changes the owner of a table, sequence, or view to the specified user. * **SET TABLESPACE new\_tablespace** Changes the table's tablespace to the specified tablespace and moves the data files associated with the table to the new tablespace. Indexes on the table, if any, are not moved; but they can be moved separately with additional **SET TABLESPACE** option in **ALTER INDEX**. * **SET {COMPRESS|NOCOMPRESS}** Sets the compression feature of a table. The table compression feature affects only the storage mode of data inserted in a batch subsequently and does not affect storage of existing data. Setting the table compression feature will result in the fact that there are both compressed and uncompressed data in the table. Row-store tables do not support compression. * **TO { GROUP groupname | NODE ( nodename \[, ... ] ) }** The syntax is only available in extended mode (when GUC parameter **support\_extended\_features** is **on**). Exercise caution when enabling the mode. It is mainly used for tools like internal dilatation tools. Common users should not use the mode. * **ADD NODE ( nodename \[, ... ] )** It is only available for internal scale-out tools. Common users should not use the syntax. * **DELETE NODE ( nodename \[, ... ] )** It is only available for internal scale-in tools. Common users should not use the syntax. * **DISABLE TRIGGER \[ trigger\_name | ALL | USER ]** Disables a single trigger specified by **trigger\_name**, disables all triggers, or disables only user triggers (excluding internally generated constraint triggers, for example, deferrable unique constraint triggers and exclusion constraints triggers). Exercise caution when using this function because data integrity cannot be ensured as expected if the triggers are not executed. * **| ENABLE TRIGGER \[ trigger\_name | ALL | USER ]** Enables a single trigger specified by **trigger\_name**, enables all triggers, or enables only user triggers. * **| ENABLE REPLICA TRIGGER trigger\_name** Determines that the trigger firing mechanism is affected by the configuration variable [session\_replication\_role](../database_reference/statement_behavior.md#en-us_topic_0283136752_en-us_topic_0237124732_en-us_topic_0059779117_sffbd1c48d86b4c3fa3287167a7810216). When the replication role is **origin** (default value) or **local**, a simple trigger is fired. When **ENABLE REPLICA** is configured for a trigger, it is fired only when the session is in replica mode. * **| ENABLE ALWAYS TRIGGER trigger\_name** Determines that all triggers are fired regardless of the current replication mode. * **| DISABLE/ENABLE \[ REPLICA | ALWAYS ] RULE** Enables or disables a rule for tables. Disabled rules are still visible in the system, but are not applied during query rewriting. The **ON SELECT** rule cannot be disabled because it is related to the view implementation. Rules configured as **ENABLE REPLICA** are enabled only when the session is in replica mode, while those configured as **ENABLE ALWAYS** can be enabled regardless of the replica mode. Rule triggering is also affected by configuration variables in [session\_replication\_role](../database_reference/statement_behavior.md#en-us_topic_0283136752_en-us_topic_0237124732_en-us_topic_0059779117_sffbd1c48d86b4c3fa3287167a7810216), which is similar to the preceding trigger setting. * **| DISABLE/ENABLE ROW LEVEL SECURITY** Enables or disables row-level access control for a table. If row-level access control is enabled for a data table but no row-level access control policy is defined, the row-level access to the data table is not affected. If row-level access control for a table is disabled, the row-level access to the table is not affected even if a row-level access control policy has been defined. For details, see [CREATE ROW LEVEL SECURITY POLICY](create_row_level_security_policy.md). * **| NO FORCE/FORCE ROW LEVEL SECURITY** Forcibly enables or disables row-level access control for a table. By default, the table owner is not affected by the row-level access control feature. However, if row-level access control is forcibly enabled, the table owner (excluding system administrators) will be affected. System administrators are not affected by any row-level access control policies. * **SET WITH OIDS** Adds an OID system column to a data table. If the OID already exists in the table, the syntax does not change anything. * **SET WITHOUT OIDS** Deletes an OID system column from a data table. If there is no OID in the table, the syntax does not change anything. * **INHERIT parent\_table** Adds the target data table to a specified parent data table as a new child data table. After that, the query for the parent data table will contain the data in the target data table. Before being added as a child data table, the target data table must contain all the columns in the parent data table. These columns must have matching data categories, and if they have NOT NULL constraints in the parent data table, they must also have NOT NULL constraints in the child data table. For all CHECK constraints in the parent data table, there must be corresponding constraints in the child data table, unless the parent data table is marked as non-inheritable. * **NO INHERIT parent\_table** Generates the target data table from the child data table of a specified parent data table. Queries for the parent data table will no longer contain records generated from the target data table. * **OF type\_name** Joins a table to a composite type, which is similar to table creation by using the **CREATE TABLE OF** option. The name and type of a table column must exactly match those defined in the composite type, but the OID system column can be different. The table cannot be inherited from any other table. These restrictions ensure that the **CREATE TABLE OF** option allows the same table definition. * **NOT OF** Removes the association between a table and a type. * **REPLICA IDENTITY { DEFAULT | USING INDEX index\_name | FULL | NOTHING }** Specifies the record level of old tuples in UPDATE and DELETE statements on a table in logical replication scenarios. * **DEFAULT** records the old value of the primary key column. If there is no primary key, **DEFAULT** does not record the old value. * **USING INDEX** records the old values of columns covered by the named indexes. These values must be unique, non-local, and non-deferrable, and contain the values of columns marked **NOT NULL**. * **FULL** records the old values of all columns in the row. * **NOTHING** does not record information in old rows. In logical replication scenarios, when the UPDATE and DELETE statements of a table are parsed, the parsed old tuples consist of the information recorded in this method. For tables with primary keys, this option can be set to **DEFAULT** or **FULL**. For a table without a primary key, set this parameter to **FULL**. Otherwise, the old tuple will be parsed as empty during decoding. You are not advised to set this parameter to **NOTHING** in common scenarios because old tuples are always parsed as empty. Even if **DEFAULT** or **USING INDEX** is specified, the old values of the columns in the current Ustore table may contain the old values of all columns in the row. This configuration option takes effect only when the old values involve TOAST values. For the ustore table, the **NOTHING** option is invalid, and the actual effect is the same as that of **FULL**. * **COMMENT {=| } 'text'** Comments a table object. * There are several clauses of **column\_clause**: ``` ADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | MODIFY column_name data_type [ ON UPDATE update_expr ] | MODIFY [ COLUMN ] column_name [ COMMENT 'text'] | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL | DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ] | ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ] | ALTER [ COLUMN ] column_name { SET DEFAULT expression | DROP DEFAULT } | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS [PERCENT] integer | ADD STATISTICS (( column_1_name, column_2_name [, ...] )) | DELETE STATISTICS (( column_1_name, column_2_name [, ...] )) | ALTER [ COLUMN ] column_name SET ( {attribute_option = value} [, ... ] ) | ALTER [ COLUMN ] column_name RESET ( attribute_option [, ... ] ) | ALTER [ COLUMN ] column_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN } ``` ## Parameter Description * **ADD \[ COLUMN ] \[ IF NOT EXISTS ] column\_name data\_type \[ compress\_mode ] \[ COLLATE collation ] \[ column\_constraint \[ ... ] ] \[ COMMENT {=| } 'text']** Adds a column to a table. If a column is added with **ADD COLUMN**, all existing rows in the table are initialized with the column's default value (**NULL** if no **DEFAULT** clause is specified).If **IF NOT EXISTS** is specified and a column already exists with this name, no error is thrown. * **ADD ( { \[ IF NOT EXISTS ] column\_name data\_type \[ compress\_mode ] \[ COMMENT {=| } 'text'] } \[, ...] )** Adds columns in the table. * **MODIFY \[ COLUMN ] column\_name \[ COMMENT {=| } 'text']** Comments a column. * **MODIFY ( { column\_name data\_type | column\_name \[ CONSTRAINT constraint\_name ] NOT NULL \[ ENABLE ] | column\_name \[ CONSTRAINT constraint\_name ] NULL } \[, ...] )** Modifies the data type of an existing column in the table. * **DROP \[ COLUMN ] \[ IF EXISTS ] column\_name \[ RESTRICT | CASCADE ]** Drops a column from a table. Indexes and constraints related to the column are automatically dropped. If an object not belonging to the table depends on the column, **CASCADE** must be specified, such as a view. The **DROP COLUMN** statement does not physically remove the column, but simply makes it invisible to SQL operations. Subsequent **INSERT** and **UPDATE** operations in the table will store a **NULL** value for the column. Therefore, column deletion takes a short period of time but does not immediately release the tablespace on the disks, because the space occupied by the deleted column is not recycled. The space will be recycled when **VACUUM** is executed. * **ALTER \[ COLUMN ] column\_name \[ SET DATA ] TYPE data\_type \[ COLLATE collation ] \[ USING expression ]** Modifies the type of a column in a table. Indexes and simple table constraints on the column will automatically use the new data type by reparsing the originally supplied expression. **ALTER TYPE** requires an entire table be rewritten. This is an advantage sometimes, because it frees up unnecessary space from a table. For example, to recycle the space occupied by a deleted column, the fastest method is to use the following statement. ``` ALTER TABLE table ALTER COLUMN anycol TYPE anytype; ``` In this statement, **anycol** indicates any column existing in the table and **anytype** indicates the type of the prototype of the column. **ALTER TYPE** does not change the table except that the table is forcibly rewritten. In this way, the data that is no longer used is deleted. * **ALTER \[ COLUMN ] column\_name { SET DEFAULT expression | DROP DEFAULT }** Sets or removes the default value for a column. The default values only apply to subsequent **INSERT** operations; they do not cause rows already in the table to change. Defaults can also be created for views, in which case they are inserted into **INSERT** statements on the view before the view's **ON INSERT** rule is applied. * **ALTER \[ COLUMN ] column\_name { SET | DROP } NOT NULL** Changes whether a column is marked to allow null values or to reject null values. You can only use **SET NOT NULL** when the column contains no null values. * **ALTER \[ COLUMN ] column\_name SET STATISTICS \[PERCENT] integer** Specifies the per-column statistics-gathering target for subsequent **ANALYZE** operations. The target can be set in the range from 0 to 10000. Set it to **–1** to revert to using the default system statistics target. * **{ADD | DELETE} STATISTICS ((column\_1\_name, column\_2\_name \[, ...]))** Adds or deletes the declaration of collecting multi-column statistics to collect multi-column statistics as needed when **ANALYZE** is performed for a table or a database. If the GUC parameter **enable\_functional\_dependency** is disabled, the statistics about a maximum of 32 columns can be collected at a time. If the GUC parameter **enable\_functional\_dependency** is enabled, the statistics about a maximum of 4 columns can be collected at a time. You are not allowed to add or delete such declaration for system catalogs or foreign tables. * **ALTER \[ COLUMN ] column\_name SET ( {attribute\_option = value} \[, ... ] )** **ALTER \[ COLUMN ] column\_name RESET ( attribute\_option \[, ... ] )** Sets or resets per-attribute options. Currently, the only defined per-attribute options are **n\_distinct** and **n\_distinct\_inherited**. **n\_distinct** affects statistics of a table, while **n\_distinct\_inherited** affects the statistics of the table and its subtables. Currently, only **SET/RESET n\_distinct** is supported, and **SET/RESET n\_distinct\_inherited** is forbidden. * **ALTER \[ COLUMN ] column\_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }** Sets the storage mode for a column. This clause specifies whether this column is held inline or in a secondary TOAST table, and whether the data should be compressed. It is set only for row-store tables and is invalid for column-store tables. If it is set for column-store tables, an error will be displayed when the statement is executed. **SET STORAGE** itself does not change anything in the table. It sets the strategy to be pursued during future table updates. * **column\_constraint** is as follows: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | UNIQUE index_parameters | PRIMARY KEY index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * **compress\_mode** of a column is as follows: ``` [ DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS ] ``` * **table\_constraint\_using\_index** used to add the primary key constraint or unique constraint based on the unique index is as follows: ``` [ CONSTRAINT constraint_name ] { UNIQUE | PRIMARY KEY } USING INDEX index_name [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * **table\_constraint** is as follows: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ idx_name ] [ USING method ] ( { { column_name | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] }[, ... ] ) index_parameters | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | FOREIGN KEY [ idx_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` **index\_parameters** is as follows: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * Rename a table. The renaming does not affect stored data. ``` ALTER TABLE [ IF EXISTS ] table_name RENAME TO new_table_name; ``` * Rename the specified column in the table. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME [ COLUMN ] column_name TO new_column_name; ``` * Rename the constraint of the table. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name ) } RENAME CONSTRAINT constraint_name TO new_constraint_name; ``` * Set the schema of the table. ``` ALTER TABLE [ IF EXISTS ] table_name SET SCHEMA new_schema; ``` > \[!NOTE]NOTE > > * The schema setting moves the table into another schema. Associated indexes and constraints owned by table columns are migrated as well. Currently, the schema for sequences cannot be changed. If the table has sequences, delete the sequences, and create them again or delete the ownership between the table and sequences. In this way, the table schema can be changed. > * To change the schema of a table, you must also have the **CREATE** permission on the new schema. To add the table as a new child of a parent table, you must own the parent table as well. To alter the owner, you must also be a direct or indirect member of the new owning role, and that role must have the **CREATE** permission on the table's schema. These restrictions enforce that the user can only recreate and delete the table. However, a system administrator can alter the ownership of any table anyway. > * All the actions except for **RENAME** and **SET SCHEMA** can be combined into a list of multiple alterations to apply in parallel. For example, it is possible to add several columns or alter the type of several columns in a single statement. This is useful with large tables, since only one pass over the tables need be made. > * Adding a **CHECK** or **NOT NULL** constraint will scan the table to validate that existing rows meet the constraint. > * Adding a column with a non-**NULL** default or changing the type of an existing column will rewrite the entire table. Rewriting a large table may take much time and temporarily needs doubled disk space. * Add columns. ``` ALTER TABLE [ IF EXISTS ] table_name ADD ( { [IF NOT EXISTS] column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ]} [, ...] ); ``` * Update columns. ``` ALTER TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type [ ON UPDATE update_expr ]| column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ``` ## Parameter Description * **IF EXISTS** Sends a notice instead of an error if no tables have identical names. The notice prompts that the table you are querying does not exist. * **table\_name \[\*] | ONLY table\_name | ONLY ( table\_name )** **table\_name** is the name of the table that you need to modify. If **ONLY** is specified, only the table is modified. If **ONLY** is not specified, the table and all subtables are modified. You can add the asterisk (\*) option following the table name to specify that all subtables are scanned, which is the default operation. * **constraint\_name** * Specifies the name of an existing constraint to drop in the DROP CONSTRAINT operation. * Specifies the name of a new constraint in the ADD CONSTRAINT operation. > \[!TIP]NOTICE > For a new constraint, constraint\_name is optional in B-compatible mode (**sql\_compatibility = 'B'**). For other modes, constraint\_name must be added. * **index\_name** Specifies the name of an index. > \[!TIP]NOTICE > In the ADD CONSTRAINT operation: > > * index\_name is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * For foreign key constraints, if constraint\_name and index\_name are specified at the same time, constraint\_name is used as the index name. > * For a unique key constraint, if both constraint\_name and index\_name are specified, index\_name is used as the index name. * **USING method** Specifies the name of the index method to be used. For details about the value range, see [USING method](create_index.md). > \[!TIP]NOTICE > In the ADD CONSTRAINT operation: > > * The USING method is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * In B-compatible mode, if USING method is not specified, the default index method is btree for ASTORE or ubtree for USTORE. * **ASC | DESC** **ASC** specifies an ascending (default) sort order. **DESC** specifies a descending sort order. > \[!TIP]NOTICE > In ADD CONSTRAINT, ASC|DESC is supported only in B-compatible databases (sql\_compatibility = 'B'). * **expression** Specifies an expression index constraint created based on one or more columns of the table. The expression index must be written with surrounding parentheses. > \[!TIP]NOTICE > Expression indexes are supported only in B-compatible databases (that is, sql\_compatibility = 'B'). * **storage\_parameter** Specifies the name of a storage parameter. The following option is added for creating an index: * parallel\_workers (int type) Value range: \[0,32]. The value **0** indicates that concurrency is disabled. Number of bgworker threads started when an index is created. For example, **2** indicates that two bgworker threads are started to create indexes concurrently. If this parameter is not set, the number of started bgworker threads is related to the table size. Generally, the number of started bgworker threads does not exceed four. * hasuids (Boolean type) Default value: **off** If this parameter is set to **on**, a unique table-level ID is allocated to a tuple when the tuple is updated. * **new\_owner** Specifies the name of the new table owner. * **new\_tablespace** Specifies the new name of the tablespace to which the table belongs. * **IF NOT EXISTS** If **IF NOT EXISTS** is specified and a column already exists with this name, no error is thrown. * column\_name, column\_1\_name, column\_2\_name Specifies the name of a new or existing column. * **data\_type** Specifies the type of a new column or a new type of an existing column. * **compress\_mode** Compression option of a table field. The clause specifies the compression algorithm preferentially used by the column. Row-store tables do not support compression. * **collation** Specifies the collation rule name of a column. The optional **COLLATE** clause specifies a collation for the new column; if omitted, the collation is the default for the new column. You can run the **select \* from pg\_collation;** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **USING expression** Specifies how to compute the new column value from the old; if omitted, the default conversion is an assignment cast from old data type to new. A **USING** clause must be provided if there is no implicit or assignment cast from the old to new type. > \[!NOTE]NOTE > **USING** in **ALTER TYPE** can specify any expression involving the old values of the row; that is, it can refer to any columns other than the one being cast. This allows general casting to be done with the **ALTER TYPE** syntax. Because of this flexibility, the **USING** expression is not applied to the column's default value (if any); the result might not be a constant expression as required for a default. This means that when there is no implicit or assignment cast from old to new type, **ALTER TYPE** might fail to convert the default even though a **USING** clause is supplied. In such cases, drop the default with **DROP DEFAULT**, perform the **ALTER TYPE**, and then use **SET DEFAULT** to add a suitable new default. Similar considerations apply to indexes and constraints involving the column. * **NOT NULL | NULL** Sets whether the column allows null values. * **integer** Specifies the constant value of a signed integer. When using **PERCENT**, the range of **integer** is from 0 to 100. * **attribute\_option** Specifies an attribute option. * **PLAIN | EXTERNAL | EXTENDED | MAIN** Specifies a column-store mode. * **PLAIN** must be used for fixed-length values (such as integers). It must be inline and uncompressed. * **MAIN** is for inline, compressible data. * **EXTERNAL** is for external, uncompressed data. Use of **EXTERNAL** will make substring operations on **text** and **bytea** values run faster, at the penalty of increased storage space. * **EXTENDED** is for external, compressed data. **EXTENDED** is the default for most data types that support non-**PLAIN** storage. * **CHECK ( expression )** New rows or rows to be updated must satisfy for an expression to be true. If any row produces a false result, an error is raised and the database is not modified. A check constraint specified as a column constraint should reference only the column's values, while an expression in a table constraint can reference multiple columns. Currently, **CHECK ( expression )** does not include subqueries and cannot use variables apart from the current column. * **DEFAULT default\_expr** Assigns a default data value for a column. The data type of the default expression must match the data type of the column. The default expression will be used in any insert operation that does not specify a value for the column. If there is no default value for a column, then the default value is null. * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** Specifies that a group of one or more columns of a table can contain only unique values. * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** Specifies that a column or columns of a table can contain only unique (non-duplicate) and non-null values. * **REFERENCES reftable \[ ( refcolum ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (column constraint)** **FOREIGN KEY ( column\_name \[, ... ] ) REFERENCES reftable \[ ( refcolumn \[, ... ] ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (table constraint)** The foreign key constraint requires that the group consisting of one or more columns in the new table should contain and match only the referenced column values in the referenced table. If **refcolum** is omitted, the primary key of **reftable** is used. The referenced column should be the only column or primary key in the referenced table. A foreign key constraint cannot be defined between a temporary table and a permanent table. There are three types of matching between a reference column and a referenced column: * **MATCH FULL**: A column with multiple foreign keys cannot be **NULL** unless all foreign key columns are **NULL**. * **MATCH SIMPLE** (default): Any unexpected foreign key column can be **NULL**. * **MATCH PARTIAL**: This option is not supported currently. In addition, when you perform certain operations on the data in the referenced table, the operations are performed on the corresponding columns in the new table. **ON DELETE**: specifies the operations to be executed after a referenced row in the referenced table is deleted. **ON UPDATE**: specifies the operation to be performed when the referenced column data in the referenced table is updated. The possible actions of the **ON DELETE** and **ON UPDATE** clauses are as follows: * **NO ACTION** (default): When a foreign key is deleted or updated, an error indicating that the foreign key constraint is violated is created. If the constraint is deferrable and there are still any referenced rows, this error will occur when the constraint is checked. * **RESTRICT**: When a foreign key is deleted or updated, an error indicating that the foreign key constraint is violated is created. It is the same as **NO ACTION** except that the action cannot be delayed. * **CASCADE**: deletes any row that references the deleted row from the new table, or update the field value of the referenced row in the new table to the new value of the referenced column. * **SET NULL**: sets the referenced field to **NULL**. * **SET DEFAULT**: sets referenced fields to their default values. * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(default): Enable constraints, create indexes, and enforce constraints on both existing data and newly added data. * ENABLE NOVALIDATE: Enable constraints and create indexes. For CHECK constraints, the constraints are only enforced for newly added data, regardless of the existing data in the table. For UNIQUE and PRIMARY KEY, indexes need to be established, so the constraints will be enforced for the existing data. * DISABLE( NOVALIDATE)(default): Disable constraints, delete indexes, and operations such as modifying the data of the constraint columns can be performed. * DISABLE VALIDATE: Disable constraints and delete indexes. Insertion, update and deletion operations on the table cannot be performed. * **DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE** Sets whether the constraint can be deferrable. * **DEFERRABLE**: deferrable to the end of the transaction and checked using **SET CONSTRAINTS**. * **NOT DEFERRABLE**: checks immediately after the execution of each command. * **INITIALLY IMMEDIATE**: checks immediately after the execution of each statement. * **INITIALLY DEFERRED**: checks when the transaction ends. > \[!NOTE]NOTE > Ustore tables do not support the **DEFERRABLE** and **INITIALLY DEFERRED** constraints. * **PARTIAL CLUSTER KEY** Specifies a partial cluster key for storage. When importing data to a column-store table, you can perform local data sorting by specified columns (single or multiple). * **WITH ( {storage\_parameter = value} \[, ... ] )** Specifies an optional storage parameter for a table or an index. * **tablespace\_name** Specifies the name of the tablespace where the index locates. * **COMPRESS|NOCOMPRESS** * **NOCOMPRESS**: If the **NOCOMPRESS** keyword is specified, the existing compression feature of the table will not be changed. * **COMPRESS**: If the **COMPRESS** keyword is specified, the table compression feature will be triggered by batch tuple insertion. Row-store tables do not support compression. * **new\_table\_name** Specifies the new table name. * **new\_column\_name** Specifies the new name of a specific column in a table. * **new\_constraint\_name** Specifies the new name of a table constraint. * **new\_schema** Specifies the new schema name. * **CASCADE** Automatically drops objects that depend on the dropped column or constraint (for example, views referencing the column). * **RESTRICT** Refuses to drop the column or constraint if there are any dependent objects. This is the default processing. * **schema\_name** Specifies the schema name of a table. ## Examples See [Examples](create_table.md#en-us_topic_0283137629_en-us_topic_0237122117_en-us_topic_0059778169_s86758dcf05d442d2a9ebd272e76ed1b8) in **CREATE TABLE**. ## Helpful Links [CREATE TABLE](create_table.md) and [DROP TABLE](drop_table.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-ALTER-TABLE.md --- # ALTER TABLE ## 功能描述 修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 * 当一条语句下有多条子命令时,drop index和rename index会优先其他子命令执行,这两种命令的优先级一致。 * 生成列语法支持忽略GENERATED ALWAYS。 ## 语法格式 * 修改表的定义。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | (ONLY) table_name | (ONLY) ( table_name ) } action [, ... ]; ``` 其中具体表操作action可以是以下子句之一: ``` column_clause | ADD [ COLUMN ] ( { column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ … ] ] } [, …] ) | {DISABLE | ENABLE} KEYS | DROP INDEX index_name [ RESTRICT | CASCADE ] | DROP PRIMARY KEY [ RESTRICT | CASCADE ] | DROP FOREIGN KEY foreign_key_name [ RESTRICT | CASCADE ] | RENAME INDEX index_name to new_index_name | ADD table_indexclause | MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP | alter_table_option [[,] ...] ``` 其中具体表选项alter\_table\_option为: ``` | AUTOEXTEND_SIZE [=] value | AUTO_INCREMENT [=] value | AVG_ROW_LENGTH [=] value | [DEFAULT] { CHARSET | CHARACTER SET } [=] charset_name | CHECKSUM [=] value | [DEFAULT] COLLATE [=] collation_name | COMMENT [=] 'text' | CONNECTION [=] 'connect_string' | {DATA | INDEX} DIRECTORY [=] 'absolute path to directory' | DELAY_KEY_WRITE [=] value | ENCRYPTION [=] 'encryption_string' | ENGINE_ATTRIBUTE [=] 'string' | INSERT_METHOD [=] { NO | FIRST | LAST } | KEY_BLOCK_SIZE [=] value | MAX_ROWS [=] value | MIN_ROWS [=] value | PACK_KEYS [=] value | PASSWORD [=] 'password' | ROW_FORMAT [=] row_format_name | START TRANSACTION | SECONDARY_ENGINE_ATTRIBUTE [=] 'string' | STATS_AUTO_RECALC [=] value | STATS_PERSISTENT [=] value | STATS_SAMPLE_PAGES [=] value | UNION [=] (tbl_name[,tbl_name]...) | TABLESPACE tablespace_name [STORAGE DISK] | [TABLESPACE tablespace_name] STORAGE MEMORY ``` 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | [GENERATED ALWAYS] AS ( generation_expr ) [STORED] | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE [KEY] index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` ```` - 向表中增加多列。BINARY关键字将设置列的字符序为该列字符集对应的`_bin`字符序。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。 ASCII关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 ``` ALTER TABLE ADD [ COLUMN ] ( { column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ … ] ] } [, …] ) ``` ```` * 对一个表进行重建。 ``` ALTER TABLE table_name FORCE; ``` * 重命名表。对名称的修改不会影响所存储的数据。 ``` ALTER TABLE [ IF EXISTS ] table_name RENAME [ TO | AS ] new_table_name; ``` * 对表timestamp列添加ON UPDATE属性。 ```sql ALTER TABLE table_name MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP; ``` * 对表timestamp列删除ON UPDATE属性。 ```sql ALTER TABLE table_name MODIFY column_name column_type; ``` * **ADD table\_indexclause** 在表上新增一个索引 ``` {[FULLTEXT] INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option]... ``` 其中参数index\_type为: ``` USING {BTREE | HASH | GIN | GIST | PSORT | UBTREE} ``` 其中参数key\_part为: ``` {col_name[(length)] | (expr)} [ASC | DESC] ``` 其中参数index\_option为: ``` index_option:{ COMMENT 'string' | index_type | [ VISIBLE | INVISIBLE ] | [WITH PARSER NGRAM] } ``` COMMENT、index\_type、\[ VISIBLE | INVISIBLE ] 的顺序和数量任意,但相同字段仅最后一个值生效。WITH PARSER NGRAM 为FULLTEXT INDEX指定的ngram解析器,前提是索引必须指定关键字FULLTEXT,FULLTEXT 默认 WITH PARSER NGRAM。 ## 参数说明 * **{DISABLE | ENABLE} KEYS** 禁用和启用一个表的所有非唯一索引。 * **DROP INDEX index\_name \[ RESTRICT | CASCADE ]** 删除一个表的索引。 * **DROP PRIMARY KEY \[ RESTRICT | CASCADE ]** 删除一个表的主键。 * **DROP FOREIGN KEY foreign\_key\_name \[ RESTRICT | CASCADE ]** 删除一个表的外键。 * **RENAME INDEX index\_name to new\_index\_name** 重命名一个表的索引。 * **AUTOEXTEND\_SIZE \[=] value** 用于指定在表空间变满时扩展表空间大小;目前该特性仅有语法支持,不实现功能。参数的取值范围包括非负整数,小数,标识符,非负整数+标识符,小数+标识符。 * **AVG\_ROW\_LENGTH \[=] value** 用于指定表的平均行长度;目前该特性仅有语法支持,不实现功能。参数的取值范围包括非负整数,小数。 * **CHECKSUM \[=] value** 用于指定是否维护所有行的实时校验和;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **CONNECTION \[=] 'connect\_string'** 用于指定联合表的连接字符串;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **{DATA | INDEX} DIRECTORY \[=] 'absolute path to directory'** 用于指定表数据数据和索引的存储目录;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **DELAY\_KEY\_WRITE \[=] value** 用于指定是否延迟表的键更新直到表关闭;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **ENCRYPTION \[=] 'encryption\_string'** 用于指定表启用或禁用页面级数据加密;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **ENGINE\_ATTRIBUTE \[=] 'string'** 用于指定主存储引擎的表属性;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **INSERT\_METHOD \[=] { NO | FIRST | LAST }** 用于指定应将行插入到的表;目前该特性仅有语法支持,不实现功能。参数的取值范围为NO,FIRST,LAST。 * **KEY\_BLOCK\_SIZE \[=] value** 用于指定索引键块的字节大小;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **MAX\_ROWS \[=] value** 用于指定计划在表中存储的最大行数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **MIN\_ROWS \[=] value** 用于指定计划在表中存储的最小行数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **PACK\_KEYS \[=] value** 用于指定控制压缩索引的方式;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **PASSWORD \[=] 'password'** 此选项未使用;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **SECONDARY\_ENGINE\_ATTRIBUTE \[=] 'string'** 用于指定辅助存储引擎的表属性;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **START TRANSACTION** 用于开启事务模式;目前该特性仅有语法支持,不实现功能。 * **STATS\_AUTO\_RECALC \[=] value** 用于指定是否自动重新计算表的持久统计信息;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **STATS\_PERSISTENT \[=] value** 用于指定是否为表启用持久统计信息;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **STATS\_SAMPLE\_PAGES \[=] value** 用于指定估计索引列的基数和其他统计信息时要采样的索引页数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **UNION \[=] (tbl\_name\[,tbl\_name]...)** 用于访问一组相同的表作为一个表;目前该特性仅有语法支持,不实现功能。 * **TABLESPACE tablespace\_name \[STORAGE DISK]** 用于指定表存储在磁盘;目前该特性仅有语法支持,不实现功能。 * **\[TABLESPACE tablespace\_name] STORAGE MEMORY** 用于指定表存储在内存;目前该特性仅有语法支持,不实现功能。 其中列相关的操作column\_clause可以是以下子句之一: ``` ADD [ COLUMN ] column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] [ FIRST | AFTER column_name ] | MODIFY [ COLUMN ] column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [{[ COLLATE collation ] | [ column_constraint ]} [ ... ] ] [FIRST | AFTER column_name] | CHANGE [ COLUMN ] old_column_name new_column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [{[ COLLATE collation ] | [ column_constraint ]} [ ... ] ] [FIRST | AFTER column_name] ``` * **ADD \[ COLUMN ] column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[BINARY | ASCII] \[ compress\_mode ] \[ COLLATE collation ] \[ column\_constraint \[ ... ] ] \[ FIRST | AFTER column\_name]** 向表中增加一个新的字段。用ADD COLUMN增加一个字段,所有表中现有行都初始化为该字段的缺省值(如果没有声明DEFAULT子句,值为NULL)。其中FIRST | AFTER column\_name表示新增字段到某个位置。BINARY关键字将设置列的字符序为该列字符集对应的`_bin`字符序,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`。ASCII关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 * **MODIFY \[ COLUMN ] column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[BINARY | ASCII] \[{\[ COLLATE collation ] | \[ column\_constraint ]} \[ ... ] ] \[FIRST | AFTER column\_name]** 修改表已存在字段的定义,将用新定义替换字段原定义,原字段上的索引、独立对象约束(例如:主键、唯一键、CHECK约束等)不会被删除。\[FIRST | AFTER column\_name]语法表示修改字段定义的同时修改字段在表中的位置。BINARY关键字将设置列的字符序为该列字符集对应的`_bin`字符序,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`。ASCII关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 * **CHANGE \[ COLUMN ] old\_column\_name new\_column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[BINARY | ASCII] \[{\[ COLLATE collation ] | \[ column\_constraint ]} \[ ... ] ] \[FIRST | AFTER column\_name]** 修改表已存在字段的名称和定义,字段新名称不能是已有字段的名称,将用新名称和定义替换字段原名称和定义原字段上的索引、独立对象约束(例如:主键、唯一键、CHECK约束)等不会被删除。\[FIRST | AFTER column\_name]语法表示修改字段名称和定义的同时修改字段在表中的位置。BINARY关键字将设置列的字符序为该列字符集对应的`_bin`字符序,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`。ASCII关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 > \[!NOTE]说明 > > 涉及的参数说明可见[ALTER TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_table.html)。 ## 示例 \--- 创建表、外键和非唯一索引。 ``` openGauss=# CREATE TABLE alter_table_tbl1 (a INT PRIMARY KEY, b INT); openGauss=# CREATE TABLE alter_table_tbl2 (c INT PRIMARY KEY, d INT); openGauss=# ALTER TABLE alter_table_tbl2 ADD CONSTRAINT alter_table_tbl_fk FOREIGN KEY (d) REFERENCES alter_table_tbl1 (a); openGauss=# CREATE INDEX alter_table_tbl_b_ind ON alter_table_tbl1(b); ``` \--- 禁用和启用非唯一索引。 ``` openGauss=# ALTER TABLE alter_table_tbl1 DISABLE KEYS; openGauss=# ALTER TABLE alter_table_tbl1 ENABLE KEYS; ``` \--- 删除索引。 ``` openGauss=# ALTER TABLE alter_table_tbl1 DROP KEY alter_table_tbl_b_ind; ``` \--- 删除主键。 ``` openGauss=# ALTER TABLE alter_table_tbl2 DROP PRIMARY KEY; ``` \--- 删除外键。 ``` openGauss=# ALTER TABLE alter_table_tbl2 DROP FOREIGN KEY alter_table_tbl_fk; ``` \--- 重建表。 ``` openGauss=# ALTER TABLE alter_table_tbl1 FORCE; ``` \--- 重命名索引。 ``` openGauss=# CREATE INDEX alter_table_tbl_b_ind ON alter_table_tbl1(b); openGauss=# ALTER TABLE alter_table_tbl1 RENAME INDEX alter_table_tbl_b_ind TO new_alter_table_tbl_b_ind; ``` \--- 修改表,创建INVISIBLE普通索引 ``` openGauss=# ALTER TABLE alter_table_tbl1 ADD INDEX alter_table_tbl_b_ind(b) INVISIBLE; ``` \--- 删除表。 ``` openGauss=# DROP TABLE alter_table_tbl1, alter_table_tbl2; ``` \--- 兼容MySQL全文索引,添加全文索引语法,前提是兼容模式为B的数据库。 ```sql test=# ALTER TABLE test ADD FULLTEXT INDEX test_index_1 (title, boby) WITH PARSER ngram; ALTER TABLE test=# \d test_index_1 Index "fulltext_test.test_index_1" Column | Type | Definition --------------+------+------------------------------------------------ to_tsvector | text | to_tsvector('"ngram"'::regconfig, title::text) to_tsvector1 | text | to_tsvector('"ngram"'::regconfig, boby) gin, for table "fulltext_test.test" ``` ## 相关链接 [ALTER TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_table.html) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-ALTER-TABLE.md --- # ALTER TABLE ## 功能描述 修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。 * 新增支持`opt_clustered`语法。 * 修改表语句中,针对UNIQUE和PRIMARY KEY约束,支持通过WITH给出选项,对应index\_parameters子句,新增支持的选项包括: ``` FILLFACTOR = fillfactor | PAD_INDEX = { ON | OFF } | IGNORE_DUP_KEY = { ON | OFF } | STATISTICS_NORECOMPUTE = { ON | OFF } | STATISTICS_INCREMENTAL = { ON | OFF } | ALLOW_ROW_LOCKS = { ON | OFF } | ALLOW_PAGE_LOCKS = { ON | OFF } | OPTIMIZE_FOR_SEQUENTIAL_KEY = { ON | OFF } | XML_COMPRESSION = { ON | OFF } | COMPRESSION_DELAY = { 0 | delay [ MINUTES | MINUTE ] } | DATA_COMPRESSION = { NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE } ``` 其中FILLFACTOR选项的取值fillfactor为\[1, 100]的整数,实际含义同A库(A库的取值范围为\[10, 100]的整数),因此当D库中fillfactor的取值范围为\[1, 10),不报错,将打印notice信息,并将fillfactor的取值设置为A库的最小值10; COMPRESSION\_DELAY选项的取值delay为\[0, 10080]的整数; 除FILLFACTOR选项含有实际功能,同A库,其余参数均无实际功能,仅语法支持。 * 修改表语句中,针对UNIQUE和PRIMARY KEY约束,支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * filegroup为任意字符串,支持通过\[]包裹。 * 新增支持为列添加identity属性的语法。 ## 语法格式 * 修改表的定义。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | (ONLY) table_name | (ONLY) ( table_name ) } action [, ... ]; ``` 其中具体表操作action可以是以下子句之一: ``` column_clause | ADD table_constraint [ NOT VALID ] | ADD table_constraint_using_index | VALIDATE CONSTRAINT constraint_name | DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ] | CLUSTER ON index_name | SET WITHOUT CLUSTER | SET ( {storage_parameter = value} [, ... ] ) | RESET ( storage_parameter [, ... ] ) | OWNER TO new_owner | SET TABLESPACE new_tablespace | SET {COMPRESS|NOCOMPRESS} | TO { GROUP groupname | NODE ( nodename [, ... ] ) } | ADD NODE ( nodename [, ... ] ) | DELETE NODE ( nodename [, ... ] ) | DISABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE REPLICA TRIGGER trigger_name | ENABLE ALWAYS TRIGGER trigger_name | DISABLE/ENABLE [ REPLICA | ALWAYS ] RULE | DISABLE ROW LEVEL SECURITY | ENABLE ROW LEVEL SECURITY | FORCE ROW LEVEL SECURITY | NO FORCE ROW LEVEL SECURITY | ENCRYPTION KEY ROTATION | INHERIT parents | NO INHERIT parents | OF type_name | NOT OF | REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING } | AUTO_INCREMENT [ = ] value | COMMENT {=| } 'text' | ALTER INDEX index_name [ VISBLE | INVISIBLE ] | [ [ DEFAULT ] CHARACTER SET | CHARSET [ = ] default_charset ] [ [ DEFAULT ] COLLATE [ = ] default_collation ] | CONVERT TO CHARACTER SET | CHARSET charset | DEFAULT [ COLLATE collation ] | MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP | IMCSTORED [ ( column_name [, ...] ) ] | MODIFY PARTITION partition_name IMCSTORED [ ( column_name [, ...] ) ] | UNIMCSTORED | MODIFY PARTITION partition_name UNIMCSTORED ``` * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | IDENTITY [ ( seed, increment ) ] | GENERATED ALWAYS AS ( generation_expr ) [STORED] | ON UPDATE update_expr | { UNIQUE [KEY] index_parameters [ ON filegroup ] | PRIMARY KEY index_parameters [ ON filegroup ] } [ { ENABLE | DISABLE } [ VALIDATE | NOVALIDATE ] | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] [ ENABLE ] | { ENABLE | DISABLE } [ VALIDATE | NOVALIDATE ] Constraint constraint_name | DEFAULT (expression) FOR (column_name) } | AUTO_INCREMENT | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] | [ COMMENT 'text' ] ``` * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ opt_clustered ] ( { { column_name [ ( length ) ] | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] [ ON filegroup ] | PRIMARY KEY [ opt_clustered ] ( { column_name [ ASC | DESC ] }[, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] [ ON filegroup ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | FOREIGN KEY [ idx_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 其中索引参数index\_parameters为: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## 参数说明 * **opt\_clustered** 参数内容为CLUSTERED/NONCLUSTERED,兼容D库的语法,指定创建聚合/非聚合索引。仅语法作用,没有实际功能。 * **WITH ( { storage\_parameter = value } \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。用于表的WITH子句还可以包含OIDS=FALSE表示不分配OID。 针对UNIQUE和PRIMARY KEY约束,新增支持的storage\_parameter选项包括: * FILLFACTOR int类型,填充因子,实际的含义和功能同A库。 取值范围:\[1, 100]的整数,A库的取值范围为\[10, 100]的整数,因此当D库中fillfactor的取值范围为\[1, 10),不报错,将打印notice信息,并将fillfactor的取值设置为A库的最小值10。 * PAD\_INDEX bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * IGNORE\_DUP\_KEY bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * STATISTICS\_NORECOMPUTE bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * STATISTICS\_INCREMENTAL bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * ALLOW\_ROW\_LOCKS bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * ALLOW\_PAGE\_LOCKS bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * OPTIMIZE\_FOR\_SEQUENTIAL\_KEY bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * XML\_COMPRESSION bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * COMPRESSION\_DELAY int类型,单位MINUTES或者MINUTE,可选,无实际功能,仅语法兼容。 取值范围:0 | delay \[ MINUTES | MINUTE ],其中delay为\[0, 10080]的整数。 * DATA\_COMPRESSION string类型,无实际功能,仅语法兼容。 取值范围:NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE\_ARCHIVE。 * **filegroup** * 修改表语句中,针对UNIQUE和PRIMARY KEY约束,支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * filegroup为任意字符串,支持通过\[]包裹。 * **DEFAULT ( expression ) FOR ( column\_name )** * 该语法可以为指定列添加DEFAULT约束,该约束为一个表达式。 * 对于显式声明约束名的场景,仅做语法支持,使用该语法创建的DEFAULT约束无法通过约束名进行删除。 * **IDENTITY \[ ( seed, increment ) ]** * 该语法为列添加identity属性,序列值递增,`seed`指定起始值,`increment`指定步长。 * 一张表只能定义一列(包括generated as identity)。 ## opt\_clustered示例 ```sql openGauss=# CREATE TABLE alter_table_tbl1 (a INT, b INT); openGauss=# ALTER TABLE alter_table_tbl1 ADD CONSTRAINT alter_table_tbl_a UNIQUE CLUSTERED (a); openGauss=# ALTER TABLE alter_table_tbl1 ADD CONSTRAINT alter_table_tbl_b PRIMARY KEY NONCLUSTERED (a); ``` ## WITH ( { storage\_parameter = value } \[, ... ] )示例 ```sql create table test1(col1 int primary key with(fillfactor = 20), col2 int); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test1_pkey" for table "test1" alter table test1 add constraint unique_name unique(col2) with (fillfactor = 50, ignore_dup_key = on); NOTICE: parameter "ignore_dup_key" is currently ignored. NOTICE: ALTER TABLE / ADD UNIQUE will create implicit index "unique_name" for table "test1" alter table test1 add column col3 int unique with (pad_index = on); NOTICE: parameter "pad_index" is currently ignored. NOTICE: ALTER TABLE / ADD UNIQUE will create implicit index "test1_col3_key" for table "test1" create table test2(col1 int, col2 int); alter table test2 add constraint pk_id primary key(col1) with (fillfactor = 50, allow_row_locks = off); NOTICE: parameter "allow_row_locks" is currently ignored. NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index "pk_id" for table "test2" create table test3(col1 int, col2 int); alter table test3 add column col3 int primary key with (data_compression = none); NOTICE: parameter "data_compression" is currently ignored. NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index "test3_pkey" for table "test3" ``` ## filegroup示例 ```sql create table test1(col1 int primary key with(fillfactor = 20), col2 int); alter table test1 add constraint unique_name unique(col2) with (fillfactor = 50, ignore_dup_key = on) on [primary1]; alter table test1 add column col3 int unique with (pad_index = on) on [primary2]; create table test2(col1 int, col2 int); alter table test2 add constraint pk_id primary key(col1) with (fillfactor = 50, allow_row_locks = off) on [primar3]; create table test3(col1 int, col2 int); alter table test3 add column col3 int primary key with (data_compression = none) on [primar4]; ``` ## IDENTITY \[ ( seed, increment ) ] 示例 ```sql openGauss=# create extension shark; CREATE EXTENSION openGauss=# create table t1 (a int identity(10, 20), b int); NOTICE: CREATE TABLE will create implicit sequence "t1_a_seq_identity" for serial column "t1.a" CREATE TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+-------------------+---------+--------------+------------- a | integer | not null identity | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no, collate=1537 Character Set: UTF8 Collate: utf8mb4_general_ci openGauss=# alter table t1 alter column b add identity ; NOTICE: ALTER TABLE will create implicit sequence "t1_b_seq_identity" for serial column "t1.b" ERROR: Multiple identity columns specified for table "t1". Only one identity column per table is allowed. openGauss=# create table t2 (a int, b int); CREATE TABLE openGauss=# alter table t2 alter column b add identity ; NOTICE: ALTER TABLE will create implicit sequence "t2_b_seq_identity" for serial column "t2.b" ERROR: column "b" of relation "t2" must be declared NOT NULL before identity can be added openGauss=# alter table t2 alter column b set not null; ALTER TABLE openGauss=# alter table t2 alter column b add identity ; NOTICE: ALTER TABLE will create implicit sequence "t2_b_seq_identity" for serial column "t2.b" ALTER TABLE openGauss=# ``` ## DEFAULT (expression) FOR (column\_name) 示例 ```sql openGauss=# create table ADD_DEFAULT(id int, v1 varchar(20), v2 float); CREATE TABLE openGauss=# \d+ ADD_DEFAULT Table "public.add_default" Column | Type | Modifiers | Storage | Stats target | Description --------+-----------------------+-----------+----------+--------------+------------- id | integer | | plain | | v1 | character varying(20) | | extended | | v2 | double precision | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table ADD_DEFAULT add default (mod(4, 3)) for id; NOTICE: DEFAULT added. The added DEFAULT can not be dropped by name ALTER TABLE openGauss=# \d+ ADD_DEFAULT Table "public.add_default" Column | Type | Modifiers | Storage | Stats target | Description --------+-----------------------+-------------------+----------+--------------+------------- id | integer | default mod(4, 3) | plain | | v1 | character varying(20) | | extended | | v2 | double precision | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# insert into ADD_DEFAULT(v1, v2) values('bac', 3.1); INSERT 0 1 openGauss=# select * from ADD_DEFAULT; id | v1 | v2 ----+-----+----- 1 | bac | 3.1 (1 row) openGauss=# create table ADD_CONSTRAINT_DEFAULT(id int, v1 varchar(20), v2 timestamptz); CREATE TABLE openGauss=# \d+ ADD_CONSTRAINT_DEFAULT Table "public.add_constraint_default" Column | Type | Modifiers | Storage | Stats target | Description --------+--------------------------+-----------+----------+--------------+------------- id | integer | | plain | | v1 | character varying(20) | | extended | | v2 | timestamp with time zone | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table ADD_CONSTRAINT_DEFAULT add constraint ADD_SYSTEIME_DEFAULT default (pg_systimestamp()) for v2; NOTICE: DEFAULT added. The added DEFAULT can not be dropped by name ALTER TABLE test_d=# \d+ ADD_CONSTRAINT_DEFAULT Table "public.add_constraint_default" Column | Type | Modifiers | Storage | Stats target | Description --------+--------------------------+---------------------------+----------+--------------+------------- id | integer | | plain | | v1 | character varying(20) | | extended | | v2 | timestamp with time zone | default pg_systimestamp() | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# insert into ADD_CONSTRAINT_DEFAULT(id, v1) values(1, 'abc'); INSERT 0 1 openGauss=# select * from ADD_CONSTRAINT_DEFAULT; id | v1 | v2 ----+-----+------------------------------- 1 | abc | 2025-10-30 11:17:36.821797+08 (1 row) ``` ## 相关链接 [ALTER TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_table.html) --- --- url: /zh/docs/latest-lite/sql_reference/alter_table.md --- # ALTER TABLE ## 功能描述 修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关。 ## 注意事项 * 表的所有者、被授予了表ALTER权限的用户或被授予ALTER ANY TABLE的用户有权限执行ALTER TABLE命令,系统管理员默认拥有此权限。但要修改表的所有者或者修改表的模式,当前用户必须是该表的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 不能修改分区表的tablespace,但可以修改分区的tablespace。 * 不支持修改存储参数ORIENTATION。 * SET SCHEMA操作不支持修改为系统内部模式,当前仅支持用户模式之间的修改。 * 列存表只支持PARTIAL CLUSTER KEY、UNIQUE、PRIMARY KEY表级约束,不支持外键等表级约束。 * 列存表只支持添加字段ADD COLUMN、修改字段的数据类型ALTER TYPE、设置单个字段的收集目标SET STATISTICS、支持更改表名称、支持更改表空间,支持删除字段DROP COLUMN。对于添加的字段和修改的字段类型要求是列存支持的[数据类型](numeric_types.md)。ALTER TYPE的USING选项只支持常量表达式和涉及本字段的表达式,暂不支持涉及其他字段的表达式。 * 列存表支持的字段约束包括NULL、NOT NULL和DEFAULT常量值、UNIQUE和PRIMARY KEY;对字段约束的修改当前只支持对DEFAULT值的修改(SET DEFAULT)和删除(DROP DEFAULT),暂不支持对非空约束NULL/NOT NULL的修改。 * 不支持增加自增列,或者增加DEFAULT值中包含nextval()表达式的列。 * 不支持对外表、临时表开启行访问控制开关。 * 通过约束名删除PRIMARY KEY约束时,不会删除NOT NULL约束,如果有需要,请手动删除NOT NULL约束。 * 使用JDBC时,支持通过PrepareStatement对DEFAULT值进行参数化设置。 * 重命名时,不能与当前模式下已存在的synonym产生命名冲突。 * 修改模式时,不能与新模式下已存在的synonym产生命名冲突。 * 仅支持在B兼容性数据库下指定COMMENT和可见性VISIBLE\INVISIBLE。 * 使用FIRST | AFTER column\_name新增列或修改列,或修改字段的字符集,会带来全表更新开销,影响在线业务。向已有的字段之间新插入列时,需要保证引用了字段的视图对象有效。 * 删除被视图引用的表字段或修改表字段类型以及字段长度时,将引用视图和物化视图置为无效状态,在查询无效视图或通过无效视图更新、删除和新增表记录以及全量更新物化视图时,检查无效的视图和物化视图引用的表字段是否全部存在,如果存在恢复视图和物化视图的有效状态并返回查询结果,否则报错提示查询无效视图。 ## 语法格式 * 修改表的定义。 ``` ALTER TABLE [CONCURRENTLY] [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name ) } action [, ... ]; ``` 其中具体表操作action可以是以下子句之一: ``` column_clause | ADD table_constraint [ NOT VALID ] | ADD table_constraint_using_index | VALIDATE CONSTRAINT constraint_name | DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ] | CLUSTER ON index_name | SET WITHOUT CLUSTER | SET ( {storage_parameter = value} [, ... ] ) | RESET ( storage_parameter [, ... ] ) | OWNER TO new_owner | SET TABLESPACE new_tablespace | SET {COMPRESS|NOCOMPRESS} | TO { GROUP groupname | NODE ( nodename [, ... ] ) } | ADD NODE ( nodename [, ... ] ) | DELETE NODE ( nodename [, ... ] ) | DISABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE REPLICA TRIGGER trigger_name | ENABLE ALWAYS TRIGGER trigger_name | DISABLE/ENABLE [ REPLICA | ALWAYS ] RULE | DISABLE ROW LEVEL SECURITY | ENABLE ROW LEVEL SECURITY | FORCE ROW LEVEL SECURITY | NO FORCE ROW LEVEL SECURITY | ENCRYPTION KEY ROTATION | INHERIT parents | NO INHERIT parents | OF type_name | NOT OF | REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING } | AUTO_INCREMENT [ = ] value | COMMENT {=| } 'text' | ALTER INDEX index_name [ VISBLE | INVISIBLE ] | [ [ DEFAULT ] CHARACTER SET | CHARSET [ = ] default_charset ] [ [ DEFAULT ] COLLATE [ = ] default_collation ] | CONVERT TO CHARACTER SET | CHARSET charset | DEFAULT [ COLLATE collation ] | REDISANYVALUE ``` \[!NOTE]说明 > * **ADD table\_constraint \[ NOT VALID ]** > 给表增加一个新的约束。 > > * **ADD table\_constraint\_using\_index** > 根据已有唯一索引为表增加主键约束或唯一约束。 > > * **VALIDATE CONSTRAINT constraint\_name** > 验证一个使用NOT VALID选项创建的检查类约束,通过扫描全表来保证所有记录都符合约束条件。如果约束已标记为有效时,什么操作也不会发生。 > > * **DROP CONSTRAINT \[ IF EXISTS ] constraint\_name \[ RESTRICT | CASCADE ]** > 删除一个表上的约束。 > > * **CLUSTER ON index\_name** > 为将来的CLUSTER(聚簇)操作选择默认索引。实际上并没有重新盘簇化处理该表。 > > * **SET WITHOUT CLUSTER** > 从表中删除最新使用的CLUSTER索引。这样会影响将来那些没有声明索引的CLUSTER(聚簇)操作。 > > * **SET ( {storage\_parameter = value} \[, ... ] )** > 修改表的一个或多个存储参数。 > > * **RESET ( storage\_parameter \[, ... ] )** > 重置表的一个或多个存储参数。与SET一样,根据参数的不同可能需要重写表才能获得想要的效果。 > > * **OWNER TO new\_owner** > 将表、序列、视图的属主改变成指定的用户。 > > * **SET TABLESPACE new\_tablespace** > 这种形式将表空间修改为指定的表空间并将相关的数据文件移动到新的表空间。但是表上的所有索引都不会被移动,索引可以通过ALTER INDEX语法的SET TABLESPACE选项来修改索引的表空间。 > > * **SET {COMPRESS|NOCOMPRESS}** > 修改表的压缩特性。表压缩特性的改变只会影响后续批量插入的数据的存储方式,对已有数据的存储毫无影响。也就是说,表压缩特性的修改会导致该表中同时存在着已压缩和未压缩的数据。行存表不支持压缩。 > > * **TO { GROUP groupname | NODE ( nodename \[, ... ] ) }** > 此语法仅在扩展模式(GUC参数support\_extended\_features为on时)下可用。该模式谨慎打开,主要供内部扩容工具使用,一般用户不应使用该模式。 > > * **ADD NODE ( nodename \[, ... ] )** > 此语法主要供内部扩容工具使用,一般用户不建议使用。 > > * **DELETE NODE ( nodename \[, ... ] )** > 此语法主要供内部缩容工具使用,一般用户不建议使用。 > > * **DISABLE TRIGGER \[ trigger\_name | ALL | USER ]** > 禁用trigger\_name所表示的单个触发器,或禁用所有触发器,或仅禁用用户触发器(此选项不包括内部生成的约束触发器,例如,可延迟唯一性和排除约束的约束触发器)。 > 应谨慎使用此功能,因为如果不执行触发器,则无法保证原先期望的约束的完整性。 > > * **| ENABLE TRIGGER \[ trigger\_name | ALL | USER ]** > 启用trigger\_name所表示的单个触发器,或启用所有触发器,或仅启用用户触发器。 > > * **| ENABLE REPLICA TRIGGER trigger\_name** > 触发器触发机制受配置变量[session\_replication\_role](../database_reference/statement_behavior.md#zh-cn_topic_0283136752_zh-cn_topic_0237124732_zh-cn_topic_0059779117_sffbd1c48d86b4c3fa3287167a7810216)的影响,当复制角色为“origin”(默认值)或“local”时,将触发简单启用的触发器。 > 配置为ENABLE REPLICA的触发器仅在会话处于“replica”模式时触发。 > > * **| ENABLE ALWAYS TRIGGER trigger\_name** > 无论当前复制模式如何,配置为ENABLE ALWAYS的触发器都将触发。 > > * **| DISABLE/ENABLE \[ REPLICA | ALWAYS ] RULE** > 配置属于表的重写规则,已禁用的规则对系统来说仍然是可见的,只是在查询重写期间不被应用。语义为关闭/启动规则。由于关系到视图的实现,ON SELECT规则不可禁用。 配置为ENABLE REPLICA的规则将会仅在会话为"replica" 模式时启动,而配置为ENABLE ALWAYS的触发器将总是会启动,不考虑当前复制模式。规则触发机制也受配置变量[session\_replication\_role](../database_reference/statement_behavior.md#zh-cn_topic_0283136752_zh-cn_topic_0237124732_zh-cn_topic_0059779117_sffbd1c48d86b4c3fa3287167a7810216)的影响,类似于上述触发器。 > > * **| DISABLE/ENABLE ROW LEVEL SECURITY** > 开启或关闭表的行访问控制开关。 > 当开启行访问控制开关时,如果未在该数据表定义相关行访问控制策略,数据表的行级访问将不受影响;如果关闭表的行访问控制开关,即使定义了行访问控制策略,数据表的行访问也不受影响。详细信息参见[CREATE ROW LEVEL SECURITY POLICY](create_row_level_security_policy.md)章节。 > > * **| NO FORCE/FORCE ROW LEVEL SECURITY** > 强制开启或关闭表的行访问控制开关。 > 默认情况,表所有者不受行访问控制特性影响,但当强制开启表的行访问控制开关时,表的所有者(不包含系统管理员用户)会受影响。系统管理员可以绕过所有的行访问控制策略,不受影响。 > > * **| ENCRYPTION KEY ROTATION** > > 透明数据加密密钥轮转。只有在数据库开启透明加密功能,并且表的enable\_tde选项为on时才可以进行表的数据加密密钥轮转。执行密钥轮转操作后,系统会自动向KMS申请创建新的密钥。密钥轮转后,使用旧密钥加密的数据仍使用旧密钥解密,新写入的数据使用新密钥加密。为保证加密数据安全,用户可根据加密表的新增数据量大小定期更新密钥,建议更新周期为两到三年。 > > * **INHERIT parent\_table** > 将目标资料表加到指定的父资料表中成为新的子资料表。之后,针对父资料表的查询将会包含目标资料表的资料。要作为子资料表加入前,目标资料表必须已经包含父资料表的所有栏位。这些栏位必须具有可匹配的资料类别,并且如果他们在父资料表中具有NOT NULL的限制条件,那么他们必须在子资料表中也具有NOT NULL的限制条件。对于父资料表的所有CHECK限制条件,必须还有相对应的子资料表限制条件,除非父资料表中标记为不可继承。 > > * **NO INHERIT parent\_table** > 从指定的父资料表的子资料表中产出目标资料表。针对父资料表的查询将不再包含从目标资料表中所产生的记录。 > > * **OF type\_name** > 将表连接至一种复合类型,与CREATE TABLE OF选项创建表一样。表的字段的名称和类型必须精确匹配复合类型中的定义,不过oid系统字段允许不一样。表不能是从任何其他表继承的。这些限制确保CREATE TABLE OF选项允许一个相同的表定义。 > > * **NOT OF** > 将一个与某类型进行关联的表进行关联的解除。 > > - **REPLICA IDENTITY { DEFAULT | USING INDEX index\_name | FULL | NOTHING }** > 在逻辑复制场景下,指定该表的UPDATE和DELETE操作中旧元组的记录级别。 > > * DEFAULT记录主键的列的旧值,没有主键则不记录。 > > * USING INDEX记录命名索引覆盖的列的旧值,这些值必须是唯一的、不局部的、不可延迟的,并且仅包括标记为NOT NULL的列。 > > * FULL记录该行中所有列的旧值。 > > * NOTHING不记录有关旧行的信息。 > > 在逻辑复制场景,解析该表的UPDATE和DELETE操作语句时,解析出的旧元组由以此方法记录的信息组成。对于有主键表该选项可设置为DEFAULT或FULL。对于无主键表该选项需设置为FULL,否则解码时旧元组将解析为空。一般场景不建议设置为NOTHING,旧元组会始终解析为空。 > > 即使指定DEFAULT或USING INDEX,当前Ustore表列的旧值中也可能包含该行所有列的旧值,只有旧值涉及toast该配置选项才会生效。另外针对Ustore表,选项NOTHING无效,实际效果等同于FULL。 > > - **AUTO\_INCREMENT \[ = ] value** > > 设置自动增长列下一次的自增值。设置的值只有大于当前自增计数器时才会生效。 > > value必须是非负整数,且不得大于2127-1。 > > 该子句仅在参数sql\_compatibility=B时生效。 > > - **COMMENT 'text'** > > 修改表对象的注释。 > > * **ALTER INDEX index\_name \[ VISBLE | INVISIBLE ]** > > 修改索引的可见性。 > > * **\[ \[ DEFAULT ] CHARACTER SET | CHARSET \[ = ] default\_charset ] \[ \[ DEFAULT ] COLLATE \[ = ] default\_collation ]** > > 修改表的默认字符集和默认字符序为指定的值。修改不会影响表中当前已经存在的列。 > > * **CONVERT TO CHARACTER SET | CHARSET charset \[ COLLATE collation ]** > > 修改表的默认字符集和默认字符序为指定的值,同时将表中的所有字符类型的字段的字符集和字符序设置为指定的值,并将字段里的数据转换为新字符集编码。 > > * **REDISANYVALUE** > > 仅有语法支持,不实现功能。 * 其中列相关的操作column\_clause可以是以下子句之一: ``` ADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] [ COMMENT {=| } 'text' ] [ FIRST | AFTER column_name ] | ADD [ IF NOT EXISTS ] column_name data_type [ compress_mode ] [, ...] | MODIFY column_name data_type | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL | MODIFY [ COLUMN ] column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [{[ COLLATE collation ] | [ column_constraint ]} [ ... ] ] [FIRST | AFTER column_name] | CHANGE [ COLUMN ] old_column_name new_column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [{[ COLLATE collation ] | [ column_constraint ]} [ ... ] ] [FIRST | AFTER column_name] | DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ] | ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ] | ALTER [ COLUMN ] column_name { SET DEFAULT expression | DROP DEFAULT } | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS [PERCENT] integer | ADD STATISTICS (( column_1_name, column_2_name [, ...] )) | DELETE STATISTICS (( column_1_name, column_2_name [, ...] )) | ALTER [ COLUMN ] column_name SET ( {attribute_option = value} [, ... ] ) | ALTER [ COLUMN ] column_name RESET ( attribute_option [, ... ] ) | ALTER [ COLUMN ] column_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN } | ALTER [ COLUMN ] column_name ADD GENERATED generated_when AS IDENTITY [ ( seq_options) ] | ALTER [ COLUMN ] column_name alter_identity_column_options [ ... ] | ALTER [ COLUMN ] column_name DROP IDENTITY [ IF EXISTS ] ``` \[!NOTE]说明 > * **ADD \[ COLUMN ] \[ IF NOT EXISTS ] column\_name data\_type \[ compress\_mode ] \[ COLLATE collation ] \[ column\_constraint \[ ... ] ] \[ FIRST | AFTER column\_name ]** > > 向表中增加一个新的字段。用ADD COLUMN增加一个字段,所有表中现有行都初始化为该字段的缺省值(如果没有声明DEFAULT子句,值为NULL)。其中FIRST | AFTER column\_name表示新增字段到某个位置。如果指定了IF NOT EXISTS子句,新增字段与表中已有字段重复时将不会抛出错误。 > > * **ADD ( \[ IF NOT EXISTS ] { column\_name data\_type \[ compress\_mode ] } \[, ...] )** > > 向表中增加多列。 > > * **MODIFY ( { column\_name data\_type } \[, ...] )** > > 修改表已存在字段的数据类型。 > > 在 A兼容模式下,如果表数据不为空,则不允许修改`numeric`类型的`scale`为更小。 > > 在 A兼容模式下,设置GUC参数`set behavior_compat_options = 'float_as_numeric';`后,如果表中数据不为空,则不允许修改`float(p)`的精度`precision`为更小值,不允许修改`float(p)`为其它类型。 > > * **MODIFY column\_name \[ CONSTRAINT constraint\_name ] NOT NULL \[ ENABLE ] \[, ...]** > > 为表的某列添加NOT NULL约束,默认启用约束。加上ENABLE也表示默认启用约束。目前暂不支持禁用约束选项。 > > * **MODIFY column\_name \[ CONSTRAINT constraint\_name ] NULL \[, ...]** > > 为表的某列移除NOT NULL约束。 > > * **MODIFY \[ COLUMN ] column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[{\[ COLLATE collation ] | \[ column\_constraint ]} \[ ... ] ] \[FIRST | AFTER column\_name]** > > 修改表已存在字段的定义,将用新定义替换字段原定义,原字段上的索引、独立对象约束(例如:主键、唯一键、CHECK约束等)不会被删除。\[FIRST | AFTER column\_name]语法表示修改字段定义的同时修改字段在表中的位置。 > > 此语法只能在参数sql\_compatibility='B'时使用。不支持列存表,不支持外表,不支持修改加密字段,不支持修改分区键字段的数据类型和排序规则,不支持修改规则引用的字段的数据类型和排序规则,不支持修改物化视图引用的字段的数据类型和排序规则。 > > 被修改数据类型或排序规则的字段如果被一个生成列引用,这个生成列的数据将会重新生成。 > > 被修改字段若被一些对象依赖(比如:索引、独立对象约束、视图、触发器、行级访问控制策略等),修改字段过程中将会重建这些对象。若被修改后字段定义 > 违反此类对象的约束,修改操作会失败,比如:修改作为视图结果列的字段的数据类型。请修改字段前评估这类影响。 > > 被修改字段若被一些对象调用(比如:自定义函数、存储过程等),修改字段不会处理这些对象。修改字段完毕后,这些对象有可能出现不可用的情况,请修改字段前评估这类影响。 > > 修改字段的字符集或字符序会将字段中的数据转换为新的字符集进行编码。 > > 此子句与上一子句中“MODIFY column\_name data\_type”部分语法相同,语义功能不同,当GUC参数b\_format\_behavior\_compat\_options含有'enable\_modify\_column'选项时,将按照此子句功能处理。 > > 不支持列的identity属性添加/修改和删除。 > > * **CHANGE \[ COLUMN ] old\_column\_name new\_column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[{\[ COLLATE collation ] | \[ column\_constraint ]} \[ ... ] ] \[FIRST | AFTER column\_name]** > > 修改表已存在字段的名称和定义,字段新名称不能是已有字段的名称,将用新名称和定义替换字段原名称和定义原字段上的索引、独立对象约束(例如:主键、唯一键、CHECK约束)等不会被删除。\[FIRST | AFTER column\_name]语法表示修改字段名称和定义的同时修改字段在表中的位置。 > > 此语法只能在参数sql\_compatibility='B'时使用。不支持列存表,不支持外表。不支持修改加密字段,不支持修改分区键字段的数据类型和排序规则,不支持修改规则引用的字段的数据类型和排序规则,不支持修改物化视图引用的字段的数据类型和排序规则 > > 被修改数据类型或排序规则的字段如果被一个生成列引用,这个生成列的数据将会重新生成。 > > 被修改字段若被一些对象依赖(比如:索引、独立对象约束、视图、触发器、行级访问控制策略等),修改字段过程中将会重建这些对象。若被修改后字段定义违反此类对象的约束,修改操作会失败,比如:修改作为视图结果列的字段的数据类型。请修改字段前评估这类影响。 > > 被修改字段若被一些对象调用(比如:自定义函数、存储过程等),修改字段不会处理这些对象。修改字段名称后,这些对象有可能出现不可用的情况,请修改字段前评估这类影响。 > > 修改字段的字符集或字符序会将字段中的数据转换为新的字符集进行编码。 > > 不支持列的identity属性添加/修改和删除。 > > * **DROP \[ COLUMN ] \[ IF EXISTS ] column\_name \[ RESTRICT | CASCADE ]** > > 从表中删除一个字段,和这个字段相关的索引和表约束也会被自动删除。如果任何表之外的对象依赖于这个字段,必须声明CASCADE ,比如视图。 > > DROP COLUMN命令并不是物理上把字段删除,而只是简单地把它标记为对SQL操作不可见。随后对该表的插入和更新将在该字段存储一个NULL。因此,删除一个字段是很快的,但是它不会立即释放表在磁盘上的空间,因为被删除了的字段占据的空间还没有回收。这些空间将在执行VACUUM时而得到回收。 > > * **ALTER \[ COLUMN ] column\_name \[ SET DATA ] TYPE data\_type \[ COLLATE collation ] \[ USING expression ]** > > 改变表字段的数据类型。该字段涉及的索引和简单的表约束将被自动地转换为使用新的字段类型,方法是重新分析最初提供的表达式。 > > ALTER TYPE要求重写整个表的特性有时候是一个优点,因为重写的过程消除了表中没用的空间。比如,要想立刻回收被一个已经删除的字段占据的空间,最快的方法是 > > ``` > ALTER TABLE table ALTER COLUMN anycol TYPE anytype; > ``` > > 这里的anycol是任何在表中还存在的字段,而anytype是和该字段的原类型一样的类型。这样的结果是在表上没有任何可见的语意的变化,但是这个命令强制重写,这样就删除了不再使用的数据。 > > * **ALTER \[ COLUMN ] column\_name { SET DEFAULT expression | DROP DEFAULT }** > > 为一个字段设置或者删除缺省值。请注意缺省值只应用于随后的INSERT命令,它们不会修改表中已经存在的行。也可以为视图创建缺省,这个时候它们是在视图的ON INSERT规则应用之前插入到INSERT句中的。 > > * **ALTER \[ COLUMN ] column\_name { SET | DROP } NOT NULL** > > 修改一个字段是否允许NULL值或者拒绝NULL值。如果表在字段中包含非NULL,则只能使用SET NOT NULL。 > > * **ALTER \[ COLUMN ] column\_name SET STATISTICS \[PERCENT] integer** > > 为随后的ANALYZE操作设置针对每个字段的统计收集目标。目标的范围可以在0到10000之内设置。设置为-1时表示重新恢复到使用系统缺省的统计目标。 > > * **{ADD | DELETE} STATISTICS ((column\_1\_name, column\_2\_name \[, ...]))** > > 用于添加和删除多列统计信息声明(不实际进行多列统计信息收集),以便在后续进行全表或全库analyze时进行多列统计信息收集。如果关闭GUC参数enable\_functional\_dependency,每组多列统计信息最多支持32列;如果开启GUC参数enable\_functional\_dependency,每组多列统计信息最多支持4列。不支持添加/删除多列统计信息声明的表:系统表、外表。 > > * **ALTER \[ COLUMN ] column\_name SET ( {attribute\_option = value} \[, ... ] )** > **ALTER \[ COLUMN ] column\_name RESET ( attribute\_option \[, ... ] )** > > 设置/重置属性选项。 > > 目前,属性选项只定义了n\_distinct和n\_distinct\_inherited。n\_distinct影响表本身的统计值,而n\_distinct\_inherited影响表及其继承子表的统计。目前,只支持SET/RESET n\_distinct参数,禁止SET/RESET n\_distinct\_inherited参数。 > > * **ALTER \[ COLUMN ] column\_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }** > > 为一个字段设置存储模式。这个设置控制这个字段是内联保存还是保存在一个附属的表里,以及数据是否要压缩。仅支持对行存表的设置;对列存表没有意义,执行时报错。SET STORAGE本身并不改变表上的任何东西,只是设置将来的表操作时,建议使用的策略。 > > * **ALTER \[ COLUMN ] column\_name ADD GENERATED generated\_when AS IDENTITY \[ ( seq\_options) ]** > > 添加identity属性,同时可以指定identity列的起始值,步长,最大值,最小值等属性。 > > * **ALTER \[ COLUMN ] column\_name alter\_identity\_column\_options \[ ... ]** > > 修改identity列的属性,序列的起始值,最大值,最小值,步长等。 > > * **ALTER \[ COLUMN ] column\_name DROP IDENTITY \[ IF EXISTS ]** > > 删除某列的identity属性,如果列没有identity属性则报错,如果声明了`IF EXISTS`语法则会跳过;成功删除后,identity列所拥有的序列也会被删除,但是列的not null约束不变。 * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED [ ALWAYS | BY DEFAULT ] AS IDENTITY [ ( seq_options ) ] | GENERATED ALWAYS AS ( generation_expr ) [STORED] | ON UPDATE update_expr | { UNIQUE [KEY] index_parameters [ ON filegroup ] | PRIMARY KEY index_parameters [ ON filegroup ] } [ { ENABLE | DISABLE } [ VALIDATE | NOVALIDATE ] | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] [ ENABLE ] } | { ENABLE | DISABLE } [ VALIDATE | NOVALIDATE ] Constraint constraint_name } | AUTO_INCREMENT | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] | [ COMMENT 'text' ] ``` * 其中列的压缩可选项compress\_mode为: ``` [ DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS ] ``` * 其中根据已有唯一索引为表增加主键约束或唯一约束table\_constraint\_using\_index为: ``` [ CONSTRAINT constraint_name ] { UNIQUE | PRIMARY KEY } USING INDEX index_name [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ idx_name ] [ USING method ] ( { { column_name [ ( length ) ] | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PARTIAL CLUSTER KEY ( column_name [, ... ] } FOREIGN KEY [ idx_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT 'text' ] ``` * 其中索引参数index\_parameters为: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * 其中identity属性参数generated\_when为: ```EBNF ALWAYS | BY DEFAULT ``` * 其中identity属性序列参数seq\_options为: ```EBNF seq_option | OWNED BY name | RESTART [ WITH ] NumericOnly ; seq_option: { MAXVALUE | MINVALUE | START WITH | START | INCREMENT [ BY ] | CACHE } NumericOnly | { NOMAXVALUE | MINVALUE | NO MAXVALUE | NO MINVALUE | NOCYCLE | [ NO ] CYCLE } ``` * 其中修改identity属性参数alter\_identity\_column\_options为: ```EBNF RESTART [ WITH ] NumericOnly | SET GENERATED generated_when | SET seq_option ``` * 重命名表。对名称的修改不会影响所存储的数据。 ``` ALTER TABLE [ IF EXISTS ] [schema_name.]table_name RENAME TO [new_schema_name.]new_table_name; ``` * 重命名表中指定的列。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME [ COLUMN ] column_name TO new_column_name; ``` * 重命名表的约束。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name ) } RENAME CONSTRAINT constraint_name TO new_constraint_name; ``` * 设置表的所属模式。 ``` ALTER TABLE [ IF EXISTS ] table_name SET SCHEMA new_schema; ``` > \[!NOTE]说明 > > * 这种形式把表移动到另外一个模式。相关的索引、约束都跟着移动。目前序列不支持改变schema。 若该表拥有序列,需要将序列删除,重建,或者取消拥有关系, 才能将表schema更改成功。 > * 要修改一个表的模式,用户必须在新模式上拥有CREATE权限。要把该表添加为一个父表的新子表,用户必须同时又是父表的所有者。要修改所有者,用户还必须是新的所有角色的直接或间接成员,并且该成员必须在此表的模式上有CREATE权限。这些限制规定了该用户不能做出了重建和删除表之外的事情。不过,系统管理员可以以任何方式修改任意表的所有权限。 > * 除了RENAME和SET SCHEMA之外所有动作都可以捆绑在一个经过多次修改的列表中并行使用。比如,可以在一个命令里增加几个字段或修改几个字段的类型。对于大表,此种操作带来的效率提升更明显,原因在于只需要对该大表做一次处理。 > * 增加一个CHECK或NOT NULL约束将会扫描该表,以保证现有的行符合约束要求。 > * 用一个非空缺省值增加一个字段或者改变一个字段的现有类型会重写整个表。对于大表来说,这个操作可能会花很长时间,并且它还临时需要两倍的磁盘空间。 * 添加多个列。 ``` ALTER TABLE [ IF EXISTS ] table_name ADD ( { [ IF NOT EXISTS ] column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ]} [, ...] ); ``` * 更新多个列。 ``` ALTER TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type [ CHARACTER SET | CHARSET charset ] [{[ COLLATE collation ] | [ column_constraint ]} [ ... ] ] [FIRST | AFTER column_name] | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ``` ## 参数说明 * **CONCURRENTLY** 使用在线DDL模式执行ALTER操作,只支持传统主备场景Astore、段页式的普通表、分区表进行修改列数据类型、修改行存压缩属性、添加列的约束(非空约束、范围约束)。 * **IF EXISTS** 如果不存在相同名称的表,不会抛出一个错误,而会发出一个通知,告知表不存在。 * **table\_name \[\*] | ONLY table\_name | ONLY ( table\_name )** table\_name是需要修改的表名。 若声明了ONLY选项,则只有那个表被更改。若未声明ONLY,该表及其所有子表都将会被更改。另外,可以在表名称后面显示地增加\*选项来指定包括子表,即表示所有后代表都被扫描,这是默认行为。 * **constraint\_name** ``` - 在DROP CONSTRAINT操作中表示要删除的现有约束的名称。 ``` * 在ADD CONSTRAINT操作中表示新增的约束名称。 > \[!TIP]须知 > > 对于新增约束,在B模式数据库下(即sql\_compatibility = 'B')constraint\_name为可选项,在其他模式数据库下,必须加上constraint\_name。 * **index\_name** 索引名称。 * **idx\_name** 索引名。 > \[!TIP]须知 > > 在ADD CONSTRAINT操作中: > > * index\_name仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 对于外键约束,constraint\_name和index\_name同时指定时,索引名为constraint\_name。 > * 对于唯一键约束,constraint\_name和index\_name同时指定时,索引名以index\_name。 * **USING method** 指定创建索引的方法。 取值范围参考[参数说明](create_index.md)中的USING method。 > \[!TIP]须知 > > 在ADD CONSTRAINT操作中: > > * USING method仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 在B模式下,未指定USING method时,对于Astore的存储方式,默认索引方法为btree;对于Ustore的存储方式,默认索引方法为ubtree。 * **ASC | DESC** ASC表示指定按升序排序(默认)。DESC指定按降序排序。 > \[!TIP]须知 > > 在ADD CONSTRAINT中,ASC|DESC只在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库不支持。 * **expression** 创建一个基于该表的一个或多个字段的表达式索引约束,必须写在圆括弧中。 > \[!TIP]须知 > > 表达式索引只在B模式数据库下支持(即sql\_compatibility = 'B'),其他模式数据库不支持。 * **storage\_parameter** 表的存储参数的名称。 创建索引新增一个选项: * parallel\_workers(int类型) 取值范围:\[0,32],0表示关闭并发。 表示创建索引时起的bgworker线程数量,例如2就表示将会起2个bgworker线程并发创建索引。 如果未设置,启动bgworker线程数量与表大小相关,一般不超过4个线程。 * hasuids(bool类型) 默认值:off 参数开启:更新表元组时,为元组分配表级唯一标识id。 * **new\_owner** 表新拥有者的名称。 * **new\_tablespace** 表所属新的表空间名称。 * **IF NOT EXISTS** 如果指定了IF NOT EXISTS子句,新增字段与表中已有字段重复时将不会抛出错误。 * **column\_name**,**column\_1\_name, column\_2\_name** 现存的或新字段的名称。 * **data\_type** 新字段的类型,或者现存字段的新类型。 * **compress\_mode** 表字段的压缩可选项。该子句指定该字段优先使用的压缩算法。行存表不支持压缩。 * **charset** 只在B模式数据库下(即sql\_compatibility = 'B')支持该语法,其他模式数据库不支持。指定表字段的字符集,单独指定时会将字段的字符序设置为指定的字符集的默认字符序。 * **collation** 字段排序规则(字符序)名称。可选字段COLLATE指定了新字段的排序规则,如果省略,排序规则为新字段的默认类型。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 对于B模式数据库下(即sql\_compatibility = 'B')还支持utf8mb4\_bin、utf8mb4\_general\_ci、utf8mb4\_unicode\_ci、binary字符序,部分说明见表字段的字符集说明(参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](create_table_1.md#table8163190152))。 > \[!NOTE]说明 > > * 仅字符类型支持指定字符集,指定为binary字符集或字符序实际是将字符类型转化为对应的二进制类型,若类型映射不存在则报错。当前仅有TEXT类型转化为BLOB的映射。 > * 除binary字符集和字符序外,当前仅支持指定与数据库编码相同的字符集。 > * 未显式指定字段字符集或字符序时,若指定了表的默认字符集或字符序,字段字符集和字符序将从表上继承。若表的默认字符集或字符序不存在,当b\_format\_behavior\_compat\_options = 'default\_collation'时,字段的字符集和字符序将继承当前数据库的字符集及其对应的默认字符序。 > * 当修改的字符集或字符序对应的字符集与当前字段字符集不同时,会将字段中的数据转换为指定的字符集进行编码。 * **USING expression** USING子句声明如何从旧的字段值里计算新的字段值;如果省略,缺省从旧类型向新类型的赋值转换。如果从旧数据类型到新类型没有隐含或者赋值的转换,则必须提供一个USING子句。 > \[!NOTE]说明 > > ALTER TYPE的USING选项实际上可以声明涉及该行旧值的任何表达式,即它可以引用除了正在被转换的字段之外其他的字段。这样,就可以用ALTER TYPE语法做非常普遍性的转换。因为这个灵活性,USING表达式并没有作用于该字段的缺省值(如果有的话),结果可能不是缺省表达式要求的常量表达式。这就意味着如果从旧类型到新类型没有隐含或者赋值转换的话,即使存在USING子句,ALTER TYPE也可能无法把缺省值转换成新的类型。在这种情况下,应该用DROP DEFAULT先删除缺省,执行ALTER TYPE,然后使用SET DEFAULT增加一个合适的新缺省值。类似的考虑也适用于涉及该字段的索引和约束。 * **NOT NULL | NULL** 设置列是否允许空值。 * **integer** 带符号的整数常值。当使用PERCENT时表示按照表数据的百分比收集统计信息,integer的取值范围为0-100。 * **attribute\_option** 属性选项。 * **PLAIN | EXTERNAL | EXTENDED | MAIN** 字段存储模式。 * PLAIN必需用于定长的数值(比如integer)并且是内联的、不压缩的。 * MAIN用于内联、可压缩的数据。 * EXTERNAL用于外部保存、不压缩的数据。使用EXTERNAL将令在text和bytea字段上的子字符串操作更快,但付出的代价是增加了存储空间。 * EXTENDED用于外部的压缩数据,EXTENDED是大多数支持非PLAIN存储的数据的缺省。 * **CHECK ( expression )** 每次将要插入的新行或者将要被更新的行必须使表达式结果为真才能成功,否则会抛出一个异常并且不会修改数据库。 声明为字段约束的检查约束应该只引用该字段的数值,而在表约束里出现的表达式可以引用多个字段。 目前,CHECK表达式不能包含子查询也不能引用除当前行字段之外的变量。 * **DEFAULT default\_expr** 给字段指定缺省值。 缺省表达式的数据类型必须和字段类型匹配。 缺省表达式将被用于任何未声明该字段数值的插入操作。如果没有指定缺省值则缺省值为NULL 。 * **GENERATED \[ ALWAYS | BY DEFAULT ] AS IDENTITY \[ ( seq\_options ) ]** 该语句创建identity列,用于生成自增/自减的序列。 若在插入时不指定此列的值(或者指定为DEFAULT),则会默认生成。 当列定义为`GANERATED ALWAYS`时,若想插入用户值需要使用`OVERRIDING SYSTEM VALUE`子句,否则会报错,对于UPDATE只能更新为`DEFAULT`; 当列定义为`GANERATED BY DEFAULT`时,用户提供的值会优先于默认值。 `seq_options`可以用于指定序列的选项。 > \[!NOTE]说明 > > * 该列的数据类型仅为整型,NUMERIC类型,该列隐式包含`NOT NULL`约束。 > * 无法同时定义default,serial,auto\_increment,生成列,NULL约束。 > * 序列生成非事务操作,当列/表约束检查失败,触发器失败时该列已生成的值不会回滚。 > * 用户自定义的值不会影响该列的下一个值的生成, > * 可以定义多列,但同一列不能重复定义。 > * 不支持分区表。 * **GENERATED ALWAYS AS ( generation\_expr ) \[STORED]** 该子句将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,STORED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > > * STORED关键字可省略,与不省略STORED语义相同。 > * 生成表达式不能以任何方式引用当前行以外的其他数据。生成表达式不能引用其他生成列,不能引用系统列。生成表达式不能返回结果集,不能使用子查询,不能使用聚集函数,不能使用窗口函数。生成表达式调用的函数只能是不可变(IMMUTABLE)函数。 > * 不能为生成列指定默认值。 > * 生成列不能作为分区键的一部分。 > * 生成列不能和ON UPDATE约束字句的CASCADE,SET NULL,SET DEFAULT动作同时指定。生成列不能和ON DELETE约束字句的SET NULL,SET DEFAULT动作同时指定。 > * 修改和删除生成列的方法和普通列相同。删除生成列依赖的普通列,生成列被自动删除。不能改变生成列所依赖的列的类型。 > * 生成列不能被直接写入。在INSERT或UPDATE命令中, 不能为生成列指定值, 但是可以指定关键字DEFAULT。 > * 生成列的权限控制和普通列一样。 > * 列存表、内存表MOT不支持生成列。外表中仅postgres\_fdw支持生成列。 * **AUTO\_INCREMENT** 指定列为自动增长列。 详见:[AUTO\_INCREMENT](create_table.md)。 * **UNIQUE \[KEY] index\_parameters** **UNIQUE ( column\_name \[ ( length ) ] \[, ... ] ) index\_parameters** UNIQUE约束表示表里的一个或多个字段的组合必须在全表范围内唯一。 UNIQUE KEY只能在sql\_compatibility='B'时使用,与UNIQUE语义相同。 column\_name(length)是前缀键,详见:[前缀键说明](create_index_1.md#前缀键说明)。 * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** 主键约束表明表中的一个或者一些字段只能包含唯一(不重复)的非NULL值。 * **REFERENCES reftable \[ ( refcolum ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (column constraint)** **FOREIGN KEY ( column\_name \[, ... ] ) REFERENCES reftable \[ ( refcolumn \[, ... ] ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (table constraint)** 外键约束要求新表中一列或多列构成的组应该只包含、匹配被参考表中被参考字段值。若省略refcolum,则将使用reftable的主键。被参考列应该是被参考表中的唯一字段或主键。外键约束不能被定义在临时表和永久表之间。 参考字段与被参考字段之间存在三种类型匹配,分别是: * MATCH FULL:不允许一个多字段外键的字段为NULL,除非全部外键字段都是NULL。 * MATCH SIMPLE(缺省):允许任意外键字段为NULL。 * MATCH PARTIAL:目前暂不支持。 另外,当被参考表中的数据发生改变时,某些操作也会在新表对应字段的数据上执行。ON DELETE子句声明当被参考表中的被参考行被删除时要执行的操作。ON UPDATE子句声明当被参考表中的被参考字段数据更新时要执行的操作。对于ON DELETE子句、ON UPDATE子句的可能动作: * NO ACTION(缺省):删除或更新时,创建一个表明违反外键约束的错误。若约束可推迟,且若仍存在任何引用行,那这个错误将会在检查约束的时候产生。 * RESTRICT:删除或更新时,创建一个表明违反外键约束的错误。与NO ACTION相同,只是动作不可推迟。 * CASCADE:删除新表中任何引用了被删除行的行,或更新新表中引用行的字段值为被参考字段的新值。 * SET NULL:设置引用字段为NULL。 * SET DEFAULT:设置引用字段为它们的缺省值。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 * **DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE** 设置该约束是否可推迟。 * DEFERRABLE:可以推迟到事务结尾使用SET CONSTRAINTS命令检查。 * NOT DEFERRABLE:在每条命令之后马上检查。 * INITIALLY IMMEDIATE:那么每条语句之后就立即检查它。 * INITIALLY DEFERRED:只有在事务结尾才检查它。 > \[!NOTE]说明Ustore表不支持新增 DEFERRABLE 以及 INITIALLY DEFERRED 约束。 * **PARTIAL CLUSTER KEY** 局部聚簇存储,列存表导入数据时按照指定的列(单列或多列),进行局部排序。 * **WITH ( {storage\_parameter = value} \[, ... ] )** 为表或索引指定一个可选的存储参数,详见[CREATE TABLE](create_table.md)语法相关字段的介绍。 > \[!NOTE]说明 > > * 行存表支持修改行存压缩参数,包括COMPRESSTYPE、COMPRESS\_LEVEL、COMPRESS\_CHUNK\_SIZE、COMPRESS\_PREALLOC\_CHUNKS、COMPRESS\_BYTE\_CONVERT、COMPRESS\_DIFF\_CONVERT,修改会对表做重建,修改后对原有数据、修改对已有数据、变更数据、新增数据同时生效。(仅支持Astore和Ustore下的普通表和分区表) > * 修改行存压缩参数时,修改后的行存压缩参数需要满足建表时各行存压缩参数的数据范围和参数间的约束。 > * 分区表不支持修改分区级别的行存压缩参数,只能修改整个表的行存压缩属性,修改对所有分区生效。 > * 修改行存压缩参数时会重写整个表,期间对表加八级锁。 > * 修改行存压缩参数时会重建表, 如果表的数据库较大,该过程可能花费较长时间 > * 重建表期间openGauss会先生成新的数据文件,再删除旧的数据文件,需要事先保证有足够的空闲物理空间。 * **tablespace\_name** 索引所在表空间的名称。 * **COMPRESS|NOCOMPRESS** * NOCOMPRESS:如果指定关键字NOCOMPRESS则不会修改表的现有压缩特性。 * COMPRESS:如果指定COMPRESS关键字,则对该表进行批量插入元组时触发该特性。行存表不支持压缩。 * **new\_table\_name** 修改后新的表名称。 * **new\_column\_name** 表中指定列修改后新的列名称。 * **new\_constraint\_name** 修改后表约束的新名称。 * **new\_schema** 修改后新的模式名称。 * **CASCADE** 级联删除依赖于被依赖字段或者约束的对象(比如引用该字段的视图)。 * **RESTRICT** 如果字段或者约束还有任何依赖的对象,则拒绝删除该字段。这是缺省行为。 - **FIRST** 新增列或修改列到第一位。 - **AFTER** **column\_name** 新增列或修改列到column\_name之后。 > \[!NOTE]说明 > > * 列存表不支持FIRST | AFTER column\_name。 > * 仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库不支持。 > * 加密列不支持FIRST | AFTER column\_name。 > * 有规则依赖的表不支持改变表列的位置(包括新增和修改导致列位置的变化)。 > * 外表不支持FIRST | AFTER column\_name。 > * SET类型的字段不支持修改到指定位置。 * **schema\_name** 表所在的模式名称。 * **VISIBLE | INVISIBLE** 指定索引是否可见,如果没有声明则默认为VISIBLE。 * **\[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset** 仅在sql\_compatibility='B'时支持该语法。修改表的默认字符集,单独指定时会将表的默认字符序设置为指定的字符集的默认字符序。 * **\[DEFAULT] COLLATE \[ = ] default\_collation** 仅在sql\_compatibility='B'时支持该语法。修改表的默认字符序,单独指定时会将表的默认字符集设置为指定的字符序对应的字符集。字符序参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](create_table_1.md#table8163190152)。 > \[!NOTE]说明 > 未显式指定表的字符集或字符序时,若指定了模式的默认字符集或字符序,表字符集和字符序将从模式上继承。若模式的默认字符集或字符序不存在,当b\_format\_behavior\_compat\_options = 'default\_collation'时,表的字符集和字符序将继承当前数据库的字符集及其对应的默认字符序。 ## 示例 请参考CREATE TABLE的[示例](create_table.md##示例)。 * add column first/after示例 ```sql -- 创建B模式数据库。 openGauss=# create database test_first_after dbcompatibility 'b'; openGauss=# \c test_first_after -- 创建表t1并插入数据。 openGauss=# drop table if exists t1 cascade; openGauss=# create table t1(f1 int, f2 varchar(20), f3 timestamp, f4 bit(8), f5 bool); openGauss=# insert into t1 values(1, 'a', '2022-11-08 19:56:10.158564', x'41', true), (2, 'b', '2022-11-09 19:56:10.158564', x'42', false); -- 指定位置新增字段 openGauss=# alter table t1 add f6 clob first; openGauss=# alter table t1 add f7 blob after f2; openGauss=# alter table t1 add f8 int, add f9 text first, add f10 float after f3; -- 查询t1表结构 openGauss=# \d+ t1 -- 查询t1表数据 openGauss=# select * from t1; -- 修改字段到指定位置 openGauss=# alter table t1 modify f3 timestamp first; openGauss=# alter table t1 modify f1 int after f5; -- 查询t1表结构 openGauss=# \d+ t1 -- 查询t1表数据 openGauss=# select * from t1; -- 修改t1表的默认字符集为utf8mb4,默认字符序为utf8mb4_bin openGauss=# alter table t1 charset utf8mb4 collate utf8mb4_bin; -- 将t1表中字符类型字段的数据转化为utf8mb4编码,并设置表和字段的字符序为utf8mb4_bin openGauss=# alter table t1 convert to charset utf8mb4 collate utf8mb4_bin; -- 为t1表新增字段并设置字段的字符集为utf8mb4,字符序为utf8mb4_bin openGauss=# alter table t1 add t10 varchar(20) charset utf8mb4 collate utf8mb4_bin; -- 修改t1表的t10字段的字符集为utf8mb4,字符序为utf8mb4_unicode_ci openGauss=# alter table t1 modify t10 varchar(20) charset utf8mb4 collate utf8mb4_unicode_ci; -- 创建INVISIBLE唯一索引 openGauss=# alter table t1 add constraint uniq_a unique (f1) invisible; -- 修改索引为VISIBLE openGauss=# alter table t1 alter index uniq_a visible; ``` * 添加/修改/删除identity列 ```sql openGauss=# create table t1 (a int generated always as identity, b int); NOTICE: CREATE TABLE will create implicit sequence "t1_a_seq" for serial column "t1.a" CREATE TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+---------------------------------------+---------+--------------+------------- a | integer | not null generated always as identity | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table t1 add column c numeric(20, 0) generated by default as identity; NOTICE: ALTER TABLE will create implicit sequence "t1_c_seq" for serial column "t1.c" ALTER TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------------+-------------------------------------------+---------+--------------+------------- a | integer | not null generated always as identity | plain | | b | integer | | plain | | c | numeric(20,0) | not null generated by default as identity | main | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table t1 alter column c set generated always set start with 10; ALTER TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------------+---------------------------------------+---------+--------------+------------- a | integer | not null generated always as identity | plain | | b | integer | | plain | | c | numeric(20,0) | not null generated always as identity | main | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table t1 alter column b drop identity; ERROR: column "b" of relation "t1" is not an identity column openGauss=# alter table t1 alter column b drop identity if exists; NOTICE: column "b" of relation "t1" is not an identity column, skipping ALTER TABLE openGauss=# alter table t1 alter column c drop identity; ALTER TABLE openGauss=# alter table t1 alter column c add generated by default as identity(start with 10 increment 20); NOTICE: ALTER TABLE will create implicit sequence "t1_c_seq1" for serial column "t1.c" ALTER TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------------+-------------------------------------------+---------+--------------+------------- a | integer | not null generated always as identity | plain | | b | integer | | plain | | c | numeric(20,0) | not null generated by default as identity | main | | Has OIDs: no Options: orientation=row, compression=no ``` ## 相关链接 [CREATE TABLE](create_table.md),[DROP TABLE](drop_table.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-ALTER-TABLE.md --- # ALTER TABLE ## 功能描述 修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 * 当一条语句下有多条子命令时,drop index和rename index会优先其他子命令执行,这两种命令的优先级一致。 * 生成列语法支持忽略GENERATED ALWAYS。 ## 语法格式 * 修改表的定义。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | (ONLY) table_name | (ONLY) ( table_name ) } action [, ... ]; ``` 其中具体表操作action可以是以下子句之一: ``` column_clause | ADD [ COLUMN ] ( { column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ … ] ] } [, …] ) | {DISABLE | ENABLE} KEYS | DROP INDEX index_name [ RESTRICT | CASCADE ] | DROP PRIMARY KEY [ RESTRICT | CASCADE ] | DROP FOREIGN KEY foreign_key_name [ RESTRICT | CASCADE ] | RENAME INDEX index_name to new_index_name | ADD table_indexclause | MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP | alter_table_option [[,] ...] ``` 其中具体表选项alter\_table\_option为: ``` | AUTOEXTEND_SIZE [=] value | AUTO_INCREMENT [=] value | AVG_ROW_LENGTH [=] value | [DEFAULT] { CHARSET | CHARACTER SET } [=] charset_name | CHECKSUM [=] value | [DEFAULT] COLLATE [=] collation_name | COMMENT [=] 'text' | CONNECTION [=] 'connect_string' | {DATA | INDEX} DIRECTORY [=] 'absolute path to directory' | DELAY_KEY_WRITE [=] value | ENCRYPTION [=] 'encryption_string' | ENGINE_ATTRIBUTE [=] 'string' | INSERT_METHOD [=] { NO | FIRST | LAST } | KEY_BLOCK_SIZE [=] value | MAX_ROWS [=] value | MIN_ROWS [=] value | PACK_KEYS [=] value | PASSWORD [=] 'password' | ROW_FORMAT [=] row_format_name | START TRANSACTION | SECONDARY_ENGINE_ATTRIBUTE [=] 'string' | STATS_AUTO_RECALC [=] value | STATS_PERSISTENT [=] value | STATS_SAMPLE_PAGES [=] value | UNION [=] (tbl_name[,tbl_name]...) | TABLESPACE tablespace_name [STORAGE DISK] | [TABLESPACE tablespace_name] STORAGE MEMORY ``` 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | [GENERATED ALWAYS] AS ( generation_expr ) [STORED] | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE [KEY] index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` ```` - 向表中增加多列。BINARY关键字将设置列的字符序为该列字符集对应的`_bin`字符序。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。 ASCII关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 ``` ALTER TABLE ADD [ COLUMN ] ( { column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ … ] ] } [, …] ) ``` ```` * 对一个表进行重建。 ``` ALTER TABLE table_name FORCE; ``` * 重命名表。对名称的修改不会影响所存储的数据。 ``` ALTER TABLE [ IF EXISTS ] table_name RENAME [ TO | AS ] new_table_name; ``` * 对表timestamp列添加ON UPDATE属性。 ```sql ALTER TABLE table_name MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP; ``` * 对表timestamp列删除ON UPDATE属性。 ```sql ALTER TABLE table_name MODIFY column_name column_type; ``` * **ADD table\_indexclause** 在表上新增一个索引 ``` {[FULLTEXT] INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option]... ``` 其中参数index\_type为: ``` USING {BTREE | HASH | GIN | GIST | PSORT | UBTREE} ``` 其中参数key\_part为: ``` {col_name[(length)] | (expr)} [ASC | DESC] ``` 其中参数index\_option为: ``` index_option:{ COMMENT 'string' | index_type | [ VISIBLE | INVISIBLE ] | [WITH PARSER NGRAM] } ``` COMMENT、index\_type、\[ VISIBLE | INVISIBLE ] 的顺序和数量任意,但相同字段仅最后一个值生效。WITH PARSER NGRAM 为FULLTEXT INDEX指定的ngram解析器,前提是索引必须指定关键字FULLTEXT,FULLTEXT 默认 WITH PARSER NGRAM。 ## 参数说明 * **{DISABLE | ENABLE} KEYS** 禁用和启用一个表的所有非唯一索引。 * **DROP INDEX index\_name \[ RESTRICT | CASCADE ]** 删除一个表的索引。 * **DROP PRIMARY KEY \[ RESTRICT | CASCADE ]** 删除一个表的主键。 * **DROP FOREIGN KEY foreign\_key\_name \[ RESTRICT | CASCADE ]** 删除一个表的外键。 * **RENAME INDEX index\_name to new\_index\_name** 重命名一个表的索引。 * **AUTOEXTEND\_SIZE \[=] value** 用于指定在表空间变满时扩展表空间大小;目前该特性仅有语法支持,不实现功能。参数的取值范围包括非负整数,小数,标识符,非负整数+标识符,小数+标识符。 * **AVG\_ROW\_LENGTH \[=] value** 用于指定表的平均行长度;目前该特性仅有语法支持,不实现功能。参数的取值范围包括非负整数,小数。 * **CHECKSUM \[=] value** 用于指定是否维护所有行的实时校验和;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **CONNECTION \[=] 'connect\_string'** 用于指定联合表的连接字符串;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **{DATA | INDEX} DIRECTORY \[=] 'absolute path to directory'** 用于指定表数据数据和索引的存储目录;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **DELAY\_KEY\_WRITE \[=] value** 用于指定是否延迟表的键更新直到表关闭;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **ENCRYPTION \[=] 'encryption\_string'** 用于指定表启用或禁用页面级数据加密;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **ENGINE\_ATTRIBUTE \[=] 'string'** 用于指定主存储引擎的表属性;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **INSERT\_METHOD \[=] { NO | FIRST | LAST }** 用于指定应将行插入到的表;目前该特性仅有语法支持,不实现功能。参数的取值范围为NO,FIRST,LAST。 * **KEY\_BLOCK\_SIZE \[=] value** 用于指定索引键块的字节大小;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **MAX\_ROWS \[=] value** 用于指定计划在表中存储的最大行数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **MIN\_ROWS \[=] value** 用于指定计划在表中存储的最小行数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **PACK\_KEYS \[=] value** 用于指定控制压缩索引的方式;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **PASSWORD \[=] 'password'** 此选项未使用;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **SECONDARY\_ENGINE\_ATTRIBUTE \[=] 'string'** 用于指定辅助存储引擎的表属性;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **START TRANSACTION** 用于开启事务模式;目前该特性仅有语法支持,不实现功能。 * **STATS\_AUTO\_RECALC \[=] value** 用于指定是否自动重新计算表的持久统计信息;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **STATS\_PERSISTENT \[=] value** 用于指定是否为表启用持久统计信息;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **STATS\_SAMPLE\_PAGES \[=] value** 用于指定估计索引列的基数和其他统计信息时要采样的索引页数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **UNION \[=] (tbl\_name\[,tbl\_name]...)** 用于访问一组相同的表作为一个表;目前该特性仅有语法支持,不实现功能。 * **TABLESPACE tablespace\_name \[STORAGE DISK]** 用于指定表存储在磁盘;目前该特性仅有语法支持,不实现功能。 * **\[TABLESPACE tablespace\_name] STORAGE MEMORY** 用于指定表存储在内存;目前该特性仅有语法支持,不实现功能。 其中列相关的操作column\_clause可以是以下子句之一: ``` ADD [ COLUMN ] column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] [ FIRST | AFTER column_name ] | MODIFY [ COLUMN ] column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [{[ COLLATE collation ] | [ column_constraint ]} [ ... ] ] [FIRST | AFTER column_name] | CHANGE [ COLUMN ] old_column_name new_column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [BINARY | ASCII] [{[ COLLATE collation ] | [ column_constraint ]} [ ... ] ] [FIRST | AFTER column_name] ``` * **ADD \[ COLUMN ] column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[BINARY | ASCII] \[ compress\_mode ] \[ COLLATE collation ] \[ column\_constraint \[ ... ] ] \[ FIRST | AFTER column\_name]** 向表中增加一个新的字段。用ADD COLUMN增加一个字段,所有表中现有行都初始化为该字段的缺省值(如果没有声明DEFAULT子句,值为NULL)。其中FIRST | AFTER column\_name表示新增字段到某个位置。BINARY关键字将设置列的字符序为该列字符集对应的`_bin`字符序,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`。ASCII关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 * **MODIFY \[ COLUMN ] column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[BINARY | ASCII] \[{\[ COLLATE collation ] | \[ column\_constraint ]} \[ ... ] ] \[FIRST | AFTER column\_name]** 修改表已存在字段的定义,将用新定义替换字段原定义,原字段上的索引、独立对象约束(例如:主键、唯一键、CHECK约束等)不会被删除。\[FIRST | AFTER column\_name]语法表示修改字段定义的同时修改字段在表中的位置。BINARY关键字将设置列的字符序为该列字符集对应的`_bin`字符序,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`。ASCII关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 * **CHANGE \[ COLUMN ] old\_column\_name new\_column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[BINARY | ASCII] \[{\[ COLLATE collation ] | \[ column\_constraint ]} \[ ... ] ] \[FIRST | AFTER column\_name]** 修改表已存在字段的名称和定义,字段新名称不能是已有字段的名称,将用新名称和定义替换字段原名称和定义原字段上的索引、独立对象约束(例如:主键、唯一键、CHECK约束)等不会被删除。\[FIRST | AFTER column\_name]语法表示修改字段名称和定义的同时修改字段在表中的位置。BINARY关键字将设置列的字符序为该列字符集对应的`_bin`字符序,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`。ASCII关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 > \[!NOTE]说明 > > 涉及的参数说明可见[ALTER TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_table.html)。 ## 示例 \--- 创建表、外键和非唯一索引。 ``` openGauss=# CREATE TABLE alter_table_tbl1 (a INT PRIMARY KEY, b INT); openGauss=# CREATE TABLE alter_table_tbl2 (c INT PRIMARY KEY, d INT); openGauss=# ALTER TABLE alter_table_tbl2 ADD CONSTRAINT alter_table_tbl_fk FOREIGN KEY (d) REFERENCES alter_table_tbl1 (a); openGauss=# CREATE INDEX alter_table_tbl_b_ind ON alter_table_tbl1(b); ``` \--- 禁用和启用非唯一索引。 ``` openGauss=# ALTER TABLE alter_table_tbl1 DISABLE KEYS; openGauss=# ALTER TABLE alter_table_tbl1 ENABLE KEYS; ``` \--- 删除索引。 ``` openGauss=# ALTER TABLE alter_table_tbl1 DROP KEY alter_table_tbl_b_ind; ``` \--- 删除主键。 ``` openGauss=# ALTER TABLE alter_table_tbl2 DROP PRIMARY KEY; ``` \--- 删除外键。 ``` openGauss=# ALTER TABLE alter_table_tbl2 DROP FOREIGN KEY alter_table_tbl_fk; ``` \--- 重建表。 ``` openGauss=# ALTER TABLE alter_table_tbl1 FORCE; ``` \--- 重命名索引。 ``` openGauss=# CREATE INDEX alter_table_tbl_b_ind ON alter_table_tbl1(b); openGauss=# ALTER TABLE alter_table_tbl1 RENAME INDEX alter_table_tbl_b_ind TO new_alter_table_tbl_b_ind; ``` \--- 修改表,创建INVISIBLE普通索引 ``` openGauss=# ALTER TABLE alter_table_tbl1 ADD INDEX alter_table_tbl_b_ind(b) INVISIBLE; ``` \--- 删除表。 ``` openGauss=# DROP TABLE alter_table_tbl1, alter_table_tbl2; ``` \--- 兼容MySQL全文索引,添加全文索引语法,前提是兼容模式为B的数据库。 ```sql test=# ALTER TABLE test ADD FULLTEXT INDEX test_index_1 (title, boby) WITH PARSER ngram; ALTER TABLE test=# \d test_index_1 Index "fulltext_test.test_index_1" Column | Type | Definition --------------+------+------------------------------------------------ to_tsvector | text | to_tsvector('"ngram"'::regconfig, title::text) to_tsvector1 | text | to_tsvector('"ngram"'::regconfig, boby) gin, for table "fulltext_test.test" ``` ## 相关链接 [ALTER TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_table.html) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-ALTER-TABLE.md --- # ALTER TABLE ## 功能描述 修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。 * 新增支持`opt_clustered`语法。 * 修改表语句中,针对UNIQUE和PRIMARY KEY约束,支持通过WITH给出选项,对应index\_parameters子句,新增支持的选项包括: ``` FILLFACTOR = fillfactor | PAD_INDEX = { ON | OFF } | IGNORE_DUP_KEY = { ON | OFF } | STATISTICS_NORECOMPUTE = { ON | OFF } | STATISTICS_INCREMENTAL = { ON | OFF } | ALLOW_ROW_LOCKS = { ON | OFF } | ALLOW_PAGE_LOCKS = { ON | OFF } | OPTIMIZE_FOR_SEQUENTIAL_KEY = { ON | OFF } | XML_COMPRESSION = { ON | OFF } | COMPRESSION_DELAY = { 0 | delay [ MINUTES | MINUTE ] } | DATA_COMPRESSION = { NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE } ``` 其中FILLFACTOR选项的取值fillfactor为\[1, 100]的整数,实际含义同A库(A库的取值范围为\[10, 100]的整数),因此当D库中fillfactor的取值范围为\[1, 10),不报错,将打印notice信息,并将fillfactor的取值设置为A库的最小值10; COMPRESSION\_DELAY选项的取值delay为\[0, 10080]的整数; 除FILLFACTOR选项含有实际功能,同A库,其余参数均无实际功能,仅语法支持。 * 修改表语句中,针对UNIQUE和PRIMARY KEY约束,支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * filegroup为任意字符串,支持通过\[]包裹。 * 新增支持为列添加identity属性的语法。 ## 语法格式 * 修改表的定义。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | (ONLY) table_name | (ONLY) ( table_name ) } action [, ... ]; ``` 其中具体表操作action可以是以下子句之一: ``` column_clause | ADD table_constraint [ NOT VALID ] | ADD table_constraint_using_index | VALIDATE CONSTRAINT constraint_name | DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ] | CLUSTER ON index_name | SET WITHOUT CLUSTER | SET ( {storage_parameter = value} [, ... ] ) | RESET ( storage_parameter [, ... ] ) | OWNER TO new_owner | SET TABLESPACE new_tablespace | SET {COMPRESS|NOCOMPRESS} | TO { GROUP groupname | NODE ( nodename [, ... ] ) } | ADD NODE ( nodename [, ... ] ) | DELETE NODE ( nodename [, ... ] ) | DISABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE REPLICA TRIGGER trigger_name | ENABLE ALWAYS TRIGGER trigger_name | DISABLE/ENABLE [ REPLICA | ALWAYS ] RULE | DISABLE ROW LEVEL SECURITY | ENABLE ROW LEVEL SECURITY | FORCE ROW LEVEL SECURITY | NO FORCE ROW LEVEL SECURITY | ENCRYPTION KEY ROTATION | INHERIT parents | NO INHERIT parents | OF type_name | NOT OF | REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING } | AUTO_INCREMENT [ = ] value | COMMENT {=| } 'text' | ALTER INDEX index_name [ VISBLE | INVISIBLE ] | [ [ DEFAULT ] CHARACTER SET | CHARSET [ = ] default_charset ] [ [ DEFAULT ] COLLATE [ = ] default_collation ] | CONVERT TO CHARACTER SET | CHARSET charset | DEFAULT [ COLLATE collation ] | MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP | IMCSTORED [ ( column_name [, ...] ) ] | MODIFY PARTITION partition_name IMCSTORED [ ( column_name [, ...] ) ] | UNIMCSTORED | MODIFY PARTITION partition_name UNIMCSTORED ``` * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | IDENTITY [ ( seed, increment ) ] | GENERATED ALWAYS AS ( generation_expr ) [STORED] | ON UPDATE update_expr | { UNIQUE [KEY] index_parameters [ ON filegroup ] | PRIMARY KEY index_parameters [ ON filegroup ] } [ { ENABLE | DISABLE } [ VALIDATE | NOVALIDATE ] | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] [ ENABLE ] | { ENABLE | DISABLE } [ VALIDATE | NOVALIDATE ] Constraint constraint_name | DEFAULT (expression) FOR (column_name) } | AUTO_INCREMENT | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] | [ COMMENT 'text' ] ``` * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ opt_clustered ] ( { { column_name [ ( length ) ] | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] [ ON filegroup ] | PRIMARY KEY [ opt_clustered ] ( { column_name [ ASC | DESC ] }[, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] [ ON filegroup ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | FOREIGN KEY [ idx_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 其中索引参数index\_parameters为: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## 参数说明 * **opt\_clustered** 参数内容为CLUSTERED/NONCLUSTERED,兼容D库的语法,指定创建聚合/非聚合索引。仅语法作用,没有实际功能。 * **WITH ( { storage\_parameter = value } \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。用于表的WITH子句还可以包含OIDS=FALSE表示不分配OID。 针对UNIQUE和PRIMARY KEY约束,新增支持的storage\_parameter选项包括: * FILLFACTOR int类型,填充因子,实际的含义和功能同A库。 取值范围:\[1, 100]的整数,A库的取值范围为\[10, 100]的整数,因此当D库中fillfactor的取值范围为\[1, 10),不报错,将打印notice信息,并将fillfactor的取值设置为A库的最小值10。 * PAD\_INDEX bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * IGNORE\_DUP\_KEY bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * STATISTICS\_NORECOMPUTE bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * STATISTICS\_INCREMENTAL bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * ALLOW\_ROW\_LOCKS bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * ALLOW\_PAGE\_LOCKS bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * OPTIMIZE\_FOR\_SEQUENTIAL\_KEY bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * XML\_COMPRESSION bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * COMPRESSION\_DELAY int类型,单位MINUTES或者MINUTE,可选,无实际功能,仅语法兼容。 取值范围:0 | delay \[ MINUTES | MINUTE ],其中delay为\[0, 10080]的整数。 * DATA\_COMPRESSION string类型,无实际功能,仅语法兼容。 取值范围:NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE\_ARCHIVE。 * **filegroup** * 修改表语句中,针对UNIQUE和PRIMARY KEY约束,支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * filegroup为任意字符串,支持通过\[]包裹。 * **DEFAULT ( expression ) FOR ( column\_name )** * 该语法可以为指定列添加DEFAULT约束,该约束为一个表达式。 * 对于显式声明约束名的场景,仅做语法支持,使用该语法创建的DEFAULT约束无法通过约束名进行删除。 * **IDENTITY \[ ( seed, increment ) ]** * 该语法为列添加identity属性,序列值递增,`seed`指定起始值,`increment`指定步长。 * 一张表只能定义一列(包括generated as identity)。 ## opt\_clustered示例 ``` openGauss=# CREATE TABLE alter_table_tbl1 (a INT, b INT); openGauss=# ALTER TABLE alter_table_tbl1 ADD CONSTRAINT alter_table_tbl_a UNIQUE CLUSTERED (a); openGauss=# ALTER TABLE alter_table_tbl1 ADD CONSTRAINT alter_table_tbl_b PRIMARY KEY NONCLUSTERED (a); ``` ## WITH ( { storage\_parameter = value } \[, ... ] )示例 ```sql create table test1(col1 int primary key with(fillfactor = 20), col2 int); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test1_pkey" for table "test1" alter table test1 add constraint unique_name unique(col2) with (fillfactor = 50, ignore_dup_key = on); NOTICE: parameter "ignore_dup_key" is currently ignored. NOTICE: ALTER TABLE / ADD UNIQUE will create implicit index "unique_name" for table "test1" alter table test1 add column col3 int unique with (pad_index = on); NOTICE: parameter "pad_index" is currently ignored. NOTICE: ALTER TABLE / ADD UNIQUE will create implicit index "test1_col3_key" for table "test1" create table test2(col1 int, col2 int); alter table test2 add constraint pk_id primary key(col1) with (fillfactor = 50, allow_row_locks = off); NOTICE: parameter "allow_row_locks" is currently ignored. NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index "pk_id" for table "test2" create table test3(col1 int, col2 int); alter table test3 add column col3 int primary key with (data_compression = none); NOTICE: parameter "data_compression" is currently ignored. NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index "test3_pkey" for table "test3" ``` ## filegroup示例 ```sql create table test1(col1 int primary key with(fillfactor = 20), col2 int); alter table test1 add constraint unique_name unique(col2) with (fillfactor = 50, ignore_dup_key = on) on [primary1]; alter table test1 add column col3 int unique with (pad_index = on) on [primary2]; create table test2(col1 int, col2 int); alter table test2 add constraint pk_id primary key(col1) with (fillfactor = 50, allow_row_locks = off) on [primar3]; create table test3(col1 int, col2 int); alter table test3 add column col3 int primary key with (data_compression = none) on [primar4]; ``` ## IDENTITY \[ ( seed, increment ) ] 示例 ```sql openGauss=# create extension shark; CREATE EXTENSION openGauss=# create table t1 (a int identity(10, 20), b int); NOTICE: CREATE TABLE will create implicit sequence "t1_a_seq_identity" for serial column "t1.a" CREATE TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+-------------------+---------+--------------+------------- a | integer | not null identity | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no, collate=1537 Character Set: UTF8 Collate: utf8mb4_general_ci openGauss=# alter table t1 alter column b add identity ; NOTICE: ALTER TABLE will create implicit sequence "t1_b_seq_identity" for serial column "t1.b" ERROR: Multiple identity columns specified for table "t1". Only one identity column per table is allowed. openGauss=# create table t2 (a int, b int); CREATE TABLE openGauss=# alter table t2 alter column b add identity ; NOTICE: ALTER TABLE will create implicit sequence "t2_b_seq_identity" for serial column "t2.b" ERROR: column "b" of relation "t2" must be declared NOT NULL before identity can be added openGauss=# alter table t2 alter column b set not null; ALTER TABLE openGauss=# alter table t2 alter column b add identity ; NOTICE: ALTER TABLE will create implicit sequence "t2_b_seq_identity" for serial column "t2.b" ALTER TABLE openGauss=# ``` ## DEFAULT (expression) FOR (column\_name) 示例 ```sql openGauss=# create table ADD_DEFAULT(id int, v1 varchar(20), v2 float); CREATE TABLE openGauss=# \d+ ADD_DEFAULT Table "public.add_default" Column | Type | Modifiers | Storage | Stats target | Description --------+-----------------------+-----------+----------+--------------+------------- id | integer | | plain | | v1 | character varying(20) | | extended | | v2 | double precision | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table ADD_DEFAULT add default (mod(4, 3)) for id; NOTICE: DEFAULT added. The added DEFAULT can not be dropped by name ALTER TABLE openGauss=# \d+ ADD_DEFAULT Table "public.add_default" Column | Type | Modifiers | Storage | Stats target | Description --------+-----------------------+-------------------+----------+--------------+------------- id | integer | default mod(4, 3) | plain | | v1 | character varying(20) | | extended | | v2 | double precision | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# insert into ADD_DEFAULT(v1, v2) values('bac', 3.1); INSERT 0 1 openGauss=# select * from ADD_DEFAULT; id | v1 | v2 ----+-----+----- 1 | bac | 3.1 (1 row) openGauss=# create table ADD_CONSTRAINT_DEFAULT(id int, v1 varchar(20), v2 timestamptz); CREATE TABLE openGauss=# \d+ ADD_CONSTRAINT_DEFAULT Table "public.add_constraint_default" Column | Type | Modifiers | Storage | Stats target | Description --------+--------------------------+-----------+----------+--------------+------------- id | integer | | plain | | v1 | character varying(20) | | extended | | v2 | timestamp with time zone | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table ADD_CONSTRAINT_DEFAULT add constraint ADD_SYSTEIME_DEFAULT default (pg_systimestamp()) for v2; NOTICE: DEFAULT added. The added DEFAULT can not be dropped by name ALTER TABLE test_d=# \d+ ADD_CONSTRAINT_DEFAULT Table "public.add_constraint_default" Column | Type | Modifiers | Storage | Stats target | Description --------+--------------------------+---------------------------+----------+--------------+------------- id | integer | | plain | | v1 | character varying(20) | | extended | | v2 | timestamp with time zone | default pg_systimestamp() | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# insert into ADD_CONSTRAINT_DEFAULT(id, v1) values(1, 'abc'); INSERT 0 1 openGauss=# select * from ADD_CONSTRAINT_DEFAULT; id | v1 | v2 ----+-----+------------------------------- 1 | abc | 2025-10-30 11:17:36.821797+08 (1 row) ``` ## 相关链接 [ALTER TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_table.html) --- --- url: /zh/docs/latest/ograc/sql_reference/alter_table.md --- # ALTER TABLE ## 功能描述 ALTER TABLE 操作用于对数据库表的定义进行结构变更,包含对字段和约束条件的调整,具体功能如下: * 数据列的增加、删除、属性修改以及重命名 * 约束条件的添加与移除 * 对现有约束进行启用或禁用 * 更改数据表的名称 * 将已有分区拆分为更小的分区单元 * 在两个表或分区之间进行数据交换 ## 注意事项 * 执行此操作的用户必须具有 ALTER TABLE 或 ALTER ANY TABLE 系统权限。非特权用户不能修改 SYS 账户所属的对象。 * 如果命令中指定的表名称、字段名称或约束名称存在冲突或无效,或者表内数据与要启用的非验证约束状态不符,系统会给出明确的错误信息。 * 要修改表中某列的属性,该列在所有现有记录中的值必须均为 NULL。如果列包含非空值且不是分区键,则仅允许以下变更:BINARY、INT、CHAR、VARCHAR 类型可增大长度或尺寸;高精度数值类型可扩展其范围(修改后的小数位数和整数位数均不得小于原值)。其他数据类型及操作均不允许。 * 在添加新列或修改现有列时,不得同时将其定义为唯一索引、主键索引或以内联方式声明的外键约束。 * ALTER TABLE 命令不适用于外部表。 * 在数据库重新启动或事务回滚过程中,无法执行此操作。 ## 语法格式 ```sql ALTER TABLE [ schema_name. ]table_name { alter_table_properties | column_clauses | partition_clauses | set_interval_clause | logic_replication_clauses } ``` * *alter\_table\_properties* 语法组件: ``` { physical_attributes_clause | RENAME TO new_table_name | AUTO_INCREMENT [ = ] value } ``` * *physical\_attributes\_clause* 语法组件: ``` { PCTFREE integer | INITRANS integer | APPENDONLY { ON | OFF } | storage_alter_clause } ``` * *storage\_alter\_clause语法:* ``` STORAGE ( MAXSIZE { UNLIMITED | integer [K | M | G | T] } ) ``` * *column\_clauses* 语法组件: ``` { add_column_clause | modify_column_clause | drop_column_clause | rename_column_clause } ``` * *add\_column\_clause* 语法组件: ``` -- 添加单一数据列。 ADD [ COLUMN ] column_name datatype_name [ DEFAULT expr [ON UPDATE expr ] ] [ COMMENT 'string' ] [ COLLATE collation_name ] [AUTO_INCREMENT] [ inline_constraint ] -- 添加多个数据列。 ADD ( [ COLUMN ] { column_name datatype_name [ DEFAULT expr [ON UPDATE expr ] ] [ COMMENT 'string' ] [ COLLATE collation_name ] [AUTO_INCREMENT] [ inline_constraint ] } [ , ... ] ) ``` * *inline\_constraint* 语法组件: ``` [ CONSTRAINT constraint_name ]{ [ NOT ] NULL | CHECK( expr ) | PRIMARY KEY | UNIQUE }[ ... ] ``` * *modify\_column\_clause* 语法组件: ``` -- 修改列定义。 MODIFY ( { column_name [ new_datatype_name ] [ DEFAULT expr [ ON UPDATE expr ] ] [ COMMENT string ] [ COLLATE collation_name ] [ inline_constraint ] } [ , ... ] ) -- 回收LOB类型字段的空间占用。 MODIFY LOB(column_name) (SHRINK SPACE) ``` * *drop\_column\_clause* 语法组件: ``` DROP [ COLUMN ] column_name ``` * *rename\_column\_clause* 语法组件: ``` RENAME COLUMN old_name TO new_name ``` * *partition\_clauses* 语法组件: ``` { add_partition_clause | drop_partition_clause | truncate_partition_clause | coalesce_partition_clause | split_partition_clause | modify_partition_clause } ``` * *add\_partition\_clause* 语法组件: ``` ADD PARTITION partition_name { VALUES LESS THAN ( { partition_value | MAXVALUE } [ , ... ] ) | VALUES ( partition_value [ , ... ] | DEFAULT ) } [ TABLESPACE tablespace_name ] [ PCTFREE integer ][ storage_clause ] { FORMAT CSF | [ COMPRESS ] [ ( { SUBPARTITION subpartition_name ( { VALUES LESS THAN ( { subpartition_value | MAXVALUE } [, ... ] ) | VALUES ( { subpartition_value [, ... ] | DEFAULT } [, ... ] ) } [ TABLESPACE tablespace_name ] ) } [, ... ] ) ] } MODIFY PARTITION partition_name ADD SUBPARTITION { VALUES LESS THAN ( { subpartition_value | MAXVALUE } [, ... ] ) | VALUES ( subpartition_values [, ... ] | DEFAULT ) } [ TABLESPACE tablespace_name ] ``` * *storage\_clause* 语法组件: ``` STORAGE ( { INITIAL integer [K | M | G | T] |MAXSIZE { UNLIMITED | integer [K | M | G | T] } } [ ...] ) ``` * *drop\_partition\_clause* 语法组件: ``` DROP { PARTITION partition_name | SUBPARTITION subpartition_name } ``` * truncate\_partition\_clause 语法组件: ``` TRUNCATE { PARTITION partition_name | SUBPARTITION subpartition_name } [ DROP STORAGE | REUSE STORAGE | PURGE ] ``` * coalesce\_partition\_clause 语法组件: ``` COALESCE PARTITION MODIFY PARTITION partition_name COALESCE SUBPARTITION ``` * *split\_partition\_clause* 语法组件: ``` SPLIT PARTITION partition_name AT (range_value) INTO ( PARTITION part_name1 [ TABLESPACE space_name ], PARTITION part_name2 [ TABLESPACE space_name ] ) [ UPDATE GLOBAL INDEXES ] SPLIT SUBPARTITION subpartition_name AT (range_value) INTO ( SUBPARTITION subpart_name1 [ TABLESPACE space_name ], SUBPARTITION subpart_name2 [ TABLESPACE space_name ] ) [ UPDATE GLOBAL INDEXES ] ``` * *modify\_partition\_clause* 语法组件: ``` MODIFY PARTITION partition_name { INITRANS integer | storage_alter_clause } ``` * *storage\_alter\_clause* 语法组件: ``` STORAGE (MAXSIZE { UNLIMITED | integer [K | M | G | T] } ) ``` * *set\_interval\_clause* 语法组件: ``` SET INTERVAL([interval_value]) ``` * *logic\_replication\_clauses* 语法组件: ``` [([ partition_name | subpartition_name ][ , ... ])] ADD LOGICAL LOG(UNIQUE index_name)| [([ partition_name | subpartition_name ][ , ... ])] ADD LOGICAL LOG(PRIMARY KEY) | DROP LOGICAL LOG ``` ## 参数说明 * **\[*schema\_name*.]**: 模式名称。当未显式指定时,系统默认采用当前登录用户的名称作为模式名。 * ***table\_name***: 需要修改的目标数据表名称,该表必须已经存在于数据库中。 * ***alter\_table\_properties***: 用于调整数据表的物理存储特性。例如,LOB\_storage\_clause 可指定大型对象(LOB)字段存储在独立的段中,并可配置为行内或行外存储。目前存储引擎仅支持行外存储模式。 * ***physical\_attributes\_clause***: * **INITRANS *integer***: 调整数据表中每个初始数据页面上预分配的事务槽数量。该参数的取值区间为 \[1, 255]。 > **说明:** > > * 此修改仅对后续新分配的数据页面生效,已分配的现有页面不受影响。 > * 对于分区表,该操作会同时更新表分区及所有二级分区的 INITRANS 属性。 * ***storage\_alter\_clause***: 设置数据表可使用的最大存储空间限额。 * **UNLIMITED**: 表示不对此表的存储空间设置上限。 * ***integer* \[K | M | G | T]**: 明确设定表存储空间的最大值,允许的范围是 \[1MB, 1TB]。 * **APPENDONLY { ON | OFF }**: 此选项控制并发插入行为。当设置为 ON 时,各插入线程将独立扩展存储空间,可提升高并发下的插入性能。默认值为 OFF。启用此功能需谨慎,若使用不当可能导致存储空间利用率下降。 * **ON**: 启用独立空间扩展模式。 > **重要提示:** > > * 对于分区表,启用 APPENDONLY ON 后,在并行插入场景下需特别注意。用户需预先规划数据,确保每个并行线程插入的数据不会跨越多个分区,即实现"一个线程对应一个分区"。 > * 不建议对 HASH 分区表启用 APPENDONLY ON 选项。 * **OFF**: 关闭独立空间扩展,采用常规并发插入模式。 * **PCTFREE *integer***: 定义数据块中保留的自由空间百分比。当数据块中的可用空间低于此百分比时,该块仅允许执行更新操作,禁止插入新数据。取值范围是 \[0, 80],默认值为 8。 * **RENAME TO *new\_table\_name***: 修改数据表的名称。 * **AUTO\_INCREMENT \[ = ] value**: 修改表上自增列的起始序列值。若未指定,则默认从 1 开始。 * ***column\_clauses***: 用于变更表结构,包括增加、删除及修改数据列。 * ***add\_column\_clause***: 向表中添加新的数据列。 * **DEFAULT —— \[ON UPDATE *expr*]**: 列的默认值支持使用表达式。在创建 DDL 时,若 DEFAULT 是常量表达式,系统会进行列数据类型的兼容性检查。 * **`[ON UPDATE expr]`**: 此为语法兼容项。当更新行数据且未显式指定该列值时,将使用此更新默认表达式填充该列。 * **`INSERT` 和 `UPDATE` 操作中,`DEFAULT` 后面的表达式文本最大长度限制为 1024 个英文字符。若超过此限制,将报错**: "GS-00611, default value string is too long, exceed 1024."。 * **COMMENT *'string'***: 为列添加注释信息。可通过查询 `MY_COL_COMMENTS` 系统视图来查看列注释。 * **COLLATE *collation\_name***: 定义该列数据的排序(比较)规则。当比较此列中的数据时,将依据此处定义的排序规则判定大小或相等关系。 *collation\_name* 为排序规则名称,可选值如下: * **`UTF8_BIN`**: 适用于 UTF8 字符集。将字符视为二进制串,从高位到低位逐位比较。区分大小写。 * **`UTF8_GENERAL_CI`**: 适用于 UTF8 字符集,不区分大小写。 * **`UTF8_UNICODE_CI`**: 适用于 UTF8 字符集,不区分大小写。 * **`GBK_BIN`**: 适用于 GBK 字符集,区分大小写。 * **`GBK_CHINESE_CI`**: 适用于 GBK 字符集,不区分大小写。 * ***inline\_constraint***: 内联列约束,作为列定义的一部分直接声明。目前支持 `[NOT] NULL`、`UNIQUE`、`PRIMARY KEY`、唯一索引、外键及 `CHECK` 约束。 * ***modify\_column\_clause***: 修改一个或多个指定列的属性,包括:更改数据类型、在符合现有约束的前提下添加列约束、以及收缩 LOB 字段占用的空间。函数索引依赖的列不支持修改属性。 修改列的数据类型时,仅在表为空或该列所有值均为 `NULL` 时,才允许进行不兼容的数据类型变更。若要进行兼容的数据类型变更,则表中必须已有数据,且待修改列的值不全为 `NULL`。当前支持的兼容数据类型变更包括: * `VARCHAR` 与 `CHAR` 类型相互转换(要求转换后的长度不小于转换前的长度)。 * `VARCHAR`、`CHAR`、`BINARY`、`INT` 类型增大其长度限制。 * 高精度数值类型(如 `NUMBER`)扩大其数值范围(要求修改后的小数位数 `scale` 和整数位数 `precision - scale` 均不小于修改前的值)。 * ***new\_datatype\_name***: 修改后列的目标数据类型。 * ***drop\_column\_clause***: 从表中删除指定的列。 * **DROP \[ COLUMN ] column\_name**: 删除列字段。`column_name` 为要删除的列的名称。 * ***rename\_column\_clause***: 重命名表中现有的列。 * **RENAME COLUMN *old\_name* TO *new\_name***: 重命名列。 * ***old\_name***: 待重命名的原列名称。 * ***new\_name***: 重命名后的新列名称。 * ***partition\_clauses***: 分区相关操作子句。 * ***add\_partition\_clause***: 为分区表添加新的分区。 * **VALUES LESS THAN**: 用于范围分区,定义新分区的上限值(不包含)。 * ***partition\_value***: 分区的边界值。 * **MAXVALUE**: 表示一个分区允许的最大可能值,通常用于最后一个分区。 * **VALUES**: 用于列表分区,定义新分区包含的特定值集合。 * **DEFAULT**: 用于列表分区,创建一个容纳所有未在其他分区中指定值的数据的默认分区。 * **INITIAL *integer* \[K | M | G | T]**: 指定新分区的初始存储空间大小。默认情况下,一个新分区会分配一个区段(EXTENT)。可通过此参数自定义初始大小。取值范围是 \[64KB, 1TB]。 * **MAXSIZE { UNLIMITED | *integer* \[K | M | G | T] }**: 指定该分区可使用的最大存储空间限额。 * **UNLIMITED**: 表示不限制该分区的存储空间上限。 * **integer \[K | M | G | T]**: 明确设定该分区存储空间的最大值,取值范围是 \[1MB, 1TB]。 * **FORMAT CSF**: 对于带CSF属性的HASH分区,由于HASH分区添加时会导致数据重分布,所以带CSF属性的HASH分区添加时可能会报错,报错与否取决于是否满足CSF属性约束。 * **COMPRESS**: 添加一个压缩分区。需确保此压缩分区所处的表空间内具有压缩属性文件,否则插入数据时会报错。 * drop\_partition\_clause * DROP PARTITION partition\_name 删除一个分区,partition\_name 是分区名称。 * DROP SUBPARTITION subpartition\_name 删除二级分区子分区,subpartition\_name为子分区的名字。 * split\_partition\_clause 分裂分区,将指定的(子)分区分裂为两个(子)分区,原始分区里的数据将会重新分布到新的分区里。目前只有RANGE分区支持split操作。 * (sub)partition\_name 将要分裂的(子)分区名称。 * (sub)part\_name1 (sub)part\_name2 分裂后新的(子)分区名称,注意这两个(子)分区名称不能重复。一级分区进行分裂后,只有最后一个新分区可以使用原分区名称。 * range\_value 分裂的边界值。 * UPDATE GLOBAL INDEXES * 如果指定update global indexes,且分区表有全局索引的时候,则数据重分布之后会自动重建全局索引。 * 如果不指定,则全局索引处于invalid状态。 * exchange\_partition\_clause 交换分区 * WITH TABLE 设置需要交换的普通表的表名。 * INCLUDING | EXCLUDING INDEXES * INCLUDING INDEXES 要交换索引。 * EXCLUDING INDEXES 不需要交换索引。 * WITH | WITHOUT VALIDATION * WITH VALIDATION 需要校验数据。 * WITHOUT VALIDATION 不需要交换数据。 * partition\_clause 需要交换的分区的信息 * partition\_name 需要交换的分区名称 * FOR(part\_key value) 当分区名不易获取的情况下,可以通过设置该分区键值用于指示需要交换的分区。 > **说明:** 分区交换的使用约束 > > 1. 不支持RCR的表和索引进行交换。 > 2. 不支持涉及外键约束的子句,例如cascade。若交换的两张表的任意表上有外键关系,则交换分区会报错。 > 3. 交换的分区需要判断是否具有压缩、nologging Insert等属性,如果属性不相同则不允许交换。 > 4. 交换的分区存在自增列的时候不允许交换。 > 5. 交换的分区的表定义、索引定义、列定义完全相同时,才允许交换。 * modify\_partition\_clause 修改分区的属性 * partition\_name 需要修改的分区名称。 * INITRANS integer 对分区的初始数据页面上事务槽的个数进行修改,取值范围是\[1,255]。 * 修改指定分区的INITRANS属性,并且会同步修改该分区的所有子分区的INITRANS。 * 对于新分配的页面,修改后的新值是有效的,对已经分配的老页面是无效的。 > **说明:** INITRANS使用 > > 1. 高并发oltp系统,当出现频繁的update/insert操作导致事务槽争用时,可以将INITRANS设为4-8(INITRANS=10时),减少动态扩展开销。 > 2. 索引块的默认INITRANS=2可能无法满足高并发写入需求,可以将其设置为3。 * storage\_alter\_clause 表的存储空间的最大值。 * UNLIMITED 说明不限制表存储空间的最大值。 * integer\[K|M|G|T] 设置表的存储空间最大值,取值范围\[1M,1T]。 * coalesce\_partition\_clause * COALESCE PARTITION 先将最后一个分区的数据插入进前面的某个分区中之后,再将最后一个分区进行删除。 * 仅限HASH分区的情况才能执行COALESCE\_PARTITION语句,并且无需指定分区名称。 * 如果只剩一个分区,不能执行COALESCE\_PARTITION语句,否则会报错。 * \[PARTITION | SUBPARTITION] NOLOGGING * NOLOGGING 启用或禁用分区上的NOLOGGING INSERT属性。 * PARTITION NOLOGGING 启用或禁用分区上的NOLOGGING INSERT属性。 * SUBPARTITION NOLOGGING 启用或禁用子分区上的NOLOGGING INSERT属性。 表级与分区级的 NOLOGGING INSERT 属性相互独立、互不影响:某个分区是否启用 NOLOGGING INSERT 属性,与表上的该属性配置无关,仅由分区自身的 NOLOGGING INSERT 属性设置决定。而父子分区间的 NOLOGGING INSERT 属性存在关联规则:若父分区开启了 NOLOGGING INSERT 属性,其下所有子分区会同步启用该属性;反之,即使启用子分区的 NOLOGGING INSERT 属性,也不会对父分区的该属性状态产生任何影响。 该特性使用时,需要注意以下约束: * NOLOGGING INSERT 该操作的目的是提升大量数据的入库性能,在表或分区上执行Nologging insert操作时,需避免与其他正常业务并发执行。这是因为Nologging insert不会记录 undo日志,若出现并发读取undo的情况,可能会导致正常业务报错。 * NOLOGGING INSERT 数据入库操作全部完成后,建议及时提交事务,同时手动触发数据刷盘操作;待上述操作执行完毕后,再启动其他相关业务。这样做可有效保障数据安全性,防止因突发掉电情况导致数据丢失,进而避免需重新执行数据入库的重复操作。 * NOLOGGING INSERT不会记录 undo 数据,因此完成数据导入后,强烈建议先及时提交事务,再开展其他业务操作 —— 这能防止其他业务因无法访问历史数据而出现异常。同时需注意,由于未生成 undo 日志,若同一事务中执行过 NOLOGGING INSERT,后续即便执行 rollback 操作(操作本身可正常执行),数据库内部也不会产生任何数据修改效果。故而,执行过 NOLOGGING INSERT 的事务,无法通过 rollback 操作回退到数据的历史版本。由于没有redo/undo,所以一旦发生任何异常,数据库不能继续保证数据一致性,因此需要删除表数据,重新执行导入操作。 * Session级别的 NOLOGGING INSERT仅供内部工具使用,客户业务禁止采用该语法。对于客户业务场景,应使用表分区级的 NOLOGGING INSERT,以此替代Session级的NOLOGGING INSERT进行相关操作。 * 开启逻辑复制或者在主备环境下不允许执行NOLOGGING INSERT。同时若数据库中有表或者分区对象存在NOLOGGING INSERT,则后续不允许动态添加备机。 * 临时表不支持NOLOGGING INSERT属性的设置,临时表本身就带有不记录redo的属性,所以临时表不支持再设置nologging属性。 * **若表或分区中已存在原有数据,则不允许启用 NOLOGGING INSERT 操作。关于版本兼容性需注意**: 支持表分区级 NOLOGGING INSERT 特性的数据库版本,不允许降级至不支持该特性的版本,但可正常升级;若两个数据库版本均支持表分区级 NOLOGGING INSERT 特性,则可不受限制地执行升级或降级操作(暂不考虑其他特性的兼容性影响)。此外,在启动数据库升级或降级流程前,用户需手动核查系统中是否存在 NOLOGGING 对象;若这些对象已无需保留 NOLOGGING 属性,建议先关闭该属性,再开展升级或降级操作。 * **若在执行备份恢复操作前,未关闭对象的NOLOGGING INSERT属性,会导致该NOLOGGING属性扩散至恢复后的新环境中。用户需提前确认是否需要保留该属性的扩散效果**: 若无需将NOLOGGING属性同步到新环境,则应在备份操作执行前,先关闭对应对象的NOLOGGING属性。 * logic\_replication\_clauses 打开表逻辑复制开关或者关闭逻辑复制的开关,支持表级和表分区级逻辑复制开关的打开或关闭。 * (sub)partition\_name * 在表名后括号内填写表(子)分区名称,即可完成表分区级逻辑复制开关的设置。该操作支持针对未开启的表分区开关进行多次补充配置,但不支持直接在表级与表分区级开关之间切换。 * SYS用户不会加载数据字典,基于这一特性,该用户不支持通过多次补充操作开启表分区逻辑复制开关。 * ADD LOGICAL LOG(PRIMARY KEY) 根据主键打开表逻辑复制开关。 * ADD LOGICAL LOG(UNIQUE index\_name) 根据唯一索引打开逻辑复制开关。 * DROP LOGICAL LOG 关闭表级和分区级逻辑复制开关。 * rename\_column\_clause 修改表名。只能修改自己schema下的表名,不能修改系统表空间下的表名。 * set\_interval\_clause 设置间隔分区,仅对分区表有效。 * **SET INTERVAL()**: 将间隔分区表修改为范围分区表。 * **SET INTERVAL(interval\_value)**: 修改间隔分区表的间隔值,interval\_value表示指定具体的间隔值数值。 ## 示例 * 添加某列 ``` --删除表training DROP TABLE IF EXISTS test; --创建表test CREATE TABLE test(student_id INT NOT NULL, course_name VARCHAR(30), course_start_date DATETIME, score INT); --添加列full_score ALTER TABLE test ADD full_score INT; ``` * 修改列的数据类型 ``` ALTER TABLE test MODIFY course_name VARCHAR(20); ``` * 添加主键约束 ``` ALTER TABLE t_or2union_1 ADD CONSTRAINT pk_a PRIMARY KEY (a); ``` * 删除列 ``` ALTER TABLE test DROP score; ``` * 重命名表 ``` ALTER TABLE test RENAME TO test2025; ``` * 创建分区表 ``` --删除表test_partition DROP TABLE IF EXISTS test_partition; --创建分区表test_partition CREATE TABLE test_partition( student_id INT NOT NULL, course_name CHAR(20), exam_date DATETIME, score INT) PARTITION BY RANGE(student_id) ( PARTITION test_partition1 VALUES LESS THAN(100), PARTITION test_partition2 VALUES LESS THAN(200), PARTITION test_partition3 VALUES LESS THAN(300), PARTITION test_partition4 VALUES LESS THAN(400) ); ``` * 添加分区test\_partition5和test\_partition6 ``` ALTER TABLE test_partition ADD PARTITION test_partition5 VALUES LESS THAN(450); ALTER TABLE test_partition ADD PARTITION test_partition6 VALUES LESS THAN(MAXVALUE); ``` * 删除分区test\_partition3和test\_partition4 ``` --删除分区test_partition3 ALTER TABLE test_partition DROP PARTITION test_partition3; --清空分区test_partition4 ALTER TABLE test_partition TRUNCATE PARTITION test_partition4; ``` * 分裂分区 ``` ALTER TABLE test_partition SPLIT PARTITION test_partition5 AT(430) INTO (PARTITION p1, PARTITION p2); ``` * 修改表的分区的MAXSIZE值 ``` --删除表 DROP TABLE IF EXISTS test_partition; --创建表 CREATE TABLE test_partition(o_id INT, o_char VARCHAR2(900)) STORAGE (MAXSIZE 5M INITIAL 1M) PARTITION BY RANGE(o_id)( PARTITION p1 VALUES LESS THAN(20) STORAGE (MAXSIZE 3M INITIAL 1M), PARTITION p2 VALUES LESS THAN(50) ); --修改表的存储空间的MAXSIZE值 ALTER TABLE test_partition STORAGE (MAXSIZE 10M); --添加分区,初始大小是5M最小值是2M ALTER TABLE test_partition ADD PARTITION p3 VALUES LESS THAN(80) STORAGE (MAXSIZE 5M INITIAL 2M); --修改分区p1的最大值为2M ALTER TABLE test_partition MODIFY PARTITION p1 STORAGE (MAXSIZE 2M); ``` * 修改表及分区的INITRANS值 ``` --删除表 DROP TABLE IF EXISTS test_partition; --创建表 CREATE TABLE test_partition(o_id INT, o_char VARCHAR2(1000)) INITRANS 10 PARTITION BY RANGE(o_id)( PARTITION p1 VALUES LESS THAN(2) INITRANS 5, PARTITION p2 VALUES LESS THAN(3) ); --修改表的INITRANS值 ALTER TABLE test_partition INITRANS 20; --修改表的分区的INITRANS值 ALTER TABLE test_partition MODIFY PARTITION p1 INITRANS 10; ``` * 打开或关闭表级的逻辑复制开关 ``` --删除表 DROP TABLE IF EXISTS test_partition; --创建表 CREATE TABLE test_partition( student_id INT PRIMARY KEY, course_name VARCHAR(50)) PARTITION BY RANGE(student_id)( PARTITION p1 VALUES LESS THAN(10), PARTITION p2 VALUES LESS THAN(50), PARTITION p3 VALUES LESS THAN(100) ); -- 打开表级的逻辑复制开关 ALTER TABLE test_partition ADD LOGICAL LOG(PRIMARY KEY); -- 关闭表级的逻辑复制开关 ALTER TABLE test_partition DROP LOGICAL LOG; ``` * 打开或关闭表分区级逻辑复制开关 ``` --删除表 DROP TABLE IF EXISTS test_partition; --创建表 CREATE TABLE test_partition( student_id INT PRIMARY KEY, course_name VARCHAR(50)) PARTITION BY RANGE(student_id)( PARTITION p1 VALUES LESS THAN(10), PARTITION p2 VALUES LESS THAN(50), PARTITION p3 VALUES LESS THAN(100) ); -- 打开表分区级的逻辑复制开关 ALTER TABLE test_partition(p1,p2) ADD LOGICAL LOG(PRIMARY KEY); -- 删除表分区的同时会删除表分区级逻辑复制开关 ALTER TABLE test_partition DROP PARTITION p1; -- 关闭表级的逻辑复制开关 ALTER TABLE test_partition DROP LOGICAL LOG; ``` --- --- url: /zh/docs/latest/sql_reference/alter_table.md --- # ALTER TABLE ## 功能描述 修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关。 ## 注意事项 * 表的所有者被授予了表ALTER权限的用户或被授予ALTER ANY TABLE的用户有权限执行ALTER TABLE命令,系统管理员默认拥有此权限。但要修改表的所有者或者修改表的模式,当前用户必须是该表的所有者或者系统管理员,且该用户是新所有者角色的成员。 * 不能修改分区表的tablespace,但可以修改分区的tablespace。 * 不支持修改存储参数ORIENTATION。 * SET SCHEMA操作不支持修改为系统内部模式,当前仅支持用户模式之间的修改。 * 列存表只支持PARTIAL CLUSTER KEY、UNIQUE、PRIMARY KEY表级约束,不支持外键等表级约束。 * 列存表只支持添加字段ADD COLUMN、修改字段的数据类型ALTER TYPE、设置单个字段的收集目标SET STATISTICS、支持更改表名称、支持更改表空间、支持删除字段DROP COLUMN。对于添加的字段和修改的字段类型要求是列存支持的[数据类型](numeric_types.md)。ALTER TYPE的USING选项只支持常量表达式和涉及本字段的表达式,暂不支持涉及其他字段的表达式。 * 列存表支持的字段约束包括NULL、NOT NULL、DEFAULT常量值、UNIQUE和PRIMARY KEY;对字段约束的修改当前只支持对DEFAULT值的修改(SET DEFAULT)和删除(DROP DEFAULT),暂不支持对非空约束NULL/NOT NULL的修改。 * 不支持增加自增列,或者增加DEFAULT值中包含nextval()表达式的列。 * 不支持对外表、临时表开启行访问控制开关。 * 通过约束名删除PRIMARY KEY约束时,不会删除NOT NULL约束,如果有需要,请手动删除NOT NULL约束。 * 使用JDBC时,支持通过PrepareStatement对DEFAULT值进行参数化设置。 * 重命名时,不能与当前命名空间的synonym产生命名冲突。 * 设置命名空间时,不能与当前命名空间的synonym产生命名冲突。 * 仅支持在B兼容性数据库下指定COMMENT和可见性VISIBLE\INVISIBLE。 * 使用FIRST | AFTER column\_name新增列或修改列,或修改字段的字符集,会带来全表更新开销,影响在线业务。向已有的字段之间新插入列时,需要保证引用了字段的视图对象有效。 * 删除被视图引用的表字段或修改表字段类型以及字段长度时,将引用视图和物化视图置为无效状态,在查询无效视图或通过无效视图更新、删除和新增表记录以及全量更新物化视图时,检查无效的视图和物化视图引用的表字段是否全部存在,如果存在恢复视图和物化视图的有效状态并返回查询结果,否则报错提示查询无效视图。 ## 语法格式 * 修改表的定义。 ``` ALTER TABLE [CONCURRENTLY] [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name ) } action [, ... ]; ``` 其中具体表操作action可以是以下子句之一: ``` column_clause | ADD table_constraint [ NOT VALID ] | ADD table_constraint_using_index | VALIDATE CONSTRAINT constraint_name | DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ] | CLUSTER ON index_name | SET WITHOUT CLUSTER | SET ( {storage_parameter = value} [, ... ] ) | RESET ( storage_parameter [, ... ] ) | OWNER TO new_owner | SET TABLESPACE new_tablespace | SET {COMPRESS|NOCOMPRESS} | TO { GROUP groupname | NODE ( nodename [, ... ] ) } | ADD NODE ( nodename [, ... ] ) | DELETE NODE ( nodename [, ... ] ) | DISABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE REPLICA TRIGGER trigger_name | ENABLE ALWAYS TRIGGER trigger_name | DISABLE/ENABLE [ REPLICA | ALWAYS ] RULE | DISABLE ROW LEVEL SECURITY | ENABLE ROW LEVEL SECURITY | FORCE ROW LEVEL SECURITY | NO FORCE ROW LEVEL SECURITY | ENCRYPTION KEY ROTATION | INHERIT parents | NO INHERIT parents | OF type_name | NOT OF | REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING } | AUTO_INCREMENT [ = ] value | COMMENT {=| } 'text' | ALTER INDEX index_name [ VISBLE | INVISIBLE ] | [ [ DEFAULT ] CHARACTER SET | CHARSET [ = ] default_charset ] [ [ DEFAULT ] COLLATE [ = ] default_collation ] | CONVERT TO CHARACTER SET | CHARSET charset | DEFAULT [ COLLATE collation ] | MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP | IMCSTORED [ ( column_name [, ...] ) ] | MODIFY PARTITION partition_name IMCSTORED [ ( column_name [, ...] ) ] | UNIMCSTORED | MODIFY PARTITION partition_name UNIMCSTORED | REDISANYVALUE ``` > - **ADD table\_constraint \[ NOT VALID ]** > > 给表增加一个新的约束。 > > * **ADD table\_constraint\_using\_index** > > 根据已有唯一索引为表增加主键约束或唯一约束。 > > * **VALIDATE CONSTRAINT constraint\_name** > > 验证一个使用NOT VALID选项创建的检查类约束,通过扫描全表来保证所有记录都符合约束条件。如果约束已标记为有效时,什么操作也不会发生。 > > * **DROP CONSTRAINT \[ IF EXISTS ] constraint\_name \[ RESTRICT | CASCADE ]** > > 删除一个表上的约束。 > > * **CLUSTER ON index\_name** > > 为将来的CLUSTER(聚簇)操作选择默认索引。实际上并没有重新盘簇化处理该表。 > > * **SET WITHOUT CLUSTER** > > 从表中删除最新使用的CLUSTER索引。这样会影响将来那些没有声明索引的CLUSTER(聚簇)操作。 > > * **SET ( {storage\_parameter = value} \[, ... ] )** > > 修改表的一个或多个存储参数。 > > * **RESET ( storage\_parameter \[, ... ] )** > > 重置表的一个或多个存储参数。与SET一样,根据参数的不同可能需要重写表才能获得想要的效果。 > > * **OWNER TO new\_owner** > > 将表、序列、视图的属主改变成指定的用户。 > > * **SET TABLESPACE new\_tablespace** > > 这种形式将表空间修改为指定的表空间并将相关的数据文件移动到新的表空间。但是表上的所有索引都不会被移动,索引可以通过ALTER INDEX语法的SET TABLESPACE选项来修改索引的表空间。 > > * **SET {COMPRESS|NOCOMPRESS}** > > 修改表的压缩特性。表压缩特性的改变只会影响后续批量插入的数据的存储方式,对已有数据的存储毫无影响。也就是说,表压缩特性的修改会导致该表中同时存在着已压缩和未压缩的数据。行存表不支持压缩。 > > * **TO { GROUP groupname | NODE ( nodename \[, ... ] ) }** > > 此语法仅在扩展模式(GUC参数support\_extended\_features为on时)下可用。该模式谨慎打开,主要供内部扩容工具使用,一般用户不应使用该模式。 > > * **ADD NODE ( nodename \[, ... ] )** > > 此语法主要供内部扩容工具使用,一般用户不建议使用。 > > * **DELETE NODE ( nodename \[, ... ] )** > > 此语法主要供内部缩容工具使用,一般用户不建议使用。 > > * **DISABLE TRIGGER \[ trigger\_name | ALL | USER ]** > > 禁用trigger\_name所表示的单个触发器,或禁用所有触发器,或仅禁用用户触发器(此选项不包括内部生成的约束触发器,例如,可延迟唯一性和排除约束的约束触发器)。 > 应谨慎使用此功能,因为如果不执行触发器,则无法保证原先期望的约束的完整性。 > > * **ENABLE TRIGGER \[ trigger\_name | ALL | USER ]** > > 启用trigger\_name所表示的单个触发器,或启用所有触发器,或仅启用用户触发器。 > > * **ENABLE REPLICA TRIGGER trigger\_name** > > 触发器触发机制受配置变量[session\_replication\_role](../database_reference/statement_behavior.md#zh-cn_topic_0237124732_zh-cn_topic_0059779117_sffbd1c48d86b4c3fa3287167a7810216)的影响,当复制角色为“origin”(默认值)或“local”时,将触发简单启用的触发器。 > 配置为ENABLE REPLICA的触发器仅在会话处于“replica”模式时触发。 > > * **ENABLE ALWAYS TRIGGER trigger\_name** > 无论当前复制模式如何,配置为ENABLE ALWAYS的触发器都将触发。 > > * **DISABLE/ENABLE \[ REPLICA | ALWAYS ] RULE** > > 配置属于表的重写规则,已禁用的规则对系统来说仍然是可见的,只是在查询重写期间不被应用。语义为关闭/启动规则。由于关系到视图的实现,ON SELECT规则不可禁用。 配置为ENABLE REPLICA的规则将会仅在会话为"replica" 模式时启动,而配置为ENABLE ALWAYS的触发器将总是会启动,不考虑当前复制模式。规则触发机制也受配置变量[session\_replication\_role](../database_reference/statement_behavior.md#zh-cn_topic_0237124732_zh-cn_topic_0059779117_sffbd1c48d86b4c3fa3287167a7810216)的影响,类似于上述触发器。 > > * **DISABLE/ENABLE ROW LEVEL SECURITY** > > 开启或关闭表的行访问控制开关。 > 当开启行访问控制开关时,如果未在该数据表定义相关行访问控制策略,数据表的行级访问将不受影响;如果关闭表的行访问控制开关,即使定义了行访问控制策略,数据表的行访问也不受影响。详细信息参见[CREATE ROW LEVEL SECURITY POLICY](create_row_level_security_policy.md)章节。 > > * **NO FORCE/FORCE ROW LEVEL SECURITY** > > 强制开启或关闭表的行访问控制开关。 > 默认情况,表所有者不受行访问控制特性影响,但当强制开启表的行访问控制开关时,表的所有者(不包含系统管理员用户)会受影响。系统管理员可以绕过所有的行访问控制策略,不受影响。 > > * **ENCRYPTION KEY ROTATION** > > 透明数据加密密钥轮转。只有在数据库开启透明加密功能,并且表的enable\_tde选项为on时才可以进行表的数据加密密钥轮转。执行密钥轮转操作后,系统会自动向KMS申请创建新的密钥。密钥轮转后,使用旧密钥加密的数据仍使用旧密钥解密,新写入的数据使用新密钥加密。为保证加密数据安全,用户可根据加密表的新增数据量大小定期更新密钥,建议更新周期为两到三年。 > > * **INHERIT parent\_table** > > 将目标资料表加到指定的父资料表中成为新的子资料表。之后,针对父资料表的查询将会包含目标资料表的资料。要作为子资料表加入前,目标资料表必须已经包含父资料表的所有栏位。这些栏位必须具有可匹配的资料类别,并且如果他们在父资料表中具有NOT NULL的限制条件,那么他们必须在子资料表中也具有NOT NULL的限制条件。对于父资料表的所有CHECK限制条件,必须还有相对应的子资料表限制条件,除非父资料表中标记为不可继承。 > > * **NO INHERIT parent\_table** > > 从指定的父资料表的子资料表中产出目标资料表。针对父资料表的查询将不再包含从目标资料表中所产生的记录。 > > * **OF type\_name** > > 将表连接至一种复合类型,与CREATE TABLE OF选项创建表一样。表的字段的名称和类型必须精确匹配复合类型中的定义,不过oid系统字段允许不一样。表不能是从任何其他表继承的。这些限制确保CREATE TABLE OF选项允许一个相同的表定义。 > > * **NOT OF** > > 将一个与某类型进行关联的表进行关联的解除。 > > * **REPLICA IDENTITY { DEFAULT | USING INDEX index\_name | FULL | NOTHING }** > > 在逻辑复制场景下,指定该表的UPDATE和DELETE操作中旧元组的记录级别。 > > * DEFAULT记录主键的列的旧值,没有主键则不记录。 > * USING INDEX记录命名索引覆盖的列的旧值,这些值必须是唯一的、不局部的、不可延迟的,并且仅包括标记为NOT NULL的列。 > * FULL记录该行中所有列的旧值。 > * NOTHING不记录有关旧行的信息。 > > 在逻辑复制场景,解析该表的UPDATE和DELETE操作语句时,解析出的旧元组由以此方法记录的信息组成。对于有主键表该选项可设置为DEFAULT或FULL。对于无主键表该选项需设置为FULL,否则解码时旧元组将解析为空。一般场景不建议设置为NOTHING,旧元组会始终解析为空。 > > 即使指定DEFAULT或USING INDEX,当前Ustore表列的旧值中也可能包含该行所有列的旧值,只有旧值涉及toast该配置选项才会生效。另外针对Ustore表,选项NOTHING无效,实际效果等同于FULL。 > > * **COMMENT {=| } 'text'** > > 修改表对象的注释。 > > * **ALTER INDEX index\_name \[ VISBLE | INVISIBLE ]** > > 修改索引的可见性。 > > * **\[ \[ DEFAULT ] CHARACTER SET | CHARSET \[ = ] default\_charset ] \[ \[ DEFAULT ] COLLATE \[ = ] default\_collation ]** > > 修改表的默认字符集和默认字符序为指定的值。修改不会影响表中当前已经存在的列。 > > * **CONVERT TO CHARACTER SET | CHARSET charset \[ COLLATE collation ]** > > 修改表的默认字符集和默认字符序为指定的值,同时将表中的所有字符类型的字段的字符集和字符序设置为指定的值,并将字段里的数据转换为新字符集编码。 > > * **IMCSTORED \[ ( column\_name \[, ...] ) ]** > > 对全表或部分列行列转换。 > > * **MODIFY PARTITION partition\_name IMCSTORED \[ ( column\_name \[, ...] ) ]** > > 对分区表的指定分区或指定分区的部分列行列转换。 > > * **UNIMCSTORED** > > 对指定行表做全量列缓存清除。 > > * **MODIFY PARTITION partition\_name UNIMCSTORED** > > 对分区表的指定分区做列缓存清除。 > > * **REDISANYVALUE** > > 仅有语法支持,不实现功能。 其中列相关的操作column\_clause可以是以下子句之一: ``` ADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [ compress_mode ] [ COLLATE collation ] [column_constraint [ ... ] ] [ FIRST | AFTER column_name ] | ADD [ IF NOT EXISTS ] column_name data_type [ compress_mode ] [, ...] | MODIFY column_name data_type | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL | MODIFY [ COLUMN ] column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [{[ COLLATE collation ] | [ column_constraint ]} [ ... ] ][FIRST | AFTER column_name] | CHANGE [ COLUMN ] old_column_name new_column_name data_type [ CHARACTER SET | CHARSET [ = ] charset ] [{[ COLLATE collation ] | [column_constraint ]} [ ... ] ] [FIRST | AFTER column_name] | DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ] | ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ] | ALTER [ COLUMN ] column_name { SET DEFAULT expression | DROP DEFAULT } | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS [PERCENT] integer | ADD STATISTICS (( column_1_name, column_2_name [, ...] )) | DELETE STATISTICS (( column_1_name, column_2_name [, ...] )) | ALTER [ COLUMN ] column_name SET ( {attribute_option = value} [, ... ] ) | ALTER [ COLUMN ] column_name RESET ( attribute_option [, ... ] ) | ALTER [ COLUMN ] column_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN } | ALTER [ COLUMN ] column_name ADD GENERATED generated_when AS IDENTITY [ ( seq_options) ] | ALTER [ COLUMN ] column_name alter_identity_column_options [ ... ] | ALTER [ COLUMN ] column_name DROP IDENTITY [ IF EXISTS ] ``` > * **ADD \[ COLUMN ] \[ IF NOT EXISTS ] column\_name data\_type \[ CHARACTER SET | CHARSET \[ = ] charset ] \[ compress\_mode ] \[ COLLATE collation ] \[ column\_constraint \[ ... ] ] \[ FIRST | AFTER column\_name]** > > 向表中增加一个新的字段。用ADD COLUMN增加一个字段,所有表中现有行都初始化为该字段的缺省值(如果没有声明DEFAULT子句,值为NULL)。其中FIRST | AFTER column\_name表示新增字段到某个位置。如果指定了IF NOT EXISTS子句,新增字段与表中已有字段重复时将不会抛出错误。 > > * **ADD ( { \[ IF NOT EXISTS ] column\_name data\_type \[ compress\_mode ] } \[, ...] )** > > 向表中增加多列。 > > * **MODIFY ( { column\_name data\_type } \[, ...] )** > > 修改表已存在字段的数据类型。 > > 在 A兼容模式下,如果表数据不为空,则不允许修改`numeric`类型的`scale`为更小。 > > 在 A兼容模式下,设置GUC参数`set behavior_compat_options = 'float_as_numeric';`后,如果表中数据不为空,则不允许修改`float(p)`的精度`precision`为更小值,不允许修改`float(p)`为其它类型。 > > * **MODIFY column\_name \[ CONSTRAINT constraint\_name ] NOT NULL \[ ENABLE ] \[, ...]** > > 为表的某列添加NOT NULL约束,默认启用约束。加上ENABLE也表示默认启用约束。目前暂不支持禁用约束选项。 > > * **MODIFY column\_name \[ CONSTRAINT constraint\_name ] NULL \[, ...]** > > 为表的某列移除NOT NULL约束。 > > * **MODIFY \[ COLUMN ] column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[{\[ COLLATE collation ] | \[ column\_constraint ]} \[ ... ] ] \[FIRST | AFTER column\_name]** > > 修改表已存在字段的定义,将用新定义替换字段原定义,原字段上的索引、独立对象约束(例如:主键、唯一键、CHECK约束等)不会被删除。\[FIRST | AFTER column\_name]语法表示修改字段定义的同时修改字段在表中的位置。 > > 此语法只能在参数sql\_compatibility='B'时使用。不支持列存表,不支持外表,不支持修改加密字段,不支持修改分区键字段的数据类型和排序规则,不支持修改规则引用的字段的数据类型和排序规则,不支持修改物化视图引用的字段的数据类型和排序规则。 > > 被修改数据类型或排序规则的字段如果被一个生成列引用,这个生成列的数据将会重新生成。 > > 被修改字段若被一些对象依赖(比如:索引、独立对象约束、视图、触发器、行级访问控制策略等),修改字段过程中将会重建这些对象。若被修改后字段定义违反此类对象的约束,修改操作会失败,比如:修改作为视图结果列的字段的数据类型。请修改字段前评估这类影响。 > > 被修改字段若被一些对象调用(比如:自定义函数、存储过程等),修改字段不会处理这些对象。修改字段完毕后,这些对象有可能出现不可用的情况,请修改字段前评估这类影响。 > > 修改字段的字符集或字符序会将字段中的数据转换为新的字符集进行编码。 > > 此子句与上一子句中“MODIFY column\_name data\_type”部分语法相同,语义功能不同,当GUC参数b\_format\_behavior\_compat\_options含有'enable\_modify\_column'选项时,将按照此子句功能处理。 > > 不支持列的identity属性添加/修改和删除。 > > * **CHANGE \[ COLUMN ] old\_column\_name new\_column\_name data\_type \[ CHARACTER SET | CHARSET charset ] \[{\[ COLLATE collation ] | \[ column\_constraint ]} \[ ... ] ] \[FIRST | AFTER column\_name]** > > 修改表已存在字段的名称和定义,字段新名称不能是已有字段的名称,将用新名称和定义替换字段原名称和定义原字段上的索引、独立对象约束(例如:主键、唯一键、CHECK约束)等不会被删除。\[FIRST | AFTER column\_name]语法表示修改字段名称和定义的同时修改字段在表中的位置。 > > 此语法只能在参数sql\_compatibility='B'时使用。不支持列存表,不支持外表。不支持修改加密字段,不支持修改分区键字段的数据类型和排序规则,不支持修改规则引用的字段的数据类型和排序规则,不支持修改物化视图引用的字段的数据类型和排序规则 > > 被修改数据类型或排序规则的字段如果被一个生成列引用,这个生成列的数据将会重新生成。 > > 被修改字段若被一些对象依赖(比如:索引、独立对象约束、视图、触发器、行级访问控制策略等),修改字段过程中将会重建这些对象。若被修改后字段定义违反此类对象的约束,修改操作会失败,比如:修改作为视图结果列的字段的数据类型。请修改字段前评估这类影响。 > > 被修改字段若被一些对象调用(比如:自定义函数、存储过程等),修改字段不会处理这些对象。修改字段名称后,这些对象有可能出现不可用的情况,请修改字段前评估这类影响。 > > 修改字段的字符集或字符序会将字段中的数据转换为新的字符集进行编码。 > > 不支持列的identity属性添加/修改和删除。 > > * **DROP \[ COLUMN ] \[ IF EXISTS ] column\_name \[ RESTRICT | CASCADE ]** > > 从表中删除一个字段,和这个字段相关的索引和表约束也会被自动删除。如果任何表之外的对象依赖于这个字段,必须声明CASCADE ,比如视图。 > > DROP COLUMN命令并不是物理上把字段删除,而只是简单地把它标记为对SQL操作不可见。随后对该表的插入和更新将在该字段存储一个NULL。因此,删除一个字段是很快的,但是它不会立即释放表在磁盘上的空间,因为被删除了的字段占据的空间还没有回收。这些空间将在执行VACUUM时而得到回收。 > > * **ALTER \[ COLUMN ] column\_name \[ SET DATA ] TYPE data\_type \[ COLLATE collation ] \[ USING expression ]** > > 改变表字段的数据类型。该字段涉及的索引和简单的表约束将被自动地转换为使用新的字段类型,方法是重新分析最初提供的表达式。 > > ALTER TYPE要求重写整个表的特性有时候是一个优点,因为重写的过程消除了表中没用的空间。比如,要想立刻回收被一个已经删除的字段占据的空间,最快的方法是 > > ``` > ALTER TABLE table ALTER COLUMN anycol TYPE anytype; > ``` > > 这里的anycol是任何在表中还存在的字段,而anytype是和该字段的原类型一样的类型。这样的结果是在表上没有任何可见的语意的变化,但是这个命令强制重写,这样就删除了不再使用的数据。 > > - **ALTER \[ COLUMN ] column\_name { SET DEFAULT expression | DROP DEFAULT }** > > 为一个字段设置或者删除缺省值。请注意缺省值只应用于随后的INSERT命令,它们不会修改表中已经存在的行。也可以为视图创建缺省,这个时候它们是在视图的ON INSERT规则应用之前插入到INSERT句中的。 > > - **ALTER \[ COLUMN ] column\_name { SET | DROP } NOT NULL** > > 修改一个字段是否允许NULL值或者拒绝NULL值。如果表在字段中包含非NULL,则只能使用SET NOT NULL。 > > - **ALTER \[ COLUMN ] column\_name SET STATISTICS \[PERCENT] integer** > > 为随后的ANALYZE操作设置针对每个字段的统计收集目标。目标的范围可以在0到10000之内设置。设置为-1时表示重新恢复到使用系统缺省的统计目标。 > > - **{ADD | DELETE} STATISTICS ((column\_1\_name, column\_2\_name \[, ...]))** > > 用于添加和删除多列统计信息声明(不实际进行多列统计信息收集),以便在后续进行全表或全库analyze时进行多列统计信息收集。如果关闭GUC参数enable\_functional\_dependency,每组多列统计信息最多支持32列;如果开启GUC参数enable\_functional\_dependency,每组多列统计信息最多支持4列。不支持添加/删除多列统计信息声明的表:系统表、外表。 > > - **ALTER \[ COLUMN ] column\_name SET ( {attribute\_option = value} \[, ... ] )** > **ALTER \[ COLUMN ] column\_name RESET ( attribute\_option \[, ... ] )** > > 设置/重置属性选项。 > > 目前,属性选项只定义了n\_distinct和n\_distinct\_inherited。n\_distinct影响表本身的统计值,而n\_distinct\_inherited影响表及其继承子表的统计。目前,只支持SET/RESET n\_distinct参数,禁止SET/RESET n\_distinct\_inherited参数。 > > - **ALTER \[ COLUMN ] column\_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }** > > 为一个字段设置存储模式。这个设置控制这个字段是内联保存还是保存在一个附属的表里,以及数据是否要压缩。仅支持对行存表的设置;对列存表没有意义,执行时报错。SET STORAGE本身并不改变表上的任何东西,只是设置将来的表操作时,建议使用的策略。 > > - **ALTER \[ COLUMN ] column\_name ADD GENERATED generated\_when AS IDENTITY \[ ( seq\_options) ]** > > 添加identity属性,同时可以指定identity列的起始值,步长,最大值,最小值等属性。 > > - **ALTER \[ COLUMN ] column\_name alter\_identity\_column\_options \[ ... ]** > > 修改identity列的属性,序列的起始值,最大值,最小值,步长等。 > > - **ALTER \[ COLUMN ] column\_name DROP IDENTITY \[ IF EXISTS ]** > > 删除某列的identity属性,如果列没有identity属性则报错,如果声明了`IF EXISTS`语法则会跳过;成功删除后,identity列所拥有的序列也会被删除,但是列的not null约束不变。 * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED [ ALWAYS | BY DEFAULT ] AS IDENTITY [ ( seq_options ) ] | GENERATED ALWAYS AS ( generation_expr ) [STORED] | ON UPDATE update_expr | { UNIQUE [KEY] index_parameters [ ON filegroup ] | PRIMARY KEY index_parameters [ ON filegroup ] } [ { ENABLE | DISABLE } [ VALIDATE | NOVALIDATE ] | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] [ ENABLE ] } | { ENABLE | DISABLE } [ VALIDATE | NOVALIDATE ] Constraint constraint_name } | AUTO_INCREMENT | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] | [ COMMENT 'text' ] ``` * 其中列的压缩可选项compress\_mode为: ``` [ DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS ] ``` * 其中根据已有唯一索引为表增加主键约束或唯一约束table\_constraint\_using\_index为: \[ CONSTRAINT constraint\_name ] { UNIQUE | PRIMARY KEY } USING INDEX index\_name \[ ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE] ] \[ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ idx_name ] [ USING method ] ( { { column_name [ ( length ) ] | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] }[, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | FOREIGN KEY [ idx_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 其中索引参数index\_parameters为: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * 其中identity属性参数generated\_when为: ```EBNF ALWAYS | BY DEFAULT ``` * 其中identity属性序列参数seq\_options为: ```EBNF seq_option | OWNED BY name | RESTART [ WITH ] NumericOnly ; seq_option: { MAXVALUE | MINVALUE | START WITH | START | INCREMENT [ BY ] | CACHE } NumericOnly | { NOMAXVALUE | MINVALUE | NO MAXVALUE | NO MINVALUE | NOCYCLE | [ NO ] CYCLE } ``` * 其中修改identity属性参数alter\_identity\_column\_options为: ```EBNF RESTART [ WITH ] NumericOnly | SET GENERATED generated_when | SET seq_option ``` * 重命名表。对名称的修改不会影响所存储的数据。 ``` ALTER TABLE [ IF EXISTS ] [schema_name.]table_name RENAME TO [new_schema_name.]new_table_name; ``` * 重命名表中指定的列。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME [ COLUMN ] column_name TO new_column_name; ``` * 重命名表的约束。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name ) } RENAME CONSTRAINT constraint_name TO new_constraint_name; ``` * 设置表的所属模式。 ``` ALTER TABLE [ IF EXISTS ] table_name SET SCHEMA new_schema; ``` > \[!NOTE]说明 > > * 这种形式把表移动到另外一个模式。相关的索引、约束都跟着移动。目前序列不支持改变schema。 若该表拥有序列,需要将序列删除,重建,或者取消拥有关系, 才能将表schema更改成功。 > > * 要修改一个表的模式,用户必须在新模式上拥有CREATE权限。要把该表添加为一个父表的新子表,用户必须同时又是父表的所有者。要修改所有者,用户还必须是新的所有角色的直接或间接成员,并且该成员必须在此表的模式上有CREATE权限。这些限制规定了该用户不能做出了重建和删除表之外的事情。不过,系统管理员可以以任何方式修改任意表的所有权限。 > > * 除了RENAME和SET SCHEMA之外所有动作都可以捆绑在一个经过多次修改的列表中并行使用。比如,可以在一个命令里增加几个字段或修改几个字段的类型。对于大表,此种操作带来的效率提升更明显,原因在于只需要对该大表做一次处理。 > > * 增加一个CHECK或NOT NULL约束将会扫描该表,以保证现有的行符合约束要求。 > > * 用一个非空缺省值增加一个字段或者改变一个字段的现有类型会重写整个表。对于大表来说,这个操作可能会花很长时间,并且它还临时需要两倍的磁盘空间。 * 添加多个列。 ``` ALTER TABLE [ IF EXISTS ] table_name ADD ( [ IF NOT EXISTS ] { column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ]} [, ...] ); ``` * 更新多个列。 ``` ALTER TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type [ CHARACTER SET | CHARSET charset ] [{[ COLLATE collation ] | [ column_constraint ]} [ ... ] ] [FIRST | AFTER column_name] | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ``` * 对表timestamp列添加ON UPDATE属性。 ```sql ALTER TABLE table_name MODIFY column_name column_type ON UPDATE CURRENT_TIMESTAMP; ``` * 对表timestamp列删除ON UPDATE属性。 ```sql ALTER TABLE table_name MODIFY column_name column_type; ``` ## 参数说明 * **CONCURRENTLY** 使用在线DDL模式执行ALTER操作,只支持传统主备场景Astore、段页式的普通表、分区表进行修改列数据类型、修改行存压缩属性、添加列的约束(非空约束、范围约束)。 * **IF EXISTS** 如果不存在相同名称的表,不会抛出一个错误,而会发出一个通知,告知表不存在。 * **table\_name \[\*] | ONLY table\_name | ONLY ( table\_name )** table\_name是需要修改的表名。 若声明了ONLY选项,则只有那个表被更改。若未声明ONLY,该表及其所有子表都将会被更改。另外,可以在表名称后面显示地增加\*选项来指定包括子表,即表示所有后代表都被扫描,这是默认行为。 * **constraint\_name** * 在DROP CONSTRAINT操作中表示要删除的现有约束的名称。 * 在ADD CONSTRAINT操作中表示新增的约束名称。 > \[!TIP]须知 > > 对于新增约束,在B模式数据库下(即sql\_compatibility = 'B')constraint\_name为可选项,在其他模式数据库下,必须加上constraint\_name。 * **index\_name** 索引名称。 > \[!TIP]须知 > > 在ADD CONSTRAINT操作中: > > * index\_name仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 对于外键约束,constraint\_name和index\_name同时指定时,索引名为constraint\_name。 > * 对于唯一键约束,constraint\_name和index\_name同时指定时,索引名以index\_name。 * **USING method** 指定创建索引的方法。 取值范围参考[参数说明](create_index.md)中的USING method。 > \[!TIP]须知 > > 在ADD CONSTRAINT操作中: > > * USING method仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 在B模式下,未指定USING method时,对于Astore的存储方式,默认索引方法为btree;对于Ustore的存储方式,默认索引方法为ubtree。 * **ASC | DESC** ASC表示指定按升序排序(默认)。DESC指定按降序排序。 > \[!TIP]须知 > > 在ADD CONSTRAINT中,ASC|DESC只在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库不支持。 * **expression** 创建一个基于该表的一个或多个字段的表达式索引约束,必须写在圆括弧中。 > \[!TIP]须知 > > 表达式索引只在B模式数据库下支持(即sql\_compatibility = 'B'),其他模式数据库不支持。 * **storage\_parameter** 表的存储参数的名称。 创建索引新增一个选项: * parallel\_workers(int类型) 取值范围:\[0,32],0表示关闭并发。 表示创建索引时起的bgworker线程数量,例如2就表示将会起2个bgworker线程并发创建索引。 如果未设置,启动bgworker线程数量与表大小相关,一般不超过4个线程。 * hasuids(bool类型) 默认值:off 参数开启:更新表元组时,为元组分配表级唯一标识id。 * **new\_owner** 表新拥有者的名称。 * **new\_tablespace** 表所属新的表空间名称。 * **IF NOT EXISTS** 如果指定了IF NOT EXISTS子句,新增字段与表中已有字段重复时将不会抛出错误。 * **column\_name**、**column\_1\_name、 column\_2\_name** 现存的或新字段的名称。 * **data\_type** 新字段的类型,或者现存字段的新类型。 * **compress\_mode** 表字段的压缩可选项。该子句指定该字段优先使用的压缩算法。行存表不支持压缩。 * **charset** 只在B模式数据库下(即sql\_compatibility = 'B')支持该语法,其他模式数据库不支持。指定表字段的字符集,单独指定时会将字段的字符序设置为指定的字符集的默认字符序。 * **collation** 字段排序规则(字符序)名称。可选字段COLLATE指定了新字段的排序规则,如果省略,排序规则为新字段的默认类型。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 对于B模式数据库下(即sql\_compatibility = 'B')还支持utf8mb4\_bin、utf8mb4\_general\_ci、utf8mb4\_unicode\_ci、binary字符序,部分说明见表字段的字符集说明(参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](create_table.md#table8163190152))。 \[!NOTE]说明 > * 仅字符类型支持指定字符集,指定为binary字符集或字符序实际是将字符类型转化为对应的二进制类型,若类型映射不存在则报错。当前仅有TEXT类型转化为BLOB的映射。 > * 除binary字符集和字符序外,当前仅支持指定与数据库编码相同的字符集。 > * 未显式指定字段字符集或字符序时,若指定了表的默认字符集或字符序,字段字符集和字符序将从表上继承。若表的默认字符集或字符序不存在,当b\_format\_behavior\_compat\_options = 'default\_collation'时,字段的字符集和字符序将继承当前数据库的字符集及其对应的默认字符序。 > * 当修改的字符集或字符序对应的字符集与当前字段字符集不同时,会将字段中的数据转换为指定的字符集进行编码。 * **USING expression** USING子句声明如何从旧的字段值里计算新的字段值;如果省略,缺省从旧类型向新类型的赋值转换。如果从旧数据类型到新类型没有隐含或者赋值的转换,则必须提供一个USING子句。 > \[!NOTE]说明 > > ALTER TYPE的USING选项实际上可以声明涉及该行旧值的任何表达式,即它可以引用除了正在被转换的字段之外其他的字段。这样,就可以用ALTER TYPE语法做非常普遍性的转换。因为这个灵活性,USING表达式并没有作用于该字段的缺省值(如果有的话),结果可能不是缺省表达式要求的常量表达式。这就意味着如果从旧类型到新类型没有隐含或者赋值转换的话,即使存在USING子句,ALTER TYPE也可能无法把缺省值转换成新的类型。在这种情况下,应该用DROP DEFAULT先删除缺省,执行ALTER TYPE,然后使用SET DEFAULT增加一个合适的新缺省值。类似的考虑也适用于涉及该字段的索引和约束。 * **NOT NULL | NULL** 设置列是否允许空值。 * **integer** 带符号的整数常值。当使用PERCENT时表示按照表数据的百分比收集统计信息,integer的取值范围为0-100。 * **attribute\_option** 属性选项。 * **PLAIN | EXTERNAL | EXTENDED | MAIN** 字段存储模式。 * PLAIN必需用于定长的数值(比如integer)并且是内联的、不压缩的。 * MAIN用于内联、可压缩的数据。 * EXTERNAL用于外部保存、不压缩的数据。使用EXTERNAL将令在text和bytea字段上的子字符串操作更快,但付出的代价是增加了存储空间。 * EXTENDED用于外部的压缩数据,EXTENDED是大多数支持非PLAIN存储的数据的缺省。 * **CHECK ( expression )** 每次将要插入的新行或者将要被更新的行必须使表达式结果为真才能成功,否则会抛出一个异常并且不会修改数据库。 声明为字段约束的检查约束应该只引用该字段的数值,而在表约束里出现的表达式可以引用多个字段。 目前,CHECK表达式不能包含子查询也不能引用除当前行字段之外的变量。 * **DEFAULT default\_expr** 给字段指定缺省值。 缺省表达式的数据类型必须和字段类型匹配。 缺省表达式将被用于任何未声明该字段数值的插入操作。如果没有指定缺省值则缺省值为NULL 。 * **GENERATED \[ ALWAYS | BY DEFAULT ] AS IDENTITY \[ ( seq\_options ) ]** 该语句创建identity列,用于生成自增/自减的序列。 若在插入时不指定此列的值(或者指定为DEFAULT),则会默认生成。 当列定义为`GANERATED ALWAYS`时,若想插入用户值需要使用`OVERRIDING SYSTEM VALUE`子句,否则会报错,对于UPDATE只能更新为`DEFAULT`; 当列定义为`GANERATED BY DEFAULT`时,用户提供的值会优先于默认值。 `seq_options`可以用于指定序列的选项。 > \[!NOTE]说明 > > * 该列的数据类型仅为整型,NUMERIC类型,该列隐式包含`NOT NULL`约束。 > * 无法同时定义default,serial,auto\_increment,生成列,NULL约束。 > * 序列生成非事务操作,当列/表约束检查失败,触发器失败时该列已生成的值不会回滚。 > * 用户自定义的值不会影响该列的下一个值的生成, > * 可以定义多列,但同一列不能重复定义。 > * 不支持分区表。 * **GENERATED ALWAYS AS ( generation\_expr ) \[STORED]** 该子句将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,STORED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > > * STORED关键字可省略,与不省略STORED语义相同。 > * 生成表达式不能以任何方式引用当前行以外的其他数据。生成表达式不能引用其他生成列,不能引用系统列。生成表达式不能返回结果集,不能使用子查询,不能使用聚集函数,不能使用窗口函数。生成表达式调用的函数只能是不可变(IMMUTABLE)函数。 > * 不能为生成列指定默认值。 > * 生成列不能作为分区键的一部分。 > * 生成列不能和ON UPDATE约束字句的CASCADE,SET NULL,SET DEFAULT动作同时指定。生成列不能和ON DELETE约束字句的SET NULL,SET DEFAULT动作同时指定。 > * 修改和删除生成列的方法和普通列相同。删除生成列依赖的普通列,生成列被自动删除。不能改变生成列所依赖的列的类型。 > * 生成列不能被直接写入。在INSERT或UPDATE命令中, 不能为生成列指定值, 但是可以指定关键字DEFAULT。 > * 生成列的权限控制和普通列一样。 > * 列存表、内存表MOT不支持生成列。外表中仅postgres\_fdw支持生成列。 * **UNIQUE \[KEY] index\_parameters** **UNIQUE ( column\_name \[ ( length ) ] \[, ... ] ) index\_parameters** UNIQUE约束表示表里的一个或多个字段的组合必须在全表范围内唯一。 UNIQUE KEY只能在sql\_compatibility='B'时使用,与UNIQUE语义相同。 column\_name(length)是前缀键,详见:[前缀键说明](create_index.md#前缀键说明)。 * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** 主键约束表明表中的一个或者一些字段只能包含唯一(不重复)的非NULL值。 * **REFERENCES reftable \[ ( refcolum ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (column constraint)** **FOREIGN KEY ( column\_name \[, ... ] ) REFERENCES reftable \[ ( refcolumn \[, ... ] ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (table constraint)** 外键约束要求新表中一列或多列构成的组应该只包含、匹配被参考表中被参考字段值。若省略refcolum,则将使用reftable的主键。被参考列应该是被参考表中的唯一字段或主键。外键约束不能被定义在临时表和永久表之间。 参考字段与被参考字段之间存在三种类型匹配,分别是: * MATCH FULL:不允许一个多字段外键的字段为NULL,除非全部外键字段都是NULL。 * MATCH SIMPLE(缺省):允许任意外键字段为NULL。 * MATCH PARTIAL:目前暂不支持。 另外,当被参考表中的数据发生改变时,某些操作也会在新表对应字段的数据上执行。ON DELETE子句声明当被参考表中的被参考行被删除时要执行的操作。ON UPDATE子句声明当被参考表中的被参考字段数据更新时要执行的操作。对于ON DELETE子句、ON UPDATE子句的可能动作: * NO ACTION(缺省):删除或更新时,创建一个表明违反外键约束的错误。若约束可推迟,且若仍存在任何引用行,那这个错误将会在检查约束的时候产生。 * RESTRICT:删除或更新时,创建一个表明违反外键约束的错误。与NO ACTION相同,只是动作不可推迟。 * CASCADE:删除新表中任何引用了被删除行的行,或更新新表中引用行的字段值为被参考字段的新值。 * SET NULL:设置引用字段为NULL。 * SET DEFAULT:设置引用字段为它们的缺省值。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 * **DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE** 设置该约束是否可推迟。 * DEFERRABLE:可以推迟到事务结尾使用SET CONSTRAINTS命令检查。 * NOT DEFERRABLE:在每条命令之后马上检查。 * INITIALLY IMMEDIATE:那么每条语句之后就立即检查它。 * INITIALLY DEFERRED:只有在事务结尾才检查它。 > \[!NOTE]说明Ustore表不支持新增 DEFERRABLE 以及 INITIALLY DEFERRED 约束。 * **PARTIAL CLUSTER KEY** 局部聚簇存储,列存表导入数据时按照指定的列(单列或多列),进行局部排序。 * **WITH ( {storage\_parameter = value} \[, ... ] )** 为表或索引指定一个可选的存储参数,详见[CREATE TABLE](create_table.md)语法相关字段的介绍。 > \[!NOTE]说明 > > * 行存表支持修改行存压缩参数,包括COMPRESSTYPE、COMPRESS\_LEVEL、COMPRESS\_CHUNK\_SIZE、COMPRESS\_PREALLOC\_CHUNKS、COMPRESS\_BYTE\_CONVERT、COMPRESS\_DIFF\_CONVERT,修改会对表做重建,修改后对原有数据、修改对已有数据、变更数据、新增数据同时生效。(仅支持Astore和Ustore下的普通表和分区表) > * 修改行存压缩参数时,修改后的行存压缩参数需要满足建表时各行存压缩参数的数据范围和参数间的约束。 > * 分区表不支持修改分区级别的行存压缩参数,只能修改整个表的行存压缩属性,修改对所有分区生效。 > * 修改行存压缩参数时会重写整个表,期间对表加八级锁。 > * 修改行存压缩参数时会重建表, 如果表的数据库较大,该过程可能花费较长时间 > * 重建表期间openGauss会先生成新的数据文件,再删除旧的数据文件,需要事先保证有足够的空闲物理空间。 * **tablespace\_name** 索引所在表空间的名称。 * **COMPRESS|NOCOMPRESS** * NOCOMPRESS:如果指定关键字NOCOMPRESS则不会修改表的现有压缩特性。 * COMPRESS:如果指定COMPRESS关键字,则对该表进行批量插入元组时触发该特性。行存表不支持压缩。 * **new\_table\_name** 修改后新的表名称。 * **new\_column\_name** 表中指定列修改后新的列名称。 * **new\_constraint\_name** 修改后表约束的新名称。 * **new\_schema** 修改后新的模式名称。 * **CASCADE** 级联删除依赖于被依赖字段或者约束的对象(比如引用该字段的视图)。 * **RESTRICT** 如果字段或者约束还有任何依赖的对象,则拒绝删除该字段。这是缺省行为。 * **FIRST** 新增列或修改列到第一位。 * **AFTER** **column\_name** 新增列或修改列到column\_name之后。 > \[!NOTE]说明 > > * 列存表不支持FIRST | AFTER column\_name。 > * 仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库不支持。 > * 加密列不支持FIRST | AFTER column\_name。 > * 有规则依赖的表不支持改变表列的位置(包括新增和修改导致列位置的变化)。 > * 外表不支持FIRST | AFTER column\_name。 > * SET类型的字段不支持修改到指定位置。 * **schema\_name** 表所在的模式名称。 * **VISIBLE | INVISIBLE** 指定索引是否可见,如果没有声明则默认为VISIBLE。 * **\[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset** 仅在sql\_compatibility='B'时支持该语法。修改表的默认字符集,单独指定时会将表的默认字符序设置为指定的字符集的默认字符序。 * **\[DEFAULT] COLLATE \[ = ] default\_collation** 仅在sql\_compatibility='B'时支持该语法。修改表的默认字符序,单独指定时会将表的默认字符集设置为指定的字符序对应的字符集。字符序参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](create_table.md#table8163190152)。 > \[!NOTE]说明 > 未显式指定表的字符集或字符序时,若指定了模式的默认字符集或字符序,表字符集和字符序将从模式上继承。若模式的默认字符集或字符序不存在,当b\_format\_behavior\_compat\_options = 'default\_collation'时,表的字符集和字符序将继承当前数据库的字符集及其对应的默认字符序。 ## 示例 请参考CREATE TABLE的[示例](create_table.md#zh-cn_topic_0283137629_zh-cn_topic_0237122117_zh-cn_topic_0059778169_s86758dcf05d442d2a9ebd272e76ed1b8)。 * add column first/after示例 ```sql -- 创建B模式数据库。 openGauss=# create database test_first_after dbcompatibility 'b'; openGauss=# \c test_first_after -- 创建表t1并插入数据。 openGauss=# drop table if exists t1 cascade; openGauss=# create table t1(f1 int, f2 varchar(20), f3 timestamp, f4 bit(8), f5 bool); openGauss=# insert into t1 values(1, 'a', '2022-11-08 19:56:10.158564', x'41', true), (2, 'b', '2022-11-09 19:56:10.158564', x'42', false); -- 指定位置新增字段 openGauss=# alter table t1 add f6 clob first; openGauss=# alter table t1 add f7 blob after f2; openGauss=# alter table t1 add f8 int, add f9 text first, add f10 float after f3; -- 查询t1表结构 openGauss=# \d+ t1 -- 查询t1表数据 openGauss=# select * from t1; -- 修改字段到指定位置 openGauss=# alter table t1 modify f3 timestamp first; openGauss=# alter table t1 modify f1 int after f5; -- 查询t1表结构 openGauss=# \d+ t1 -- 查询t1表数据 openGauss=# select * from t1; -- 修改t1表的默认字符集为utf8mb4,默认字符序为utf8mb4_bin openGauss=# alter table t1 charset utf8mb4 collate utf8mb4_bin; -- 将t1表中字符类型字段的数据转化为utf8mb4编码,并设置表和字段的字符序为utf8mb4_bin openGauss=# alter table t1 convert to charset utf8mb4 collate utf8mb4_bin; -- 为t1表新增字段并设置字段的字符集为utf8mb4,字符序为utf8mb4_bin openGauss=# alter table t1 add t10 varchar(20) charset utf8mb4 collate utf8mb4_bin; -- 修改t1表的t10字段的字符集为utf8mb4,字符序为utf8mb4_unicode_ci openGauss=# alter table t1 modify t10 varchar(20) charset utf8mb4 collate utf8mb4_unicode_ci; -- 创建INVISIBLE唯一索引 openGauss=# alter table t1 add constraint uniq_a unique (f1) invisible; -- 修改索引为VISIBLE openGauss=# alter table t1 alter index uniq_a visible; ``` * 添加/修改/删除identity列 ```sql openGauss=# create table t1 (a int generated always as identity, b int); NOTICE: CREATE TABLE will create implicit sequence "t1_a_seq" for serial column "t1.a" CREATE TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+---------------------------------------+---------+--------------+------------- a | integer | not null generated always as identity | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table t1 add column c numeric(20, 0) generated by default as identity; NOTICE: ALTER TABLE will create implicit sequence "t1_c_seq" for serial column "t1.c" ALTER TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------------+-------------------------------------------+---------+--------------+------------- a | integer | not null generated always as identity | plain | | b | integer | | plain | | c | numeric(20,0) | not null generated by default as identity | main | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table t1 alter column c set generated always set start with 10; ALTER TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------------+---------------------------------------+---------+--------------+------------- a | integer | not null generated always as identity | plain | | b | integer | | plain | | c | numeric(20,0) | not null generated always as identity | main | | Has OIDs: no Options: orientation=row, compression=no openGauss=# alter table t1 alter column b drop identity; ERROR: column "b" of relation "t1" is not an identity column openGauss=# alter table t1 alter column b drop identity if exists; NOTICE: column "b" of relation "t1" is not an identity column, skipping ALTER TABLE openGauss=# alter table t1 alter column c drop identity; ALTER TABLE openGauss=# alter table t1 alter column c add generated by default as identity(start with 10 increment 20); NOTICE: ALTER TABLE will create implicit sequence "t1_c_seq1" for serial column "t1.c" ALTER TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------------+-------------------------------------------+---------+--------------+------------- a | integer | not null generated always as identity | plain | | b | integer | | plain | | c | numeric(20,0) | not null generated by default as identity | main | | Has OIDs: no Options: orientation=row, compression=no ``` ## 相关链接 [CREATE TABLE](create_table.md),[DROP TABLE](drop_table.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_table_inherit.md --- # ALTER TABLE INHERIT ## Function Modify the inheritance table, including changing the regular table to an inheritance table and changing the inheritance table to a regular table. ## Precautions * Only tables that fully contain the parent table structure can be changed to child tables. * After terminating the inheritance relationship, although it is no longer a child table, there are still columns with the same name and type inherited from the parent table, and the existing data will not be deleted. * Modify the table structure of the parent table, and inherit the table accordingly. * Modify the data of the parent table, and the data of the inherited table will be updated together. * The not null, default, and check constraints inherited from the parent table cannot be deleted or modified. * The parent table deletes a column, the child table's column will not be deleted when using like parent\_name clause to create a table. * The parent table deletes a column, the child table columns will be deleted when not using like parent\_name clause to create a table. * Indexes, uniqueness, primary keys, and foreign key constraints which are using include all to inherit from the parent table can be deleted or modified. ## Syntax ``` ALTER TABLE table_name { inherit | no inherit } parent_name; ``` > * please refer to [alter table](alter_table.md) chapter to get more detailed parameter explanations. ## Parameter Description * **table\_name** Specifies the name of the child table. Value range: an existing partitioned table name. * **parent\_name** Specifies the name of parent table to inherit. Value range: an existing partition name. ## Examples ``` --Create two parent tables openGauss=# CREATE TABLE father ( id int NOT NULL, md_attr CHARACTER VARYING(32) UNIQUE, num int DEFAULT 2, salary REAL CHECK(SALARY > 0), CONSTRAINT pk_father_z83rgvsefn PRIMARY KEY (id) ); openGauss=# CREATE TABLE father2 (id int); --Create child tables openGauss=# CREATE TABLE child (id int); openGauss=# ALTER TABLE child inherit father2; openGauss=# CREATE TABLE child2() inherits(father); openGauss=# CREATE TABLE child3(like father) inherits(father); --Modify the table structure of the parent table, and the child tables will follow the changes. openGauss=# ALTER TABLE father alter COLUMN id type CHAR; --Parent tables drop column openGauss=# ALTER TABLE father DROP COLUMN if exists salary; --When not using like parent_name to create child table, the child table columns will be deleted openGauss=# \d+ child2 --When using like parent_name to create child table, the child table columns will not be deleted openGauss=# \d+ child3 --Termination of inheritance relationship openGauss=# ALTER TABLE child no inherit father2; --drop tables openGauss=# drop table father cascade; openGauss=# drop table child cascade; openGauss=# drop table father2 cascade; ``` **CREATE TABLE INHERITS**. ## Helpful Links [CREATE TABLE INHERITS](create_table_inherits.md) and [DROP TABLE](drop_table.md) --- --- url: /en/docs/latest/sql_reference/alter_table_inherit.md --- # ALTER TABLE INHERIT ## Function Modify the inheritance table, including changing the regular table to an inheritance table and changing the inheritance table to a regular table. ## Precautions * Only tables that fully contain the parent table structure can be changed to child tables. * After terminating the inheritance relationship, although it is no longer a child table, there are still columns with the same name and type inherited from the parent table, and the existing data will not be deleted. * Modify the table structure of the parent table, and inherit the table accordingly. * Modify the data of the parent table, and the data of the inherited table will be updated together. * The not null, default, and check constraints inherited from the parent table cannot be deleted or modified. * The parent table deletes a column, the child table's column will not be deleted when using like parent\_name clause to create a table. * The parent table deletes a column, the child table columns will be deleted when not using like parent\_name clause to create a table. * Indexes, uniqueness, primary keys, and foreign key constraints which are using include all to inherit from the parent table can be deleted or modified. ## Syntax ``` ALTER TABLE table_name { inherit | no inherit } parent_name; ``` > * please refer to [alter table](alter_table.md) chapter to get more detailed parameter explanations. ## Parameter Description * **table\_name** Specifies the name of the child table. Value range: an existing partitioned table name. * **parent\_name** Specifies the name of parent table to inherit. Value range: an existing partition name. ## Examples ``` --Create two parent tables openGauss=# CREATE TABLE father ( id int NOT NULL, md_attr CHARACTER VARYING(32) UNIQUE, num int DEFAULT 2, salary REAL CHECK(SALARY > 0), CONSTRAINT pk_father_z83rgvsefn PRIMARY KEY (id) ); openGauss=# CREATE TABLE father2 (id int); --Create child tables openGauss=# CREATE TABLE child (id int); openGauss=# ALTER TABLE child inherit father2; openGauss=# CREATE TABLE child2() inherits(father); openGauss=# CREATE TABLE child3(like father) inherits(father); --Modify the table structure of the parent table, and the child tables will follow the changes. openGauss=# ALTER TABLE father alter COLUMN id type CHAR; --Parent tables drop column openGauss=# ALTER TABLE father DROP COLUMN if exists salary; --When not using like parent_name to create child table, the child table columns will be deleted openGauss=# \d+ child2 --When using like parent_name to create child table, the child table columns will not be deleted openGauss=# \d+ child3 --Termination of inheritance relationship openGauss=# ALTER TABLE child no inherit father2; --drop tables openGauss=# drop table father cascade; openGauss=# drop table child cascade; openGauss=# drop table father2 cascade; ``` **CREATE TABLE INHERITS**. ## Helpful Links [CREATE TABLE INHERITS](create_table_inherits.md) and [DROP TABLE](drop_table.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_table_inherit.md --- # ALTER TABLE INHERIT ## 功能描述 修改继承表,包括将普通表改为继承表及将继承表改为普通表。 ## 注意事项 * 只有完全包含父表结构的表才能被改为子表。 * 解除继承关系后,虽然不再是子表,但还是留有从父表继承的同名属性列,已有的数据也不会被删除。 * 修改父表的表结构,继承表也跟随着变化。 * 修改父表的数据,继承表的数据会被一起更新。 * 从父表继承的非空、默认值和检查三种约束不能被删除或修改。 * 使用like parent\_name建表的话,父表删除了某列,子表列不会被删除。 * 不使用like parent\_name建表的话,父表删除了某列,子表列会被删除。 * 使用including all从父表继承的索引、唯一、主键、外键约束可以被删除或修改。 ## 语法格式 ``` ALTER TABLE table_name { inherit | no inherit } parent_name; ``` > * 更多参数细节说明可参考[ALTER TABLE](alter_table.md)章节。 ## 参数说明 * **table\_name** 继承表子表的表名。 取值范围:字符串,要符合标识符的命名规范。 * **parent\_name** 要继承的父表的表名。 取值范围:字符串,要符合标识符的命名规范。 ## 示例 ``` --创建两张父表 openGauss=# CREATE TABLE father ( id int NOT NULL, md_attr CHARACTER VARYING(32) UNIQUE, num int DEFAULT 2, salary REAL CHECK(SALARY > 0), CONSTRAINT pk_father_z83rgvsefn PRIMARY KEY (id) ); openGauss=# CREATE TABLE father2 (id int); --创建子表 openGauss=# CREATE TABLE child (id int); openGauss=# ALTER TABLE child inherit father2; openGauss=# CREATE TABLE child2() inherits(father); openGauss=# CREATE TABLE child3(like father) inherits(father); --修改父表的表结构,子表也跟随着变化。 openGauss=# ALTER TABLE father alter COLUMN id type CHAR; --父表删除列 openGauss=# ALTER TABLE father DROP COLUMN if exists salary; --不用like father建表的话,子表列会被删除 openGauss=# \d+ child2 --用like father建表的话,子表列不会被删除 openGauss=# \d+ child3 --解除继承关系 openGauss=# ALTER TABLE child no inherit father2; --删除表 openGauss=# drop table father cascade; openGauss=# drop table child cascade; openGauss=# drop table father2 cascade; ``` ## 相关链接 [CREATE TABLE INHERITS](create_table_inherits.md),[DROP TABLE](drop_table.md) --- --- url: /zh/docs/latest/sql_reference/alter_table_inherit.md --- # ALTER TABLE INHERIT ## 功能描述 修改继承表,包括将普通表改为继承表及将继承表改为普通表。 ## 注意事项 * 只有完全包含父表结构的表才能被改为子表。 * 解除继承关系后,虽然不再是子表,但还是留有从父表继承的同名属性列,已有的数据也不会被删除。 * 修改父表的表结构,继承表也跟随着变化。 * 修改父表的数据,继承表的数据会被一起更新。 * 从父表继承的非空、默认值和检查三种约束不能被删除或修改。 * 使用like parent\_name建表的话,父表删除了某列,子表列不会被删除。 * 不使用like parent\_name建表的话,父表删除了某列,子表列会被删除。 * 使用including all从父表继承的索引、唯一、主键、外键约束可以被删除或修改。 ## 语法格式 ``` ALTER TABLE table_name { inherit | no inherit } parent_name; ``` > * 更多参数细节说明可参考[ALTER TABLE](alter_table.md)章节。 ## 参数说明 * **table\_name** 继承表子表的表名。 取值范围:字符串,要符合标识符的命名规范。 * **parent\_name** 要继承的父表的表名。 取值范围:字符串,要符合标识符的命名规范。 ## 示例 ``` --创建两张父表 openGauss=# CREATE TABLE father ( id int NOT NULL, md_attr CHARACTER VARYING(32) UNIQUE, num int DEFAULT 2, salary REAL CHECK(SALARY > 0), CONSTRAINT pk_father_z83rgvsefn PRIMARY KEY (id) ); openGauss=# CREATE TABLE father2 (id int); --创建子表 openGauss=# CREATE TABLE child (id int); openGauss=# ALTER TABLE child inherit father2; openGauss=# CREATE TABLE child2() inherits(father); openGauss=# CREATE TABLE child3(like father) inherits(father); --修改父表的表结构,子表也跟随着变化。 openGauss=# ALTER TABLE father alter COLUMN id type CHAR; --父表删除列 openGauss=# ALTER TABLE father DROP COLUMN if exists salary; --不用like father建表的话,子表列会被删除 openGauss=# \d+ child2 --用like father建表的话,子表列不会被删除 openGauss=# \d+ child3 --解除继承关系 openGauss=# ALTER TABLE child no inherit father2; --删除表 openGauss=# drop table father cascade; openGauss=# drop table child cascade; openGauss=# drop table father2 cascade; ``` ## 相关链接 [CREATE TABLE INHERITS](create_table_inherits.md),[DROP TABLE](drop_table.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_table_partition.md --- # ALTER TABLE PARTITION ## Function **ALTER TABLE PARTITION** modifies table partitions, including adding, deleting, splitting, merging partitions, and altering partition attributes. ## Precautions * The tablespace of the added partition cannot be **PG\_GLOBAL**. * The name of the added partition must be different from the names of existing partitions in the partitioned table. * The key value of the added partition must be consistent with the type of partition keys in the partitioned table. * If a range partition is added, the key value of the added partition must be greater than the upper limit of the last range partition in the partitioned table. * If a list partition is added, the key value of the added partition cannot be the same as that of an existing partition. * Hash partitions cannot be added. * If the number of partitions in the target partitioned table has reached the maximum (**1048575**), partitions cannot be added. * If a partitioned table has only one partition, the partition cannot be deleted. * Use **PARTITION FOR()** to choose partitions. The number of specified values in the brackets should be the same as the column number in customized partitions, and they must be consistent. * The **Value** partitioned table does not support the **Alter Partition** operation. * Column-store tables and row-store tables cannot be partitioned. * Partitions cannot be added to an interval partitioned table. * Hash partitioned tables do not support splitting, combination, addition, and deletion of partitions. * List partitioned tables do not support partition splitting or partition combination. * Only the owner of a partitioned table or users granted with the **ALTER** permission on the partitioned table can run the **ALTER TABLE PARTITION** command. The system administrator has the permission to run the command by default. ## Syntax * Modify the syntax of the table partition. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ``` **action** indicates the following clauses for maintaining partitions. For the partition continuity when multiple clauses are used for partition maintenance, openGauss does **DROP PARTITION** and then **ADD PARTITION**, and finally runs the rest clauses in sequence. ``` move_clause | exchange_clause | row_clause | merge_clause | modify_clause | split_clause | add_clause | drop_clause | truncate_clause ``` * The **move\_clause** syntax is used to move the partition to a new tablespace. ``` MOVE PARTITION { partion_name | FOR ( partition_value [, ...] ) } TABLESPACE tablespacename ``` * The **exchange\_clause** syntax is used to move the data from a general table to a specified partition. ``` EXCHANGE PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } WITH TABLE {[ ONLY ] ordinary_table_name | ordinary_table_name * | ONLY ( ordinary_table_name )} [ { WITH | WITHOUT } VALIDATION ] [ VERBOSE ] [ UPDATE GLOBAL INDEX ] ``` The ordinary table and partition whose data is to be exchanged must meet the following requirements: * The number of columns of the ordinary table is the same as that of the partition, and their information should be consistent, including: column name, data type, constraint, collation information, storage parameter, and compression information. * The compression information of the ordinary table and partition should be consistent. * The number and information of indexes of the ordinary table and partition should be consistent. * The number and information of constraints of the ordinary table and partition should be consistent. * An ordinary table cannot be a temporary table. A partitioned table can only be a range partitioned table, list partitioned table, or hash partitioned table. * Ordinary tables and partitioned tables do not support dynamic data masking and row-level access control constraints. * List partitioned tables and hash partitioned tables cannot be column-store. * List, hash, and range partitioned tables support **exchange\_clause**. > \[!TIP]NOTICE > > * When the exchange is done, the data and tablespace of the ordinary table and partition are exchanged. The statistics about ordinary tables and partitions become unreliable, and they should be analyzed again. > * A non-partition key cannot be used to create a local unique index. Therefore, if an ordinary table contains a unique index, data cannot be exchanged. * The **row\_clause** syntax is used to set row movement of a partitioned table. ``` { ENABLE | DISABLE } ROW MOVEMENT ``` * The **merge\_clause** syntax is used to merge partitions into one. ``` MERGE PARTITIONS { partition_name } [, ...] INTO PARTITION partition_name [ TABLESPACE tablespacename ] [ UPDATE GLOBAL INDEX ] ``` * The **modify\_clause** syntax is used to set whether a partition index is usable. ``` MODIFY PARTITION partition_name { UNUSABLE LOCAL INDEXES | REBUILD UNUSABLE LOCAL INDEXES } ``` * The **split\_clause** syntax is used to split one partition into partitions. ``` SPLIT PARTITION { partition_name | FOR ( partition_value [, ...] ) } { split_point_clause | no_split_point_clause } [ UPDATE GLOBAL INDEX ] ``` * The **split\_point\_clause** syntax is used to specify a split point. ``` AT ( partition_value ) INTO ( PARTITION partition_name [ TABLESPACE tablespacename ] , PARTITION partition_name [ TABLESPACE tablespacename ] ) ``` > \[!TIP]NOTICE > > * Column-store tables and row-store tables cannot be partitioned. > * The size of the split point should be in the range of partition keys of the partition to be split. The split point can only split one partition into two new partitions. * The **no\_split\_point\_clause** syntax does not specify a split point. ``` INTO { ( partition_less_than_item [, ...] ) | ( partition_start_end_item [, ...] ) } ``` > \[!TIP]NOTICE > > * The first new partition key specified by **partition\_less\_than\_item** should be greater than that of the previously split partition (if any), and the last partition key specified by **partition\_less\_than\_item** should equal that of the partition being split. > * The first new partition key specified by **partition\_start\_end\_item** should equal that of the former partition (if any), and the last partition key specified by **partition\_start\_end\_item** should equal that of the partition being split. > * **partition\_less\_than\_item** supports a maximum of 4 partition keys, while **partition\_start\_end\_item** supports only one partition key. For details about the supported data types, see [PARTITION BY RANGE(parti...](create_table_partition.md). > * **partition\_less\_than\_item** and **partition\_start\_end\_item** cannot be used in the same statement. * The syntax of **partition\_less\_than\_item** is as follows: ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } [, ...] ) [ TABLESPACE tablespacename ] ``` * The syntax of **partition\_start\_end\_item** is as follows. For details about the constraints, see [partition\_start\_end\_item syntax](create_table_partition.md). ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` * The **add\_clause** syntax is used to add one or more partitions to a specified partitioned table. ``` ADD PARTITION ( partition_col1_name = partition_col1_value [, partition_col2_name = partition_col2_value ] [, ...] ) [ LOCATION 'location1' ] [ PARTITION (partition_colA_name = partition_colA_value [, partition_colB_name = partition_colB_value ] [, ...] ) ] [ LOCATION 'location2' ] ADD {partition_less_than_item | partition_start_end_item| partition_list_item } ``` The syntax of **partition\_list\_item** is as follows: ``` PARTITION partition_name VALUES (list_values_clause) [ TABLESPACE tablespacename ] ``` > \[!TIP]NOTICE > > * **partition\_list\_item** supports only one partition key. For details about the data types supported by **partition\_list\_item**, see [PARTITION BY LIST(partit...](create_table_partition.md). > * Interval and hash partitioned tables do not support partition addition. * The **drop\_clause** syntax is used to remove a partition from a specified partitioned table. ``` DROP PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` > \[!TIP]NOTICE > Hash partitioned table does not support partition deletion. * The **truncate\_clause** syntax is used to remove a specified partition from a partitioned table. ``` TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` * The syntax for modifying the name of a partition is as follows: ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME PARTITION { partion_name | FOR ( partition_value [, ...] ) } TO partition_new_name; ``` ## Parameter Description * **table\_name** Specifies the name of a partitioned table. Value range: an existing partitioned table name. * **partition\_name** Specifies the name of a partition. Value range: an existing partition name. * **tablespacename** Specifies which tablespace the partition moves to. Value range: an existing tablespace name. * **partition\_value** Specifies the key value of a partition. The value specified by **PARTITION FOR ( partition\_value \[, ...] )** can uniquely identify a partition. Value range: partition keys for the partition to be renamed. * **UNUSABLE LOCAL INDEXES** Sets all the indexes unusable in the partition. * **REBUILD UNUSABLE LOCAL INDEXES** Rebuilds all the indexes in the partition. * **ENABLE/DISABLE ROW MOVEMET** Sets row movement. If the tuple value is updated on the partition key during the **UPDATE** action, the partition where the tuple is located is altered. Setting this parameter enables error messages to be reported or movement of the tuple between partitions. Value range: * **ENABLE**: Row movement is enabled. * **DISABLE**: Row movement is disabled. The default value is **ENABLE**. * **ordinary\_table\_name** Specifies the name of the ordinary table whose data is to be migrated. Value range: an existing table name. * **{ WITH | WITHOUT } VALIDATION** Checks whether the ordinary table data meets the specified partition key range of the partition to be migrated. Value range: * **WITH**: checks whether the ordinary table data meets the partition key range of the partition to be migrated. If any data does not meet the required range, an error is reported. * **WITHOUT**: does not check whether the ordinary table data meets the partition key range of the partition to be migrated. The default value is **WITH**. The check is time consuming, especially when the data volume is large. Therefore, use **WITHOUT** when you are sure that the current ordinary table data meets the partition key range of the partition to be migrated. * **VERBOSE** When **VALIDATION** is **WITH**, if the ordinary table contains data that is out of the partition key range, insert the data to the correct partition. If there is no correct partition where the data can be inserted to, an error is reported. > \[!TIP]NOTICE > Only when **VALIDATION** is **WITH**, **VERBOSE** can be specified. * **partition\_new\_name** Specifies the new name of a partition. Value range: a string. It must comply with the identifier naming convention. ## Examples See [Examples](create_table_partition.md#en-us_topic_0283136653_en-us_topic_0237122119_en-us_topic_0059777586_s43dd49de892344bf89e6f56f17404842) in **CREATE TABLE PARTITION**. ## Helpful Links [CREATE TABLE PARTITION](create_table_partition.md) and [DROP TABLE](drop_table.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-alter-table-partition.md --- # ALTER TABLE PARTITION ## Function **ALTER TABLE PARTITION** modifies table partitions, including adding, deleting, splitting, merging partitions, and altering partition attributes. Compared with the kernel syntax, the rebuild, remove, check, repair, optimize, truncate, analyze, exchange of Dolphin is modified in B compatibility mode. ## Precautions * The tablespace of the added partition cannot be **PG\_GLOBAL**. * The name of the added partition must be different from the names of existing partitions in the partitioned table. * The key value of the added partition must be consistent with the type of partition keys in the partitioned table. * If a range partition is added, the key value of the added partition must be greater than the upper limit of the last range partition in the partitioned table. * If a list partition is added, the key value of the added partition cannot be the same as that of an existing partition. * Hash partitions cannot be added. * If the number of partitions in the target partitioned table has reached the maximum (**1048575**), partitions cannot be added. * If a partitioned table has only one partition, the partition cannot be deleted. * Use **PARTITION FOR()** to choose partitions. The number of specified values in the brackets should be the same as the column number in customized partitions, and they must be consistent. * The **Value** partitioned table does not support the **Alter Partition** operation. * Column-store tables and row-store tables do not support partition splitting. * Partitions cannot be added to an interval partitioned table. * Hash partitioned tables do not support splitting, combination, addition, and deletion of partitions. * List partitioned tables do not support partition splitting or partition combination. * Only the owner of a partitioned table or users granted with the **ALTER** permission on the partitioned table can run the **ALTER TABLE PARTITION** command. The system administrator has the permission to run the command by default. ## Syntax * Modify the syntax of the table partition. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ``` **action** indicates the following clauses for maintaining partitions. For partition continuity, when multiple clauses are used for partition maintenance, openGauss performs **DROP PARTITION** and then **ADD PARTITION**, and finally runs the rest clauses in sequence. ``` move_clause | exchange_clause | row_clause | merge_clause | modify_clause | split_clause | add_clause | drop_clause | truncate_clause | rebuild_clause | remove_clause | repair_clause | check_clause | optimize_clause ``` * The **move\_clause** syntax is used to move the partition to a new tablespace. ``` MOVE PARTITION { partion_name | FOR ( partition_value [, ...] ) } TABLESPACE tablespacename ``` * The **exchange\_clause** syntax is used to move the data from an ordinary table to a specified partition. ``` EXCHANGE PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } WITH TABLE {[ ONLY ] ordinary_table_name | ordinary_table_name * | ONLY ( ordinary_table_name )} [ { WITH | WITHOUT } VALIDATION ] [ VERBOSE ] [ UPDATE GLOBAL INDEX ] ``` The ordinary table and partition whose data is to be exchanged must meet the following requirements: * The number of columns of the ordinary table is the same as that of the partition, and their information should be consistent, including: column name, data type, constraint, collation information, storage parameter, and compression information. * The compressed information of the ordinary table and partitioned table should be consistent. * The number and information of indexes of the ordinary table and partition should be consistent. * The number and information of constraints of the ordinary table and partition should be consistent. * An ordinary table cannot be a temporary table. A partitioned table can only be a range partitioned table, list partitioned table, or hash partitioned table. * Ordinary tables and partitioned tables do not support dynamic data masking and row-level access control constraints. * List partitioned tables and hash partitioned tables cannot be column-store. * List, hash, and range partitioned tables support exchange\_clause. > \[!TIP]NOTICE > > * When the exchange is done, the data and tablespace of the ordinary table and partition are exchanged. The statistics about ordinary tables and partitions become unreliable, and they should be analyzed again. > * A non-partition key cannot be used to create a local unique index. Therefore, if an ordinary table contains a unique index, data cannot be exchanged. * The **row\_clause** syntax is used to set row movement of a partitioned table. ``` { ENABLE | DISABLE } ROW MOVEMENT ``` * The **merge\_clause** syntax is used to merge partitions into one. ``` MERGE PARTITIONS { partition_name } [, ...] INTO PARTITION partition_name [ TABLESPACE tablespacename ] [ UPDATE GLOBAL INDEX ] ``` * The **modify\_clause** syntax is used to set whether a partitioned index is available. ``` MODIFY PARTITION partition_name { UNUSABLE LOCAL INDEXES | REBUILD UNUSABLE LOCAL INDEXES } ``` * The **split\_clause** syntax is used to split one partition into different partitions. ``` SPLIT PARTITION { partition_name | FOR ( partition_value [, ...] ) } { split_point_clause | no_split_point_clause } [ UPDATE GLOBAL INDEX ] ``` * The **split\_point\_clause** syntax is used to specify a split point. ``` AT ( partition_value ) INTO ( PARTITION partition_name [ TABLESPACE tablespacename ] , PARTITION partition_name [ TABLESPACE tablespacename ] ) ``` > \[!TIP]NOTICE > > * Column-store tables and row-store tables cannot be partitioned. > * The size of the split point should be in the range of partition keys of the partition to be split. The split point can only split one partition into two new partitions. * The **no\_split\_point\_clause** syntax does not specify a split point. ``` INTO { ( partition_less_than_item [, ...] ) | ( partition_start_end_item [, ...] ) } ``` ``` >[!TIP]NOTICE > >- The first new partition key specified by partition\_less\_than\_item should be greater than that of the previously split partition (if any), and the last partition key specified by partition\_less\_than\_item should equal that of the partition being split. >- The start point (if any) of the first new partition specified by **partition\_start\_end\_item** must be equal to the partition key (if any) of the previous partition. The end point (if any) of the last partition specified by **partition\_start\_end\_item** must be equal to the partition key of the splitting partition. >- partition\_less\_than\_item supports a maximum of 4 partition keys, while partition\_start\_end\_item supports only one partition key. For details about the supported data types, see [PARTITION BY RANGE(parti....](https://docs.opengauss.org/en/docs/latest/sql_reference/create_table_partition.html) >- partition\_less\_than\_item and partition\_start\_end\_item cannot be used in the same statement. There is no restriction on different split statements. ``` * The syntax of **partition\_less\_than\_item** is as follows: ```` ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } [, ...] ) [ TABLESPACE tablespacename ] ``` ```` * The syntax of **partition\_start\_end\_item** is as follows. For details about the constraints, see [START END](https://docs.opengauss.org/en/docs/latest/sql_reference/create_table_partition.html). ```` ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` ```` * The **add\_clause** syntax is used to add one or more partitions to a specified partitioned table. ``` ADD PARTITION ( partition_col1_name = partition_col1_value [, partition_col2_name = partition_col2_value ] [, ...] ) [ LOCATION 'location1' ] [ PARTITION (partition_colA_name = partition_colA_value [, partition_colB_name = partition_colB_value ] [, ...] ) ] [ LOCATION 'location2' ] ADD {partition_less_than_item | partition_start_end_item| partition_list_item } ``` * The syntax of **partition\_list\_item** is as follows: ``` PARTITION partition_name VALUES (list_values_clause) [ TABLESPACE tablespacename ] ``` > \[!TIP]NOTICE > > * partition\_list\_item supports only one partition key. For details about the supported data types, see [PARTITION BY LIST(partit...](https://docs.opengauss.org/en/docs/latest/sql_reference/create_table_partition.html). > * Interval and hash partitioned tables do not support partition addition. * The **drop\_clause** syntax is used to remove a partition from a specified partitioned table. ``` DROP PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` > \[!TIP]NOTICE > Hash partitioned table does not support partition deletion. * The **truncate\_clause** syntax is used to remove a specified partition from a partitioned table. ``` TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` * The syntax for modifying the name of a partition is as follows: ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME PARTITION { partion_name | FOR ( partition_value [, ...] ) } TO partition_new_name; ``` * The syntax for recreating a partition is as follows: It is generally used to reclaim the space used by a partition, which has the same effect as deleting all records stored in the partition and then inserting them again. This is useful for defragmentation. Column-store tables are not supported, and level-2 partitions of level-2 partitioned tables cannot be specified. ``` REBUILD PARTITION { partition_name } [, ...] REBUILD PARTITION ALL ``` * The syntax for removing partitions from a table is as follows: Partitions are removed from a table but all data is retained. Column-store tables and segment tables are not supported. ``` REMOVE PARTITIONING ``` * The syntax for repairing, checking, and optimizing partitioned tables is as follows: It is used only for syntax and has no actual purpose. ``` CHECK PARTITION { partition_name } [, ...] CHECK PARTITION ALL REPAIR PARTITION { partition_name } [, ...] REPAIR PARTITION ALL OPTIMIZE PARTITION { partition_name } [, ...] OPTIMIZE PARTITION ALL ``` * The syntax for truncating partitions in a B-compatible database is as follows: The truncate operation deletes all data corresponding to the current partition. ``` TRUNCATE PARTITION { partition_name } [, ...] TRUNCATE PARTITION all ``` * The syntax for exchanging partitions in a B-compatible database is as follows: It can be used to exchange data between partitioned tables and ordinary tables. Data in ordinary tables and partitions is exchanged, and tablespace information in ordinary tables and partitions is exchanged. In this case, the statistics of ordinary tables and partitions become unreliable. You need to run ANALYZE on ordinary tables and partitions again. Level-2 partitions cannot be exchanged. ``` exchange partition partition_name with table table_name (without/with validation); ``` * The syntax for analyzing partitions in a B-compatible database is as follows: It collects statistics related to table contents. The execution plan generator uses the statistics to determine the most effective execution plan. Level-2 partitions cannot be specified using ANALYZE. ``` analyze partition { partition_name } [, ...] analyze partition all; ``` * The syntax for adding partitions in a B-compatible database is as follows: ``` ADD {partition_less_than_item | partition_start_end_item| partition_list_item } [, ...] ``` * The syntax for dropping partitions in a B-compatible database is as follows: ``` DROP PARTITION { { partition_name } [ UPDATE GLOBAL INDEX ] } [, ...] DROP SUBPARTITION { { partition_name } [ UPDATE GLOBAL INDEX ] } [, ...] ``` * The syntax for reorganizing partitions in a B-compatible database is as follows: It splits or merges specified partitions to reorganize the definition of partitions. Here are some key points for ALTER TABLE... REORGANIZE PARTITION to repartition: * The options used by PARTITION to determine the new partitioning scheme should follow the same rules as those used by the CREATE TABLE statement. * The new RANGE partitioning scheme cannot have any overlapping scope. A new LIST partitioning scheme cannot have any overlapping value sets. * The partition combination in the partition\_definitions list should have the same range or overall value set partition\_list as the composite partition named in the list. * For a table RANGE with partitions, you can only reorganize adjacent partitions. You cannot skip range partitions. * For the LIST partition, the value definition of the corresponding data cannot be deleted. * REORGANIZE PARTITION cannot be used to change the partition type used by a table. * The original table data cannot be lost. * The interval partition and value partition are not supported. ``` REORGANIZE PARTITION {{ partition_name } [, ...]} INTO {partition_less_than_item | partition_list_item } [, ...] ``` ## Parameter Description * **table\_name** Specifies the name of a partitioned table. Value range: an existing partitioned table name. * **partition\_name** Specifies the name of a partition. Value range: an existing partition name. * **tablespacename** Specifies which tablespace the partition moves to. Value range: an existing tablespace name * **partition\_value** Partition key value Values specified by **PARTITION FOR ( partition\_value \[, ...] )** can uniquely identify a partition. Value range: partition keys for the partition to be renamed. * **UNUSABLE LOCAL INDEXES** Sets all the indexes unusable in the partition. * **REBUILD UNUSABLE LOCAL INDEXES** Rebuilds all the indexes in the partition. * **ENABLE/DISABLE ROW MOVEMET** Sets row movement. If the tuple value is updated on the partition key during the **UPDATE** operation, the partition where the tuple is located is altered. Setting of this parameter enables error messages to be reported or movement of the tuple between partitions. Value range: * **ENABLE**: Row movement is enabled. * **DISABLE**: Row movement is disabled. The default value is **ENABLE**. * **ordinary\_table\_name** Specifies the name of the ordinary table whose data is to be migrated. Value range: an existing table name. * **{ WITH | WITHOUT } VALIDATION** Checks whether the ordinary table data meets the specified partition key range of the partition to be exchanged. Value range: * **WITH**: checks whether the common table data meets the partition key range of the partition to be exchanged. If any data does not meet the required range, an error is reported. * **WITHOUT**: does not check whether the common table data meets the partition key range of the partition to be exchanged. The default value is **WITH**. The check is time consuming, especially when the data volume is large. Therefore, use **WITHOUT** when you are sure that the current ordinary table data meets the partition key range of the partition to be migrated. * **VERBOSE** When **VALIDATION** is **WITH**, if the ordinary table contains data that is out of the partition key range, insert the data to the correct partition. If there is no correct partition where the data can be inserted to, an error is reported. > \[!TIP]NOTICE > Only when **VALIDATION** is **WITH**, **VERBOSE** can be specified. * **partition\_new\_name** Specifies the new name of a partition. Value range: String, which must comply with the naming convention. ## Examples For details, see [Examples](https://docs.opengauss.org/en/docs/latest/sql_reference/create_table_partition.html#en-us_topic_0283136653_en-us_topic_0237122119_en-us_topic_0059777586_s43dd49de892344bf89e6f56f17404842) in CREATE TABLE PARTITION. ## Helpful Links [CREATE TABLE PARTITION](https://docs.opengauss.org/en/docs/latest/sql_reference/create_table_partition.html), [DROP TABLE](https://docs.opengauss.org/en/docs/latest/sql_reference/drop_table.html) --- --- url: /en/docs/latest/sql_reference/alter_table_partition.md --- # ALTER TABLE PARTITION ## Function **ALTER TABLE PARTITION** modifies table partitions, including adding, deleting, splitting, merging partitions, and altering partition attributes. ## Precautions * The tablespace of the added partition cannot be **PG\_GLOBAL**. * The name of the added partition must be different from the names of existing partitions in the partitioned table. * The key value of the added partition must be consistent with the type of partition keys in the partitioned table. * If a range partition is added, the key value of the added partition must be greater than the upper limit of the last range partition in the partitioned table. * If a list partition is added, the key value of the added partition cannot be the same as that of an existing partition. * Hash partitions cannot be added. * If the number of partitions in the target partitioned table has reached the maximum (**1048575**), partitions cannot be added. * If a partitioned table has only one partition, the partition cannot be deleted. * Use **PARTITION FOR()** to choose partitions. The number of specified values in the brackets should be the same as the column number in customized partitions, and they must be consistent. * The **Value** partitioned table does not support the **Alter Partition** operation. * Column-store tables and row-store tables cannot be partitioned. * Partitions cannot be added to an interval partitioned table. * Hash partitioned tables do not support splitting, combination, addition, and deletion of partitions. * List partitioned tables do not support partition splitting or partition combination. * Only the owner of a partitioned table or users granted with the **ALTER** permission on the partitioned table can run the **ALTER TABLE PARTITION** command. The system administrator has the permission to run the command by default. ## Syntax * Modify the syntax of the table partition. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ``` **action** indicates the following clauses for maintaining partitions. For the partition continuity when multiple clauses are used for partition maintenance, openGauss does **DROP PARTITION** and then **ADD PARTITION**, and finally runs the rest clauses in sequence. ``` move_clause | exchange_clause | row_clause | merge_clause | modify_clause | split_clause | add_clause | drop_clause | truncate_clause ``` * The **move\_clause** syntax is used to move the partition to a new tablespace. ``` MOVE PARTITION { partion_name | FOR ( partition_value [, ...] ) } TABLESPACE tablespacename ``` * The **exchange\_clause** syntax is used to move the data from a general table to a specified partition. ``` EXCHANGE PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } WITH TABLE {[ ONLY ] ordinary_table_name | ordinary_table_name * | ONLY ( ordinary_table_name )} [ { WITH | WITHOUT } VALIDATION ] [ VERBOSE ] [ UPDATE GLOBAL INDEX ] ``` The ordinary table and partition whose data is to be exchanged must meet the following requirements: * The number of columns of the ordinary table is the same as that of the partition, and their information should be consistent, including: column name, data type, constraint, collation information, storage parameter, and compression information. * The compression information of the ordinary table and partition should be consistent. * The number and information of indexes of the ordinary table and partition should be consistent. * The number and information of constraints of the ordinary table and partition should be consistent. * An ordinary table cannot be a temporary table. A partitioned table can only be a range partitioned table, list partitioned table, or hash partitioned table. * Ordinary tables and partitioned tables do not support dynamic data masking and row-level access control constraints. * List partitioned tables and hash partitioned tables cannot be column-store. * List, hash, and range partitioned tables support **exchange\_clause**. > \[!TIP]NOTICE > > * When the exchange is done, the data and tablespace of the ordinary table and partition are exchanged. The statistics about ordinary tables and partitions become unreliable, and they should be analyzed again. > * A non-partition key cannot be used to create a local unique index. Therefore, if an ordinary table contains a unique index, data cannot be exchanged. * The **row\_clause** syntax is used to set row movement of a partitioned table. ``` { ENABLE | DISABLE } ROW MOVEMENT ``` * The **merge\_clause** syntax is used to merge partitions into one. ``` MERGE PARTITIONS { partition_name } [, ...] INTO PARTITION partition_name [ TABLESPACE tablespacename ] [ UPDATE GLOBAL INDEX ] ``` * The **modify\_clause** syntax is used to set whether a partition index is usable. ``` MODIFY PARTITION partition_name { UNUSABLE LOCAL INDEXES | REBUILD UNUSABLE LOCAL INDEXES } ``` * The **split\_clause** syntax is used to split one partition into partitions. ``` SPLIT PARTITION { partition_name | FOR ( partition_value [, ...] ) } { split_point_clause | no_split_point_clause } [ UPDATE GLOBAL INDEX ] ``` * The **split\_point\_clause** syntax is used to specify a split point. ``` AT ( partition_value ) INTO ( PARTITION partition_name [ TABLESPACE tablespacename ] , PARTITION partition_name [ TABLESPACE tablespacename ] ) ``` > \[!TIP]NOTICE > > * Column-store tables and row-store tables cannot be partitioned. > * The size of the split point should be in the range of partition keys of the partition to be split. The split point can only split one partition into two new partitions. * The **no\_split\_point\_clause** syntax does not specify a split point. ``` INTO { ( partition_less_than_item [, ...] ) | ( partition_start_end_item [, ...] ) } ``` > \[!TIP]NOTICE > > * The first new partition key specified by **partition\_less\_than\_item** should be greater than that of the previously split partition (if any), and the last partition key specified by **partition\_less\_than\_item** should equal that of the partition being split. > * The first new partition key specified by **partition\_start\_end\_item** should equal that of the former partition (if any), and the last partition key specified by **partition\_start\_end\_item** should equal that of the partition being split. > * **partition\_less\_than\_item** supports a maximum of 4 partition keys, while **partition\_start\_end\_item** supports only one partition key. For details about the supported data types, see [PARTITION BY RANGE(parti...](create_table_partition.md). > * **partition\_less\_than\_item** and **partition\_start\_end\_item** cannot be used in the same statement. * The syntax of **partition\_less\_than\_item** is as follows: ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } [, ...] ) [ TABLESPACE tablespacename ] ``` * The syntax of **partition\_start\_end\_item** is as follows. For details about the constraints, see [partition\_start\_end\_item syntax](create_table_partition.md). ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` * The **add\_clause** syntax is used to add one or more partitions to a specified partitioned table. ``` ADD PARTITION ( partition_col1_name = partition_col1_value [, partition_col2_name = partition_col2_value ] [, ...] ) [ LOCATION 'location1' ] [ PARTITION (partition_colA_name = partition_colA_value [, partition_colB_name = partition_colB_value ] [, ...] ) ] [ LOCATION 'location2' ] ADD {partition_less_than_item | partition_start_end_item| partition_list_item } ``` The syntax of **partition\_list\_item** is as follows: ``` PARTITION partition_name VALUES (list_values_clause) [ TABLESPACE tablespacename ] ``` > \[!TIP]NOTICE > > * **partition\_list\_item** supports only one partition key. For details about the data types supported by **partition\_list\_item**, see [PARTITION BY LIST(partit...](create_table_partition.md). > * Interval and hash partitioned tables do not support partition addition. * The **drop\_clause** syntax is used to remove a partition from a specified partitioned table. ``` DROP PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` > \[!TIP]NOTICE > Hash partitioned table does not support partition deletion. * The **truncate\_clause** syntax is used to remove a specified partition from a partitioned table. ``` TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` * The syntax for modifying the name of a partition is as follows: ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME PARTITION { partion_name | FOR ( partition_value [, ...] ) } TO partition_new_name; ``` ## Parameter Description * **table\_name** Specifies the name of a partitioned table. Value range: an existing partitioned table name. * **partition\_name** Specifies the name of a partition. Value range: an existing partition name. * **tablespacename** Specifies which tablespace the partition moves to. Value range: an existing tablespace name. * **partition\_value** Specifies the key value of a partition. The value specified by **PARTITION FOR ( partition\_value \[, ...] )** can uniquely identify a partition. Value range: partition keys for the partition to be renamed. * **UNUSABLE LOCAL INDEXES** Sets all the indexes unusable in the partition. * **REBUILD UNUSABLE LOCAL INDEXES** Rebuilds all the indexes in the partition. * **ENABLE/DISABLE ROW MOVEMET** Sets row movement. If the tuple value is updated on the partition key during the **UPDATE** action, the partition where the tuple is located is altered. Setting this parameter enables error messages to be reported or movement of the tuple between partitions. Value range: * **ENABLE**: Row movement is enabled. * **DISABLE**: Row movement is disabled. The default value is **ENABLE**. * **ordinary\_table\_name** Specifies the name of the ordinary table whose data is to be migrated. Value range: an existing table name. * **{ WITH | WITHOUT } VALIDATION** Checks whether the ordinary table data meets the specified partition key range of the partition to be migrated. Value range: * **WITH**: checks whether the ordinary table data meets the partition key range of the partition to be migrated. If any data does not meet the required range, an error is reported. * **WITHOUT**: does not check whether the ordinary table data meets the partition key range of the partition to be migrated. The default value is **WITH**. The check is time consuming, especially when the data volume is large. Therefore, use **WITHOUT** when you are sure that the current ordinary table data meets the partition key range of the partition to be migrated. * **VERBOSE** When **VALIDATION** is **WITH**, if the ordinary table contains data that is out of the partition key range, insert the data to the correct partition. If there is no correct partition where the data can be inserted to, an error is reported. > \[!TIP]NOTICE > Only when **VALIDATION** is **WITH**, **VERBOSE** can be specified. * **partition\_new\_name** Specifies the new name of a partition. Value range: a string. It must comply with the identifier naming convention. ## Examples See [Examples](create_table_partition.md#en-us_topic_0283136653_en-us_topic_0237122119_en-us_topic_0059777586_s43dd49de892344bf89e6f56f17404842) in **CREATE TABLE PARTITION**. ## Helpful Links [CREATE TABLE PARTITION](create_table_partition.md) and [DROP TABLE](drop_table.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-ALTER-TABLE-PARTITION.md --- # ALTER TABLE PARTITION ## 功能描述 修改表分区,包括增删分区、切割分区、合成分区以及修改分区属性等。 相比于内核语法,dolphin的rebuild,remove,check,repair,optimize,truncate,analyze,exchange,reorganize都做了B兼容模式下的特色修改。 ## 注意事项 * 添加分区的表空间不能是PG\_GLOBAL。 * 添加分区的名称不能与该分区表已有分区的名称相同。 * 添加分区的分区键值要和分区表的分区键的类型一致。 * 若添加RANGE分区,添加分区键值要大于分区表中最后一个范围分区的上边界。 * 若添加LIST分区,添加分区键值不能与现有分区键值重复。 * 不支持添加HASH分区。 * 如果目标分区表中已有分区数达到了最大值1048575,则不能继续添加分区。 * 当分区表只有一个分区时,不能删除该分区。 * 选择分区使用PARTITION FOR(),括号里指定值个数应该与定义分区时使用的列个数相同,并且一一对应。 * Value分区表不支持相应的Alter Partition操作。 * 列存分区表不支持切割分区。 * 间隔分区表不支持添加分区。 * 哈希分区表不支持切割分区,不支持合成分区,不支持添加和删除分区。 * 列表分区表不支持切割分区,不支持合成分区。 * 只有分区表的所有者或者被授予了分区表ALTER权限的用户有权限执行ALTER TABLE PARTITION命令,系统管理员默认拥有此权限。 ## 语法格式 * 修改表分区主语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | (ONLY) table_name | (ONLY) ( table_name )} action [, ... ]; ``` 其中action统指如下分区维护子语法。当存在多个分区维护子句时,保证了分区的连续性,无论这些子句的排序如何,openGauss总会先执行DROP PARTITION再执行ADD PARTITION操作,最后顺序执行其它分区维护操作。 ``` move_clause | exchange_clause | row_clause | merge_clause | modify_clause | split_clause | add_clause | drop_clause | truncate_clause | rebuild_clause | remove_clause | repair_clause | check_clause | optimize_clause ``` * move\_clause子语法用于移动分区到新的表空间。 ``` MOVE PARTITION { partion_name | FOR ( partition_value [, ...] ) } TABLESPACE tablespacename ``` * exchange\_clause子语法用于把普通表的数据迁移到指定的分区。 ``` EXCHANGE PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } WITH TABLE {[ (ONLY) ] ordinary_table_name | ordinary_table_name * | (ONLY) ( ordinary_table_name )} [ { WITH | WITHOUT } VALIDATION ] [ VERBOSE ] [ UPDATE GLOBAL INDEX ] ``` 进行交换的普通表和分区必须满足如下条件: * 普通表和分区的列数目相同,对应列的信息严格一致,包括:列名、列的数据类型、列约束、列的Collation信息、列的存储参数、列的压缩信息等。 * 普通表和分区的表压缩信息严格一致。 * 普通表和分区的索引个数相同,且对应索引的信息严格一致。 * 普通表和分区的表约束个数相同,且对应表约束的信息严格一致。 * 普通表不可以是临时表,分区表只能是范围分区表,列表分区表,哈希分区表。 * 普通表和分区表上不可以有动态数据脱敏,行访问控制约束。 * 列表分区表,哈希分区表不能是列存储。 * List/Hash/Range类型分区表支持exchange\_clause。 > \[!TIP]须知 > > * 完成交换后,普通表和分区的数据被置换,同时普通表和分区的表空间信息被置换。此时,普通表和分区的统计信息变得不可靠,需要对普通表和分区重新执行analyze。 > > * 由于非分区键不能建立本地唯一索引,只能建立全局唯一索引,所以如果普通表含有唯一索引时,会导致不能交换数据。 > > * 分区表的分区键包含表达式处理(例如:abs(column))的场景下,交换分区时不会对普通表的待迁移数据进行表达式处理,而且对原有数据直接适用分区。 * row\_clause子语法用于设置分区表的行迁移开关。 ``` { ENABLE | DISABLE } ROW MOVEMENT ``` * merge\_clause子语法用于把多个分区合并成一个分区。 ``` MERGE PARTITIONS { partition_name } [, ...] INTO PARTITION partition_name [ TABLESPACE tablespacename ] [ UPDATE GLOBAL INDEX ] ``` * modify\_clause子语法用于设置分区索引是否可用。 ``` MODIFY PARTITION partition_name { UNUSABLE LOCAL INDEXES | REBUILD UNUSABLE LOCAL INDEXES } ``` * split\_clause子语法用于把一个分区切割成多个分区。 ``` SPLIT PARTITION { partition_name | FOR ( partition_value [, ...] ) } { split_point_clause | no_split_point_clause } [ UPDATE GLOBAL INDEX ] ``` * 指定切割点split\_point\_clause的语法为。 ``` AT ( partition_value ) INTO ( PARTITION partition_name [ TABLESPACE tablespacename ] , PARTITION partition_name [ TABLESPACE tablespacename ] ) ``` > \[!TIP]须知 > > * 列存分区表不支持切割分区。 > > * 切割点的大小要位于正在被切割的分区的分区键范围内,指定切割点的方式只能把一个分区切割成两个新分区。 * 不指定切割点no\_split\_point\_clause的语法为。 ``` INTO { ( partition_less_than_item [, ...] ) | ( partition_start_end_item [, ...] ) } ``` ``` >[!TIP]须知 > >- 不指定切割点的方式,partition\_less\_than\_item指定的第一个新分区的分区键要大于正在被切割的分区的前一个分区(如果存在的话)的分区键,partition\_less\_than\_item指定的最后一个分区的分区键要等于正在被切割的分区的分区键大小。 > >- 不指定切割点的方式,partition\_start\_end\_item指定的第一个新分区的起始点(如果存在的话)必须等于正在被切割的分区的前一个分区(如果存在的话)的分区键,partition\_start\_end\_item指定的最后一个分区的终止点(如果存在的话)必须等于正在被切割的分区的分区键。 > >- partition\_less\_than\_item支持的分区键个数最多为4,而partition\_start\_end\_item仅支持1个分区键,其支持的数据类型参见[PARTITION BY RANGE\(parti...](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_table_partition.html#zh-cn_topic_0283136653_zh-cn_topic_0237122119_section1163224811518)。 > >- 在同一语句中partition\_less\_than\_item和partition\_start\_end\_item两者不可同时使用;不同split语句之间没有限制。 ``` * 分区项partition\_less\_than\_item的语法为。 ```` ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } [, ...] ) | MAXVALUE [ TABLESPACE tablespacename ] ``` ```` * 分区项partition\_start\_end\_item的语法为,其约束参见[START END语法描述](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_table_partition.html#zh-cn_topic_0283136653_zh-cn_topic_0237122119_section1163224811518)。 ```` ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE}) | MAXVALUE} | {START(partition_value)} | {END ({partition_value | MAXVALUE}) | MAXVALUE} } [TABLESPACE tablespace_name] ``` ```` * add\_clause子语法用于为指定的分区表添加一个或多个分区。 ``` ADD PARTITION ( partition_col1_name = partition_col1_value [, partition_col2_name = partition_col2_value ] [, ...] ) [ LOCATION 'location1' ] [ PARTITION (partition_colA_name = partition_colA_value [, partition_colB_name = partition_colB_value ] [, ...] ) ] [ LOCATION 'location2' ] ADD {partition_less_than_item | partition_start_end_item| partition_list_item } ``` * 分区项partition\_list\_item的语法如下。 ``` PARTITION partition_name VALUES [ IN ] (list_values_clause) [ TABLESPACE tablespacename ] ``` > \[!TIP]须知 > > * partition\_list\_item仅支持的1个分区键,其支持的数据类型参见[PARTITION BY LIST(partit...](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_table_partition.html#zh-cn_topic_0283136653_zh-cn_topic_0237122119_section1163224811518)。 > > * 间隔/哈希分区表不支持添加分区。 * drop\_clause子语法用于删除分区表中的指定分区。 ``` DROP PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` > \[!TIP]须知 > 哈希分区表不支持删除分区。 * truncate\_clause子语法用于清空分区表中的指定分区。 ``` TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` * 修改表分区名称的语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | (ONLY) table_name | (ONLY) ( table_name )} RENAME PARTITION { partion_name | FOR ( partition_value [, ...] ) } TO partition_new_name; ``` * 重建分区语法 一般用于回收分区使用空间,与删除存储在分区中的所有记录,然后重新插入它们的效果相同。这对于碎片整理很有用。 不支持列存表,不支持指定二级分区表的二级分区。 ``` REBUILD PARTITION { partition_name } [, ...] REBUILD PARTITION ALL ``` * 分区表remove partitioning语法 移除表中partition,但是保留所有数据。 不支持列存表和segment表。 ``` REMOVE PARTITIONING ``` * 分区表repair,check和optimize语法 仅支持语法,不做实际功能支持。 ``` CHECK PARTITION { partition_name } [, ...] CHECK PARTITION ALL REPAIR PARTITION { partition_name } [, ...] REPAIR PARTITION ALL OPTIMIZE PARTITION { partition_name } [, ...] OPTIMIZE PARTITION ALL ``` * Truncate分区语法 Truncate操作会删除当前分区对应的所有数据。 ``` TRUNCATE PARTITION { partition_name } [, ...] TRUNCATE PARTITION all ``` * exchange分区语法对齐 可以用来交换分区表和普通表的数据,普通表和分区的数据被置换,同时普通表和分区的表空间信息被置换。此时,普通表和分区的统计信息变得不可靠,需要对普通表和分区重新执行analyze。 不支持交换二级分区。 ``` exchange partition partition_name with table table_name (without/with validation); ``` * analyze分区语法对齐 用于收集与表内容相关的统计信息。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。 不支持analyze指定二级分区。 ``` analyze partition { partition_name } [, ...] analyze partition all; ``` * add分区语法。 ``` ADD {partition_less_than_item | partition_start_end_item| partition_list_item } [, ...] ``` * drop分区语法。 ``` DROP PARTITION { { partition_name } [ UPDATE GLOBAL INDEX ] } [, ...] DROP SUBPARTITION { { partition_name } [ UPDATE GLOBAL INDEX ] } [, ...] ``` * reorganize分区语法。 重新分割或融合指定分区,重新划分分区的定义。 以下是ALTER TABLE ... REORGANIZE PARTITION用于重新分区一些关键点: * PARTITION用于确定新分区方案的选项应遵循与CREATE TABLE语句所使用的规则相同的规则。 * 新的RANGE分区方案不能有任何重叠范围。一个新的LIST分区方案不能有任何重叠的值集。 * partition\_definitions列表中的分区组合应与清单中命名的组合分区具有相同的范围或整体值集partition\_list。 * 对于由分区的表RANGE,您只能重组相邻的分区。您不能跳过范围分区。 * 对于LIST分区,不可以删除已有对应数据的value值定义。 * 不能用于REORGANIZE PARTITION更改表使用的分区类型。 * 不可丢失原有表数据。 * 不支持interval分区,不支持value分区。 * 对于RANGE分区,不支持start end语法。 ``` REORGANIZE PARTITION {{ partition_name } [, ...]} INTO {partition_less_than_item | partition_list_item } [, ...] ``` ## 参数说明 * **table\_name** 分区表名。 取值范围:已存在的分区表名。 * **partition\_name** 分区名。 取值范围:已存在的分区名。 * **tablespacename** 指定分区要移动到哪个表空间。 取值范围:已存在的表空间名。 * **partition\_value** 分区键值。 通过PARTITION FOR ( partition\_value \[, ...] )子句指定的这一组值,可以唯一确定一个分区。 取值范围:需要进行重命名的分区的分区键的取值范围。 * **UNUSABLE LOCAL INDEXES** 设置该分区上的所有索引不可用。 * **REBUILD UNUSABLE LOCAL INDEXES** 重建该分区上的所有索引。 * **ENABLE/DISABLE ROW MOVEMET** 行迁移开关。 如果进行UPDATE操作时,更新了元组在分区键上的值,造成了该元组所在分区发生变化,就会根据该开关给出报错信息,或者进行元组在分区间的转移。 取值范围: * ENABLE:打开行迁移开关。 * DISABLE:关闭行迁移开关。 默认是打开状态。 * **ordinary\_table\_name** 进行迁移的普通表的名称。 取值范围:已存在的普通表名。 * **{ WITH | WITHOUT } VALIDATION** 在进行数据迁移时,是否检查普通表中的数据满足指定分区的分区键范围。 取值范围: * WITH:对于普通表中的数据要检查是否满足分区的分区键范围,如果有数据不满足,则报错。 * WITHOUT:对于普通表中的数据不检查是否满足分区的分区键范围。 默认是WITH状态。 由于检查比较耗时,特别是当数据量很大的情况下更甚。所以在保证当前普通表中的数据满足分区的分区键范围时,可以加上WITHOUT来指明不进行检查。 * **VERBOSE** 在VALIDATION是WITH状态时,如果检查出普通表有不满足要交换分区的分区键范围的数据,那么把这些数据插入到正确的分区,如果路由不到任何分区,再报错。 > \[!TIP]须知 > 只有在VALIDATION是WITH状态时,才可以指定VERBOSE。 * **partition\_new\_name** 分区的新名称。 取值范围:字符串,要符合标识符的命名规范。 ## 示例 请参考CREATE TABLE PARTITION的[示例](dolphin-CREATE-TABLE-PARTITION.md#zh-cn_topic_0283136653_zh-cn_topic_0237122119_zh-cn_topic_0059777586_s43dd49de892344bf89e6f56f17404842)。 ## 相关链接 [CREATE TABLE PARTITION](dolphin-CREATE-TABLE-PARTITION.md),[DROP TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/drop_table.html) --- --- url: /zh/docs/latest-lite/sql_reference/alter_table_partition.md --- # ALTER TABLE PARTITION ## 功能描述 修改表分区,包括增加/删除分区、切割/合并分区、清空分区、移动分区表空间、交换分区、重命名分区,以及修改分区属性等。 ## 注意事项 * 添加分区的表空间不能是PG\_GLOBAL。 * 添加分区的名称不能与该分区表已有分区的名称相同。 * 添加分区的分区键值要和分区表的分区键的类型一致。 * 若添加RANGE分区,添加分区键值要大于分区表中最后一个范围分区的上边界。 * 若添加LIST分区,添加分区键值不能与现有分区键值重复。 * 不支持添加HASH分区。 * 如果目标分区表中已有分区数达到了最大值1048575,则不能继续添加分区。 * 当分区表只有一个分区时,不能删除该分区。 * 选择分区使用PARTITION FOR(),括号里指定值个数应该与定义分区时使用的列个数相同,并且一一对应。 * Value分区表不支持相应的Alter Partition操作。 * 列存分区表不支持切割分区。 * 间隔分区表不支持添加分区。 * 哈希分区表不支持切割分区,不支持合成分区,不支持添加和删除分区。 * 列表分区表不支持切割分区,不支持合成分区。 * 只有分区表的所有者或者被授予了分区表ALTER权限的用户有权限执行ALTER TABLE PARTITION命令,系统管理员默认拥有此权限。 * 删除、切割、合并、清空、交换分区的操作会使Global索引失效,可以申明UPDATE GLOBAL INDEX子句同步更新索引。 * 如果删除、切割、合并、清空、交换分区操作不申明UPDATE GLOBAL INDEX子句,并发的DML业务有可能因为索引不可用而报错。 ## 语法格式 修改分区表分区包括修改表分区主语法、修改表分区名称的语法和重置分区ID的语法。 * 修改表分区主语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ``` 其中action统指如下分区维护子语法。当存在多个分区维护子句时,保证了分区的连续性,无论这些子句的排序如何,openGauss总会先执行DROP PARTITION再执行ADD PARTITION操作,最后顺序执行其它分区维护操作。 ``` move_clause | exchange_clause | row_clause | merge_clause | modify_clause | split_clause | add_clause | drop_clause | truncate_clause ``` * move\_clause子语法用于移动分区到新的表空间。 ``` MOVE PARTITION { partion_name | FOR ( partition_value [, ...] ) } TABLESPACE tablespacename ``` * exchange\_clause子语法用于把普通表的数据迁移到指定的分区。 ``` EXCHANGE PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } WITH TABLE {[ ONLY ] ordinary_table_name | ordinary_table_name * | ONLY ( ordinary_table_name )} [ { WITH | WITHOUT } VALIDATION ] [ VERBOSE ] [ UPDATE GLOBAL INDEX ] ``` 进行交换的普通表和分区必须满足如下条件: * 普通表和分区的列数目相同,对应列的信息严格一致,包括:列名、列的数据类型、列约束、列的Collation信息、列的存储参数、列的压缩信息等。 * 普通表和分区的表压缩信息严格一致。 * 普通表和分区的索引个数相同,且对应索引的信息严格一致。 * 普通表和分区的表约束个数相同,且对应表约束的信息严格一致。 * 普通表不可以是临时表,分区表只能是范围分区表,列表分区表,哈希分区表或间隔分区表。 * 普通表和分区表上不可以有动态数据脱敏,行访问控制约束。 * 列表分区表,哈希分区表不能是列存储。 > \[!TIP]须知 > > * 完成交换后,普通表和分区的数据被置换,同时普通表和分区的表空间信息被置换。此时,普通表和分区的统计信息变得不可靠,需要对普通表和分区重新执行analyze。 > * 由于非分区键不能建立本地唯一索引,只能建立全局唯一索引,所以如果普通表含有唯一索引时,可能会导致不能交换数据。 > * 如果在普通表/分区表上进行了drop column操作,被删除的列依然物理存在,所以需要保证普通表和分区的被删除列也严格对齐才能交换成功。 > * 分区表的分区键包含表达式处理(例如:abs(column))的场景下,交换分区时不会对普通表的待迁移数据进行表达式处理,而且对原有数据直接适用分区。 * row\_clause子语法用于设置分区表的行迁移开关。 ``` { ENABLE | DISABLE } ROW MOVEMENT ``` * merge\_clause子语法用于把多个分区合并成一个分区。当前只有RANGE分区支持合并分区。 ``` MERGE PARTITIONS { partition_name } [, ...] INTO PARTITION partition_name [ TABLESPACE tablespacename ] [ UPDATE GLOBAL INDEX ] ``` > \[!WARNING]注意 > ```` >``` ```` ```` >Ustore存储引擎表不支持在事务块中执行ALTER TABLE MERGE PARTITIONS的操作。 >``` - modify\_clause子语法用于设置分区索引是否可用。 ``` MODIFY PARTITION partition_name { UNUSABLE LOCAL INDEXES | REBUILD UNUSABLE LOCAL INDEXES } ``` - split\_clause子语法用于把一个分区切割成多个分区。当前只有RANGE分区支持切割分区。 ``` SPLIT PARTITION { partition_name | FOR ( partition_value [, ...] ) } { split_point_clause | no_split_point_clause } [ UPDATE GLOBAL INDEX ] ``` - 指定切割点split\_point\_clause的语法为。 ``` AT ( partition_value ) INTO ( PARTITION partition_name [ TABLESPACE tablespacename ] , PARTITION partition_name [ TABLESPACE tablespacename ] ) ``` >[!TIP]须知 >- 列存分区表不支持切割分区。 >- 切割点的大小要位于正在被切割的分区的分区键范围内,指定切割点的方式只能把一个分区切割成两个新分区。 - 不指定切割点no\_split\_point\_clause的语法为。 ``` INTO { ( partition_less_than_item [, ...] ) | ( partition_start_end_item [, ...] ) } ``` >[!TIP]须知 >- 不指定切割点的方式,partition\_less\_than\_item指定的第一个新分区的分区键要大于正在被切割的分区的前一个分区(如果存在的话)的分区键,partition\_less\_than\_item指定的最后一个分区的分区键要等于正在被切割的分区的分区键大小。 >- 不指定切割点的方式,partition\_start\_end\_item指定的第一个新分区的起始点(如果存在的话)必须等于正在被切割的分区的前一个分区(如果存在的话)的分区键,partition\_start\_end\_item指定的最后一个分区的终止点(如果存在的话)必须等于正在被切割的分区的分区键。 >- partition\_less\_than\_item支持的分区键个数最多为4,而partition\_start\_end\_item仅支持1个分区键,其支持的数据类型参见[PARTITION BY RANGE\(parti...](create_table_partition.md#zh-cn_topic_0283136653_zh-cn_topic_0237122119_section1163224811518)。 >- 在同一语句中partition\_less\_than\_item和partition\_start\_end\_item两者不可同时使用;不同split语句之间没有限制。 - 分区项partition\_less\_than\_item的语法为。 ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } [, ...] ) [ TABLESPACE tablespacename ] ``` - 分区项partition\_start\_end\_item的语法为,其约束参见[START END语法描述](create_table_partition.md#zh-cn_topic_0283136653_zh-cn_topic_0237122119_section1163224811518)。 ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` - add\_clause子语法用于为指定的分区表添加一个或多个分区。 ``` ADD PARTITION ( partition_col1_name = partition_col1_value [, partition_col2_name = partition_col2_value ] [, ...] ) [ LOCATION 'location1' ] [ PARTITION (partition_colA_name = partition_colA_value [, partition_colB_name = partition_colB_value ] [, ...] ) ] [ LOCATION 'location2' ] ADD {partition_less_than_item | partition_start_end_item| partition_list_item } ``` 分区项partition\_list\_item的语法如下。 ``` PARTITION partition_name VALUES (list_values_clause) [ TABLESPACE tablespacename ] ``` >[!TIP]须知 >- partition\_list\_item仅支持1个分区键,其支持的数据类型参见[PARTITION BY LIST\(partit...](create_table_partition.md#zh-cn_topic_0283136653_zh-cn_topic_0237122119_section1163224811518)。 >- 间隔/哈希分区表不支持添加分区。 - drop\_clause子语法用于删除分区表中的指定分区。 ``` DROP PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` >[!TIP]须知 >- 哈希分区表不支持删除分区。 >- 当分区表只有一个分区时,不能删除该分区。 - truncate\_clause子语法用于清空分区表中的指定分区。 ``` TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` ```` * 修改表分区名称的语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME PARTITION { partion_name | FOR ( partition_value [, ...] ) } TO partition_new_name; ``` * 重置分区ID的语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RESET PARTITION; ``` ## 参数说明 * **table\_name** 分区表名。 取值范围:已存在的分区表名。 * **partition\_name** 分区名。 取值范围:已存在的分区名。 * **tablespacename** 指定分区要移动到哪个表空间。 取值范围:已存在的表空间名。 * **partition\_value** 分区键值。 通过PARTITION FOR ( partition\_value \[, ...] )子句指定的这一组值,可以唯一确定一个分区。 取值范围:需要进行重命名的分区的分区键的取值范围。 * **UNUSABLE LOCAL INDEXES** 设置该分区上的所有索引不可用。 * **REBUILD UNUSABLE LOCAL INDEXES** 重建该分区上的所有索引。 * **ENABLE/DISABLE ROW MOVEMET** 行迁移开关。 如果进行UPDATE操作时,更新了元组在分区键上的值,造成了该元组所在分区发生变化,就会根据该开关给出报错信息,或者进行元组在分区间的转移。 取值范围: * ENABLE:打开行迁移开关。 * DISABLE:关闭行迁移开关。 默认是打开状态。 * **ordinary\_table\_name** 进行迁移的普通表的名称。 取值范围:已存在的普通表名。 * **{ WITH | WITHOUT } VALIDATION** 在进行数据迁移时,是否检查普通表中的数据满足指定分区的分区键范围。 取值范围: * WITH:对于普通表中的数据要检查是否满足分区的分区键范围,如果有数据不满足,则报错。 * WITHOUT:对于普通表中的数据不检查是否满足分区的分区键范围。 默认是WITH状态。 由于检查比较耗时,特别是当数据量很大的情况下更甚。所以在保证当前普通表中的数据满足分区的分区键范围时,可以加上WITHOUT来指明不进行检查。 * **VERBOSE** 在VALIDATION是WITH状态时,如果检查出普通表有不满足要交换分区的分区键范围的数据,那么把这些数据插入到正确的分区,如果路由不到任何分区,再报错。 > \[!TIP]须知 > 只有在VALIDATION是WITH状态时,才可以指定VERBOSE。 * **partition\_new\_name** 分区的新名称。 取值范围:字符串,要符合标识符的命名规范。 ## 示例 请参考CREATE TABLE PARTITION的[示例](create_table_partition.md#zh-cn_topic_0283136653_zh-cn_topic_0237122119_zh-cn_topic_0059777586_s43dd49de892344bf89e6f56f17404842)。 ## 相关链接 [CREATE TABLE PARTITION](create_table_partition.md),[DROP TABLE](drop_table.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-ALTER-TABLE-PARTITION.md --- # ALTER TABLE PARTITION ## 功能描述 修改表分区,包括增删分区、切割分区、合成分区以及修改分区属性等。 相比于内核语法,dolphin的rebuild,remove,check,repair,optimize,truncate,analyze,exchange,reorganize都做了B兼容模式下的特色修改。 ## 注意事项 * 添加分区的表空间不能是PG\_GLOBAL。 * 添加分区的名称不能与该分区表已有分区的名称相同。 * 添加分区的分区键值要和分区表的分区键的类型一致。 * 若添加RANGE分区,添加分区键值要大于分区表中最后一个范围分区的上边界。 * 若添加LIST分区,添加分区键值不能与现有分区键值重复。 * 不支持添加HASH分区。 * 如果目标分区表中已有分区数达到了最大值1048575,则不能继续添加分区。 * 当分区表只有一个分区时,不能删除该分区。 * 选择分区使用PARTITION FOR(),括号里指定值个数应该与定义分区时使用的列个数相同,并且一一对应。 * Value分区表不支持相应的Alter Partition操作。 * 列存分区表不支持切割分区。 * 间隔分区表不支持添加分区。 * 哈希分区表不支持切割分区,不支持合成分区,不支持添加和删除分区。 * 列表分区表不支持切割分区,不支持合成分区。 * 只有分区表的所有者或者被授予了分区表ALTER权限的用户有权限执行ALTER TABLE PARTITION命令,系统管理员默认拥有此权限。 ## 语法格式 * 修改表分区主语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | (ONLY) table_name | (ONLY) ( table_name )} action [, ... ]; ``` 其中action统指如下分区维护子语法。当存在多个分区维护子句时,保证了分区的连续性,无论这些子句的排序如何,openGauss总会先执行DROP PARTITION再执行ADD PARTITION操作,最后顺序执行其它分区维护操作。 ``` move_clause | exchange_clause | row_clause | merge_clause | modify_clause | split_clause | add_clause | drop_clause | truncate_clause | rebuild_clause | remove_clause | repair_clause | check_clause | optimize_clause ``` * move\_clause子语法用于移动分区到新的表空间。 ``` MOVE PARTITION { partion_name | FOR ( partition_value [, ...] ) } TABLESPACE tablespacename ``` * exchange\_clause子语法用于把普通表的数据迁移到指定的分区。 ``` EXCHANGE PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } WITH TABLE {[ (ONLY) ] ordinary_table_name | ordinary_table_name * | (ONLY) ( ordinary_table_name )} [ { WITH | WITHOUT } VALIDATION ] [ VERBOSE ] [ UPDATE GLOBAL INDEX ] ``` 进行交换的普通表和分区必须满足如下条件: * 普通表和分区的列数目相同,对应列的信息严格一致,包括:列名、列的数据类型、列约束、列的Collation信息、列的存储参数、列的压缩信息等。 * 普通表和分区的表压缩信息严格一致。 * 普通表和分区的索引个数相同,且对应索引的信息严格一致。 * 普通表和分区的表约束个数相同,且对应表约束的信息严格一致。 * 普通表不可以是临时表,分区表只能是范围分区表,列表分区表,哈希分区表。 * 普通表和分区表上不可以有动态数据脱敏,行访问控制约束。 * 列表分区表,哈希分区表不能是列存储。 * List/Hash/Range类型分区表支持exchange\_clause。 > \[!TIP]须知 > > * 完成交换后,普通表和分区的数据被置换,同时普通表和分区的表空间信息被置换。此时,普通表和分区的统计信息变得不可靠,需要对普通表和分区重新执行analyze。 > > * 由于非分区键不能建立本地唯一索引,只能建立全局唯一索引,所以如果普通表含有唯一索引时,会导致不能交换数据。 > > * 分区表的分区键包含表达式处理(例如:abs(column))的场景下,交换分区时不会对普通表的待迁移数据进行表达式处理,而且对原有数据直接适用分区。 * row\_clause子语法用于设置分区表的行迁移开关。 ``` { ENABLE | DISABLE } ROW MOVEMENT ``` * merge\_clause子语法用于把多个分区合并成一个分区。 ``` MERGE PARTITIONS { partition_name } [, ...] INTO PARTITION partition_name [ TABLESPACE tablespacename ] [ UPDATE GLOBAL INDEX ] ``` * modify\_clause子语法用于设置分区索引是否可用。 ``` MODIFY PARTITION partition_name { UNUSABLE LOCAL INDEXES | REBUILD UNUSABLE LOCAL INDEXES } ``` * split\_clause子语法用于把一个分区切割成多个分区。 ``` SPLIT PARTITION { partition_name | FOR ( partition_value [, ...] ) } { split_point_clause | no_split_point_clause } [ UPDATE GLOBAL INDEX ] ``` * 指定切割点split\_point\_clause的语法为。 ``` AT ( partition_value ) INTO ( PARTITION partition_name [ TABLESPACE tablespacename ] , PARTITION partition_name [ TABLESPACE tablespacename ] ) ``` > \[!TIP]须知 > > * 列存分区表不支持切割分区。 > > * 切割点的大小要位于正在被切割的分区的分区键范围内,指定切割点的方式只能把一个分区切割成两个新分区。 * 不指定切割点no\_split\_point\_clause的语法为。 ``` INTO { ( partition_less_than_item [, ...] ) | ( partition_start_end_item [, ...] ) } ``` ``` >[!TIP]须知 > >- 不指定切割点的方式,partition\_less\_than\_item指定的第一个新分区的分区键要大于正在被切割的分区的前一个分区(如果存在的话)的分区键,partition\_less\_than\_item指定的最后一个分区的分区键要等于正在被切割的分区的分区键大小。 > >- 不指定切割点的方式,partition\_start\_end\_item指定的第一个新分区的起始点(如果存在的话)必须等于正在被切割的分区的前一个分区(如果存在的话)的分区键,partition\_start\_end\_item指定的最后一个分区的终止点(如果存在的话)必须等于正在被切割的分区的分区键。 > >- partition\_less\_than\_item支持的分区键个数最多为4,而partition\_start\_end\_item仅支持1个分区键,其支持的数据类型参见[PARTITION BY RANGE\(parti...](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_table_partition.html#zh-cn_topic_0283136653_zh-cn_topic_0237122119_zh-cn_topic_0059777586_sd2701df1d7364084a7791592def4e9eb)。 > >- 在同一语句中partition\_less\_than\_item和partition\_start\_end\_item两者不可同时使用;不同split语句之间没有限制。 ``` * 分区项partition\_less\_than\_item的语法为。 ```` ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } [, ...] ) | MAXVALUE [ TABLESPACE tablespacename ] ``` ```` * 分区项partition\_start\_end\_item的语法为,其约束参见[START END语法描述](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_table_partition.html#zh-cn_topic_0283136653_zh-cn_topic_0237122119_zh-cn_topic_0059777586_sd2701df1d7364084a7791592def4e9eb)。 ```` ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE}) | MAXVALUE} | {START(partition_value)} | {END ({partition_value | MAXVALUE}) | MAXVALUE} } [TABLESPACE tablespace_name] ``` ```` * add\_clause子语法用于为指定的分区表添加一个或多个分区。 ``` ADD PARTITION ( partition_col1_name = partition_col1_value [, partition_col2_name = partition_col2_value ] [, ...] ) [ LOCATION 'location1' ] [ PARTITION (partition_colA_name = partition_colA_value [, partition_colB_name = partition_colB_value ] [, ...] ) ] [ LOCATION 'location2' ] ADD {partition_less_than_item | partition_start_end_item| partition_list_item } ``` * 分区项partition\_list\_item的语法如下。 ``` PARTITION partition_name VALUES [ IN ] (list_values_clause) [ TABLESPACE tablespacename ] ``` > \[!TIP]须知 > > * partition\_list\_item仅支持的1个分区键,其支持的数据类型参见[PARTITION BY LIST(partit...](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_table_partition.html#zh-cn_topic_0283136653_zh-cn_topic_0237122119_zh-cn_topic_0059777586_sd2701df1d7364084a7791592def4e9eb)。 > > * 间隔/哈希分区表不支持添加分区。 * drop\_clause子语法用于删除分区表中的指定分区。 ``` DROP PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` > \[!TIP]须知 > 哈希分区表不支持删除分区。 * truncate\_clause子语法用于清空分区表中的指定分区。 ``` TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` * 修改表分区名称的语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | (ONLY) table_name | (ONLY) ( table_name )} RENAME PARTITION { partion_name | FOR ( partition_value [, ...] ) } TO partition_new_name; ``` * 重建分区语法 一般用于回收分区使用空间,与删除存储在分区中的所有记录,然后重新插入它们的效果相同。这对于碎片整理很有用。 不支持列存表,不支持指定二级分区表的二级分区。 ``` REBUILD PARTITION { partition_name } [, ...] REBUILD PARTITION ALL ``` * 分区表remove partitioning语法 移除表中partition,但是保留所有数据。 不支持列存表和segment表。 ``` REMOVE PARTITIONING ``` * 分区表repair,check和optimize语法 仅支持语法,不做实际功能支持。 ``` CHECK PARTITION { partition_name } [, ...] CHECK PARTITION ALL REPAIR PARTITION { partition_name } [, ...] REPAIR PARTITION ALL OPTIMIZE PARTITION { partition_name } [, ...] OPTIMIZE PARTITION ALL ``` * Truncate分区语法 Truncate操作会删除当前分区对应的所有数据。 ``` TRUNCATE PARTITION { partition_name } [, ...] TRUNCATE PARTITION all ``` * exchange分区语法对齐 可以用来交换分区表和普通表的数据,普通表和分区的数据被置换,同时普通表和分区的表空间信息被置换。此时,普通表和分区的统计信息变得不可靠,需要对普通表和分区重新执行analyze。 不支持交换二级分区。 ``` exchange partition partition_name with table table_name (without/with validation); ``` * analyze分区语法对齐 用于收集与表内容相关的统计信息。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。 不支持analyze指定二级分区。 ``` analyze partition { partition_name } [, ...] analyze partition all; ``` * add分区语法。 ``` ADD {partition_less_than_item | partition_start_end_item| partition_list_item } [, ...] ``` * drop分区语法。 ``` DROP PARTITION { { partition_name } [ UPDATE GLOBAL INDEX ] } [, ...] DROP SUBPARTITION { { partition_name } [ UPDATE GLOBAL INDEX ] } [, ...] ``` * reorganize分区语法。 重新分割或融合指定分区,重新划分分区的定义。 以下是ALTER TABLE ... REORGANIZE PARTITION用于重新分区一些关键点: * PARTITION用于确定新分区方案的选项应遵循与CREATE TABLE语句所使用的规则相同的规则。 * 新的RANGE分区方案不能有任何重叠范围。一个新的LIST分区方案不能有任何重叠的值集。 * partition\_definitions列表中的分区组合应与清单中命名的组合分区具有相同的范围或整体值集partition\_list。 * 对于由分区的表RANGE,您只能重组相邻的分区。您不能跳过范围分区。 * 对于LIST分区,不可以删除已有对应数据的value值定义。 * 不能用于REORGANIZE PARTITION更改表使用的分区类型。 * 不可丢失原有表数据。 * 不支持interval分区,不支持value分区。 * 对于RANGE分区,不支持start end语法。 ``` REORGANIZE PARTITION {{ partition_name } [, ...]} INTO {partition_less_than_item | partition_list_item } [, ...] ``` ## 参数说明 * **table\_name** 分区表名。 取值范围:已存在的分区表名。 * **partition\_name** 分区名。 取值范围:已存在的分区名。 * **tablespacename** 指定分区要移动到哪个表空间。 取值范围:已存在的表空间名。 * **partition\_value** 分区键值。 通过PARTITION FOR ( partition\_value \[, ...] )子句指定的这一组值,可以唯一确定一个分区。 取值范围:需要进行重命名的分区的分区键的取值范围。 * **UNUSABLE LOCAL INDEXES** 设置该分区上的所有索引不可用。 * **REBUILD UNUSABLE LOCAL INDEXES** 重建该分区上的所有索引。 * **ENABLE/DISABLE ROW MOVEMET** 行迁移开关。 如果进行UPDATE操作时,更新了元组在分区键上的值,造成了该元组所在分区发生变化,就会根据该开关给出报错信息,或者进行元组在分区间的转移。 取值范围: * ENABLE:打开行迁移开关。 * DISABLE:关闭行迁移开关。 默认是打开状态。 * **ordinary\_table\_name** 进行迁移的普通表的名称。 取值范围:已存在的普通表名。 * **{ WITH | WITHOUT } VALIDATION** 在进行数据迁移时,是否检查普通表中的数据满足指定分区的分区键范围。 取值范围: * WITH:对于普通表中的数据要检查是否满足分区的分区键范围,如果有数据不满足,则报错。 * WITHOUT:对于普通表中的数据不检查是否满足分区的分区键范围。 默认是WITH状态。 由于检查比较耗时,特别是当数据量很大的情况下更甚。所以在保证当前普通表中的数据满足分区的分区键范围时,可以加上WITHOUT来指明不进行检查。 * **VERBOSE** 在VALIDATION是WITH状态时,如果检查出普通表有不满足要交换分区的分区键范围的数据,那么把这些数据插入到正确的分区,如果路由不到任何分区,再报错。 > \[!TIP]须知 > 只有在VALIDATION是WITH状态时,才可以指定VERBOSE。 * **partition\_new\_name** 分区的新名称。 取值范围:字符串,要符合标识符的命名规范。 ## 示例 请参考CREATE TABLE PARTITION的[示例](dolphin-CREATE-TABLE-PARTITION.md#zh-cn_topic_0283136653_zh-cn_topic_0237122119_zh-cn_topic_0059777586_s43dd49de892344bf89e6f56f17404842)。 ## 相关链接 [CREATE TABLE PARTITION](dolphin-CREATE-TABLE-PARTITION.md),[DROP TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/drop_table.html) --- --- url: /zh/docs/latest/sql_reference/alter_table_partition.md --- # ALTER TABLE PARTITION ## 功能描述 修改表分区,包括增加/删除分区、切割/合并分区、清空分区、移动分区表空间、交换分区、重命名分区,以及修改分区属性等。 ## 注意事项 * 添加分区的表空间不能是PG\_GLOBAL。 * 添加分区的名称不能与该分区表已有分区的名称相同。 * 添加分区的分区键值要和分区表的分区键的类型一致。 * 若添加RANGE分区,添加分区键值要大于分区表中最后一个范围分区的上边界。 * 若添加LIST分区,添加分区键值不能与现有分区键值重复。 * 不支持添加HASH分区。 * 如果目标分区表中已有分区数达到了最大值1048575,则不能继续添加分区。 * 当分区表只有一个分区时,不能删除该分区。 * 选择分区使用PARTITION FOR(),括号里指定值个数应该与定义分区时使用的列个数相同,并且一一对应。 * Value分区表不支持相应的Alter Partition操作。 * 列存分区表不支持切割分区。 * 间隔分区表不支持添加分区。 * 哈希分区表不支持切割分区,不支持合成分区,不支持添加和删除分区。 * 列表分区表不支持切割分区,不支持合成分区。 * 只有分区表的所有者或者被授予了分区表ALTER权限的用户有权限执行ALTER TABLE PARTITION命令,系统管理员默认拥有此权限。 * 删除、切割、合并、清空、交换分区的操作会使Global索引失效,可以申明UPDATE GLOBAL INDEX子句同步更新索引。 * 如果删除、切割、合并、清空、交换分区操作不申明UPDATE GLOBAL INDEX子句,并发的DML业务有可能因为索引不可用而报错。 ## 语法格式 修改分区表分区包括修改表分区主语法、修改表分区名称的语法和重置分区ID的语法。 * 修改表分区主语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ``` 其中action统指如下分区维护子语法。当存在多个分区维护子句时,保证了分区的连续性,无论这些子句的排序如何,openGauss总会先执行DROP PARTITION再执行ADD PARTITION操作,最后顺序执行其它分区维护操作。 ``` move_clause | exchange_clause | row_clause | merge_clause | modify_clause | split_clause | add_clause | drop_clause | truncate_clause ``` * move\_clause子语法用于移动分区到新的表空间。 ``` MOVE PARTITION { partion_name | FOR ( partition_value [, ...] ) } TABLESPACE tablespacename ``` * exchange\_clause子语法用于把普通表的数据迁移到指定的分区。 ``` EXCHANGE PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } WITH TABLE {[ ONLY ] ordinary_table_name | ordinary_table_name * | ONLY ( ordinary_table_name )} [ { WITH | WITHOUT } VALIDATION ] [ VERBOSE ] [ UPDATE GLOBAL INDEX ] ``` 进行交换的普通表和分区必须满足如下条件: * 普通表和分区的列数目相同,对应列的信息严格一致,包括:列名、列的数据类型、列约束、列的Collation信息、列的存储参数、列的压缩信息等。 * 普通表和分区的表压缩信息严格一致。 * 普通表和分区的索引个数相同,且对应索引的信息严格一致。 * 普通表和分区的表约束个数相同,且对应表约束的信息严格一致。 * 普通表不可以是临时表,分区表只能是范围分区表,列表分区表,哈希分区表或间隔分区表。 * 普通表和分区表上不可以有动态数据脱敏,行访问控制约束。 * 列表分区表,哈希分区表不能是列存储。 > \[!TIP]须知 > > * 完成交换后,普通表和分区的数据被置换,同时普通表和分区的表空间信息被置换。此时,普通表和分区的统计信息变得不可靠,需要对普通表和分区重新执行analyze。 > * 由于非分区键不能建立本地唯一索引,只能建立全局唯一索引,所以如果普通表含有唯一索引时,可能会导致不能交换数据。 > * 如果在普通表/分区表上进行了drop column操作,被删除的列依然物理存在,所以需要保证普通表和分区的被删除列也严格对齐才能交换成功。 > * 分区表的分区键包含表达式处理(例如:abs(column))的场景下,交换分区时不会对普通表的待迁移数据进行表达式处理,而且对原有数据直接适用分区。 * row\_clause子语法用于设置分区表的行迁移开关。 ``` { ENABLE | DISABLE } ROW MOVEMENT ``` * merge\_clause子语法用于把多个分区合并成一个分区。当前只有RANGE分区支持合并分区。 ``` MERGE PARTITIONS { partition_name } [, ...] INTO PARTITION partition_name [ TABLESPACE tablespacename ] [ UPDATE GLOBAL INDEX ] ``` > \[!WARNING]注意 > ```` >``` ```` ```` >Ustore存储引擎表不支持在事务块中执行ALTER TABLE MERGE PARTITIONS的操作。 >``` - modify\_clause子语法用于设置分区索引是否可用。 ``` MODIFY PARTITION partition_name { UNUSABLE LOCAL INDEXES | REBUILD UNUSABLE LOCAL INDEXES } ``` - split\_clause子语法用于把一个分区切割成多个分区。当前只有RANGE分区支持切割分区。 ``` SPLIT PARTITION { partition_name | FOR ( partition_value [, ...] ) } { split_point_clause | no_split_point_clause } [ UPDATE GLOBAL INDEX ] ``` - 指定切割点split\_point\_clause的语法为。 ``` AT ( partition_value ) INTO ( PARTITION partition_name [ TABLESPACE tablespacename ] , PARTITION partition_name [ TABLESPACE tablespacename ] ) ``` >[!TIP]须知 >- 列存分区表不支持切割分区。 >- 切割点的大小要位于正在被切割的分区的分区键范围内,指定切割点的方式只能把一个分区切割成两个新分区。 - 不指定切割点no\_split\_point\_clause的语法为。 ``` INTO { ( partition_less_than_item [, ...] ) | ( partition_start_end_item [, ...] ) } ``` >[!TIP]须知 >- 不指定切割点的方式,partition\_less\_than\_item指定的第一个新分区的分区键要大于正在被切割的分区的前一个分区(如果存在的话)的分区键,partition\_less\_than\_item指定的最后一个分区的分区键要等于正在被切割的分区的分区键大小。 >- 不指定切割点的方式,partition\_start\_end\_item指定的第一个新分区的起始点(如果存在的话)必须等于正在被切割的分区的前一个分区(如果存在的话)的分区键,partition\_start\_end\_item指定的最后一个分区的终止点(如果存在的话)必须等于正在被切割的分区的分区键。 >- partition\_less\_than\_item支持的分区键个数最多为4,而partition\_start\_end\_item仅支持1个分区键,其支持的数据类型参见[PARTITION BY RANGE\(parti...](create_table_partition.md)。 >- 在同一语句中partition\_less\_than\_item和partition\_start\_end\_item两者不可同时使用;不同split语句之间没有限制。 - 分区项partition\_less\_than\_item的语法为。 ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } [, ...] ) [ TABLESPACE tablespacename ] ``` - 分区项partition\_start\_end\_item的语法为,其约束参见[START END语法描述](create_table_partition.md)。 ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` - add\_clause子语法用于为指定的分区表添加一个或多个分区。 ``` ADD PARTITION ( partition_col1_name = partition_col1_value [, partition_col2_name = partition_col2_value ] [, ...] ) [ LOCATION 'location1' ] [ PARTITION (partition_colA_name = partition_colA_value [, partition_colB_name = partition_colB_value ] [, ...] ) ] [ LOCATION 'location2' ] ADD {partition_less_than_item | partition_start_end_item| partition_list_item } ``` 分区项partition\_list\_item的语法如下。 ``` PARTITION partition_name VALUES (list_values_clause) [ TABLESPACE tablespacename ] ``` >[!TIP]须知 >- partition\_list\_item仅支持1个分区键,其支持的数据类型参见[PARTITION BY LIST\(partit...](create_table_partition.md)。 >- 间隔/哈希分区表不支持添加分区。 - drop\_clause子语法用于删除分区表中的指定分区。 ``` DROP PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` >[!TIP]须知 >- 哈希分区表不支持删除分区。 >- 当分区表只有一个分区时,不能删除该分区。 - truncate\_clause子语法用于清空分区表中的指定分区。 ``` TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` ```` * 修改表分区名称的语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME PARTITION { partion_name | FOR ( partition_value [, ...] ) } TO partition_new_name; ``` * 重置分区ID的语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RESET PARTITION; ``` ## 参数说明 * **table\_name** 分区表名。 取值范围:已存在的分区表名。 * **partition\_name** 分区名。 取值范围:已存在的分区名。 * **tablespacename** 指定分区要移动到哪个表空间。 取值范围:已存在的表空间名。 * **partition\_value** 分区键值。 通过PARTITION FOR ( partition\_value \[, ...] )子句指定的这一组值,可以唯一确定一个分区。 取值范围:需要进行重命名的分区的分区键的取值范围。 * **UNUSABLE LOCAL INDEXES** 设置该分区上的所有索引不可用。 * **REBUILD UNUSABLE LOCAL INDEXES** 重建该分区上的所有索引。 * **ENABLE/DISABLE ROW MOVEMET** 行迁移开关。 如果进行UPDATE操作时,更新了元组在分区键上的值,造成了该元组所在分区发生变化,就会根据该开关给出报错信息,或者进行元组在分区间的转移。 取值范围: * ENABLE:打开行迁移开关。 * DISABLE:关闭行迁移开关。 默认是打开状态。 * **ordinary\_table\_name** 进行迁移的普通表的名称。 取值范围:已存在的普通表名。 * **{ WITH | WITHOUT } VALIDATION** 在进行数据迁移时,是否检查普通表中的数据满足指定分区的分区键范围。 取值范围: * WITH:对于普通表中的数据要检查是否满足分区的分区键范围,如果有数据不满足,则报错。 * WITHOUT:对于普通表中的数据不检查是否满足分区的分区键范围。 默认是WITH状态。 由于检查比较耗时,特别是当数据量很大的情况下更甚。所以在保证当前普通表中的数据满足分区的分区键范围时,可以加上WITHOUT来指明不进行检查。 * **VERBOSE** 在VALIDATION是WITH状态时,如果检查出普通表有不满足要交换分区的分区键范围的数据,那么把这些数据插入到正确的分区,如果路由不到任何分区,再报错。 > \[!TIP]须知 > 只有在VALIDATION是WITH状态时,才可以指定VERBOSE。 * **partition\_new\_name** 分区的新名称。 取值范围:字符串,要符合标识符的命名规范。 ## 示例 请参考CREATE TABLE PARTITION的[示例](create_table_partition.md#zh-cn_topic_0283136653_zh-cn_topic_0237122119_zh-cn_topic_0059777586_s43dd49de892344bf89e6f56f17404842)。 ## 相关链接 [CREATE TABLE PARTITION](create_table_partition.md),[DROP TABLE](drop_table.md) --- --- url: /en/docs/latest-lite/brief_tutorial/alter_table_statement.md --- # ALTER TABLE Statement The ALTER TABLE statement modifies tables, including modifying table definitions, renaming tables, renaming specified columns in tables, renaming table constraints, setting table schemas, enabling or disabling row-level security policies, and adding or updating multiple columns. ## Syntax * Add a column to an existing table. ``` ALTER TABLE table_name ADD column_name data_type; ``` * Delete a column from an existing table. ``` ALTER TABLE table_name DROP COLUMN column_name; ``` * Change the column type of a table. ``` ALTER TABLE table_name MODIFY column_name data_type; ``` * Add or delete a NOT NULL constraint to or from a column of an existing table. ``` ALTER TABLE table_name ALTER column_name { SET | DROP } NOT NULL ``` * Rename a specified column in a table. ``` ALTER TABLE table_name RENAME column_name TO new_column_name; ``` * Update columns. ``` ALTER TABLE table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ``` * Rename a table,which does not affect stored data. ``` ALTER TABLE table_name RENAME TO new_table_name; ``` ## Parameter Description * **table\_name** Specifies the name of the table to be modified. If **ONLY** is specified, only the table is modified. If **ONLY** is not specified, the table and all subtables are modified. You can add the asterisk (\*) option following the table name to specify that all subtables are scanned, which is the default operation. * **column\_name** Specifies the name of a new or an existing column. * **data\_type** Specifies the type of a new column or a new type of an existing column. * **new\_table\_name** Specifies the new table name. * **new\_column\_name** Specifies the new name of a specific column in a table. * **constraint\_name** Specifies the name of a constraint. ## Examples The data in the **customer\_t1** table is as follows: ``` openGauss=# SELECT * FROM customer_t1; c_customer_sk | c_customer_id | c_first_name | c_last_name | amount ---------------+---------------+--------------+-------------+-------- 3869 | hello | Grace | | 1000 3869 | hello | Grace | | 1000 3869 | | Grace | | 3869 | hello | | | 3869 | hello | | | | | | | 6985 | maps | Joes | | 2200 9976 | world | James | | 5000 4421 | Admin | Local | | 3000 6881 | maps | Lily | | 1000 4320 | tpcds | Lily | | 2000 (11 rows) ``` * Add a column. Add a new column to the preceding table. ``` openGauss=# ALTER TABLE customer_t1 ADD date time; ``` The following shows the structure of the **customer\_t1** table. The **date** column is added successfully. ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(8) | amount | integer | date | time without time zone | ``` * Change the data type of a column. Change the data type of the **c\_last\_name** column from character(8) to character(12). ``` openGauss=# ALTER TABLE customer_t1 MODIFY c_last_name character(12); ``` Query the structure of the **customer\_t1** table. The data type of the **c\_last\_name** column is changed successfully. ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | date | time without time zone | ``` * Add a column constraint. Delete the rows where the **c\_customer\_sk** column is empty. ``` openGauss=# DELETE FROM customer_t1 WHERE c_customer_sk is NULL; ``` Add a not-null constraint to the **c\_customer\_sk** column. ``` openGauss=# ALTER TABLE customer_t1 ALTER c_customer_sk SET NOT NULL; ``` Query the structure of the **customer\_t1** table. The constraint is successfully added to the **c\_customer\_sk** column. ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | not null c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | date | time without time zone | ``` * Change a column name. Change the column name from **date** to **purchase\_date**. ``` openGauss=# ALTER TABLE customer_t1 RENAME date TO purchase_date; ``` Query the structure of the **customer\_t1** table. The name of the **date** column is changed successfully. ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | not null c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | purchase_date | time without time zone | ``` * Delete a column. Delete the **purchase\_date** column. ``` openGauss=# ALTER TABLE customer_t1 DROP purchase_date; ``` After deletion, the data in the **customer\_t1** table is as follows: ``` openGauss=# SELECT * FROM customer_t1; c_customer_sk | c_customer_id | c_first_name | c_last_name | amount ---------------+---------------+--------------+-------------+-------- 3869 | hello | Grace | | 1000 3869 | hello | Grace | | 1000 3869 | | Grace | | 3869 | hello | | | 3869 | hello | | | 6985 | maps | Joes | | 2200 9976 | world | James | | 5000 4421 | Admin | Local | | 3000 6881 | maps | Lily | | 1000 4320 | tpcds | Lily | | 2000 (10 rows) ``` --- --- url: /en/docs/latest/sql_reference/brief_tutorial/alter-table-statement.md --- # ALTER TABLE Statement The ALTER TABLE statement modifies tables, including modifying table definitions, renaming tables, renaming specified columns in tables, renaming table constraints, setting table schemas, enabling or disabling row-level security policies, and adding or updating multiple columns. ## Syntax * Add a column to an existing table. ``` ALTER TABLE table_name ADD column_name data_type; ``` * Delete a column from an existing table. ``` ALTER TABLE table_name DROP COLUMN column_name; ``` * Change the column type of a table. ``` ALTER TABLE table_name MODIFY column_name data_type; ``` * Add or delete a NOT NULL constraint to or from a column of an existing table. ``` ALTER TABLE table_name ALTER column_name { SET | DROP } NOT NULL; ``` * Rename a specified column in a table. ``` ALTER TABLE table_name RENAME column_name TO new_column_name; ``` * Update columns. ``` ALTER TABLE table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ``` * Rename a table,which does not affect stored data. ``` ALTER TABLE table_name RENAME TO new_table_name; ``` ## Parameter Description * **table\_name** Specifies the name of the table to be modified. If **ONLY** is specified, only the table is modified. If **ONLY** is not specified, the table and all subtables are modified. You can add the asterisk (\*) option following the table name to specify that all subtables are scanned, which is the default operation. * **column\_name** Specifies the name of a new or an existing column. * **data\_type** Specifies the type of a new column or a new type of an existing column. * **new\_table\_name** Specifies the new table name. * **new\_column\_name** Specifies the new name of a specific column in a table. * **constraint\_name** Specifies the name of a constraint. ## Examples The data in the **customer\_t1** table is as follows: ``` openGauss=# SELECT * FROM customer_t1; c_customer_sk | c_customer_id | c_first_name | c_last_name | amount ---------------+---------------+--------------+-------------+-------- 3869 | hello | Grace | | 1000 3869 | hello | Grace | | 1000 3869 | | Grace | | 3869 | hello | | | 3869 | hello | | | | | | | 6985 | maps | Joes | | 2200 9976 | world | James | | 5000 4421 | Admin | Local | | 3000 6881 | maps | Lily | | 1000 4320 | tpcds | Lily | | 2000 (11 rows) ``` * Add a column. Add a new column to the preceding table. ``` openGauss=# ALTER TABLE customer_t1 ADD date time; ``` The following shows the structure of the **customer\_t1** table. The **date** column is added successfully. ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(8) | amount | integer | date | time without time zone | ``` * Change the data type of a column. Change the data type of the **c** column from character(8) to character(12). ``` openGauss=# ALTER TABLE customer_t1 MODIFY c_last_name character(12); ``` Query the structure of the **customer\_t1** table. The data type of the **c\_last\_name** column is changed successfully. ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | date | time without time zone | ``` * Add a column constraint. Delete the rows where the **c\_customer\_sk** column is empty. ``` openGauss=# DELETE FROM customer_t1 WHERE c_customer_sk is NULL; ``` Add a not-null constraint to the **c\_customer\_sk** column. ``` openGauss=# ALTER TABLE customer_t1 ALTER c_customer_sk SET NOT NULL; ``` Query the structure of the **customer\_t1** table. The constraint is successfully added to the **c\_customer\_sk** column. ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | not null c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | date | time without time zone | ``` * Change a column name. Change the column name from **date** to **purchase date**. ``` openGauss=# ALTER TABLE customer_t1 RENAME date TO purchase_date; ``` Query the structure of the **customer\_t1** table. The name of the **date** column is changed successfully. ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | not null c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | purchase_date | time without time zone | ``` * Delete a column. Delete the **purchase\_date** column. ``` openGauss=# ALTER TABLE customer_t1 DROP purchase_date; ``` After deletion, the data in the **customer\_t1** table is as follows: ``` openGauss=# SELECT * FROM customer_t1; c_customer_sk | c_customer_id | c_first_name | c_last_name | amount ---------------+---------------+--------------+-------------+-------- 3869 | hello | Grace | | 1000 3869 | hello | Grace | | 1000 3869 | | Grace | | 3869 | hello | | | 3869 | hello | | | 6985 | maps | Joes | | 2200 9976 | world | James | | 5000 4421 | Admin | Local | | 3000 6881 | maps | Lily | | 1000 4320 | tpcds | Lily | | 2000 (10 rows) ``` --- --- url: /en/docs/latest-lite/sql_reference/alter_table_subpartition.md --- # ALTER TABLE SUBPARTITION ## Function **ALTER TABLE SUBPARTITION** modifies partitions from a level-2 partitioned table, including adding, deleting, clearing, and splitting partitions. ## Precautions * Currently, partitions from the level-2 partitioned table can be added, deleted, cleared, or split only. * The tablespace of the added partition cannot be **PG\_GLOBAL**. * The name of the added partition must be different from the names of the existing level-1 and level-2 partitions in the partitioned table. * The key value of the added partition must be consistent with the type of partition keys in the partitioned table. * If a range partition is added, the key value of the added partition must be greater than the upper limit of the last range partition in the partitioned table. To add a partition to a table with the **MAXVALUE** partition, you are advised to use the **SPLIT** syntax. * If a list partition is added, the key value of the added partition cannot be the same as that of an existing partition. To add a partition to a table with the **DEFAULT** partition, you are advised to use the **SPLIT** syntax. * Hash partitions cannot be added. However, if the level-2 partition mode of an level-2 partitioned table is hash but the level-1 partition mode is not hash, you can add a level-1 partition and create the corresponding level-2 partition. * If the number of partitions in the target partitioned table has reached the maximum (**1048575**), partitions cannot be added. * If the partitioned table contains only one level-1 or level-2 partition, the partition cannot be deleted. * Hash partitions cannot be deleted. * Use **PARTITION FOR()** to choose partitions. The number of specified values in the brackets should be the same as the column number in customized partitions, and they must be consistent. * Only level-2 partitions (leaf nodes) can be split. Only range and list partitioning policies can be used and hash partitioning policies are not supported. The list partitioning policy can be used only when the default partition is used. * Only the owner of a partitioned table or users granted with the **ALTER** permission on the partitioned table can run the **ALTER TABLE PARTITION** command. The system administrator has the permission to run the command by default. * If the **ALTER** statement does not contain **UPDATE GLOBAL INDEX**, the original GLOBAL index is invalid. In this case, other indexes are used for query. If the ALTER statement contains UPDATEGLOBAL INDEX, the original GLOBAL index is still valid and the index function is correct. ## Syntax * Modify the syntax of the table partition. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ``` **action** indicates the following clauses for maintaining partitions. ``` add_clause | drop_clause | split_clause | truncate_clause ``` * The **add\_clause** syntax is used to add one or more partitions to a specified partitioned table. The syntax can be used in level-1 partitions. ``` ADD {partition_less_than_item | partition_list_item } [ ( subpartition_definition_list ) ] ``` It can also be used in level-2 partitions. ``` MODIFY PARTITION partition_name ADD subpartition_definition ``` **partition\_less\_than\_item** defines a range partition. The syntax is as follows: ``` PARTITION partition_name VALUES LESS THAN ( partition_value | MAXVALUE ) [ TABLESPACE tablespacename ] ``` **partition\_list\_item** defines a list partition. The syntax is as follows: ``` PARTITION partition_name VALUES ( partition_value [, ...] | DEFAULT ) [ TABLESPACE tablespacename ] ``` **subpartition\_definition\_list** contains the **subpartition\_definition** object of one or more level-2 partitions. The syntax is as follows: ``` SUBPARTITION subpartition_name { VALUES LESS THAN ( partition_value | MAXVALUE ) | VALUES ( partition_value [, ...] | DEFAULT ) } [ TABLESPACE tablespace ] ``` > \[!TIP]NOTICE > If the level-1 partition is a hash partition, you cannot use **ADD** to add a level-1 partition. If the level-2 partition is a hash partition, you cannot use **MODIFY** to add a level-2 partition. * The **drop\_clause** syntax is used to remove a partition from a specified partitioned table. The syntax can be used in level-1 partitions. ``` DROP PARTITION { partition_name | FOR ( partition_value ) } [ UPDATE GLOBAL INDEX ] ``` It can also be used in level-2 partitions. ``` DROP SUBPARTITION { subpartition_name | FOR ( partition_value, subpartition_value ) } [ UPDATE GLOBAL INDEX ] ``` > \[!TIP]NOTICE > > * If the level-1 partition is a hash partition, the level-1 partition cannot be deleted. If the level-2 partition is a hash partition, the level-2 partition cannot be deleted. > * At least one sub-partition must be retained. * The **split\_clause** syntax is used to split one partition into different partitions. ``` SPLIT SUBPARTITION { subpartition_name} { split_point_clause } [ UPDATE GLOBAL INDEX ] ``` The **split\_point\_clause** syntax used to specify a split point in the range partitioning policy is as follows: ``` AT ( subpartition_value ) INTO ( SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] , SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] ) ``` The **split\_point\_clause** syntax used to specify a split point in the list partitioning policy is as follows: ``` VALUES ( subpartition_value ) INTO ( SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] , SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] ) ``` > \[!TIP]NOTICE > > * The size of the split point should be in the range of the splitting partition key. > * One partition can be split into only two new partitions. > * In the range partitioning policy, the current partition is split into two partitions based on the split point. A partition smaller than the size specified by the split point is regarded as one partition, and a partition larger than the size specified by the split point is regarded as the other partition. Therefore, only one split point can be used in the range partitioning policy. In the list partitioning policy, there can be multiple but no more than 64 split points. These split points are extracted from the boundary values of the current partition as a new partition, and the remaining boundary values of the current partition are used as another new partition. * The **truncate\_clause** syntax is used to remove a specified partition from a partitioned table. ``` TRUNCATE SUBPARTITION { subpartition_name } [ UPDATE GLOBAL INDEX ] ``` ## Parameter Description * **table\_name** Specifies the name of a partitioned table. Value range: an existing partitioned table name. * **subpartition\_name** Specifies the name of a level-2 partition name. Value range: an existing level-2 partition name. * **tablespacename** Specifies which tablespace the partition moves to. Value range: an existing tablespace name. ## Examples See the examples in **CREATE TABLE SUBPARTITION**. --- --- url: /en/docs/latest/sql_reference/alter_table_subpartition.md --- # ALTER TABLE SUBPARTITION ## Function **ALTER TABLE SUBPARTITION** modifies partitions from a level-2 partitioned table, including adding, deleting, clearing, and splitting partitions. ## Precautions * Currently, partitions from the level-2 partitioned table can be added, deleted, cleared, or split only. * The tablespace of the added partition cannot be **PG\_GLOBAL**. * The name of the added partition must be different from the names of the existing level-1 and level-2 partitions in the partitioned table. * The key value of the added partition must be consistent with the type of partition keys in the partitioned table. * If a range partition is added, the key value of the added partition must be greater than the upper limit of the last range partition in the partitioned table. To add a partition to a table with the **MAXVALUE** partition, you are advised to use the **SPLIT** syntax. * If a list partition is added, the key value of the added partition cannot be the same as that of an existing partition. To add a partition to a table with the **DEFAULT** partition, you are advised to use the **SPLIT** syntax. * Hash partitions cannot be added. However, if the level-2 partition mode of an level-2 partitioned table is hash but the level-1 partition mode is not hash, you can add a level-1 partition and create the corresponding level-2 partition. * If the number of partitions in the target partitioned table has reached the maximum (**1048575**), partitions cannot be added. * If the partitioned table contains only one level-1 or level-2 partition, the partition cannot be deleted. * Hash partitions cannot be deleted. * Use **PARTITION FOR()** to choose partitions. The number of specified values in the brackets should be the same as the column number in customized partitions, and they must be consistent. * Only level-2 partitions (leaf nodes) can be split. Only range and list partitioning policies can be used and hash partitioning policies are not supported. The list partitioning policy can be used only when the default partition is used. * Only the owner of a partitioned table or users granted with the **ALTER** permission on the partitioned table can run the **ALTER TABLE PARTITION** command. The system administrator has the permission to run the command by default. * If the **ALTER** statement does not contain **UPDATE GLOBAL INDEX**, the original GLOBAL index is invalid. In this case, other indexes are used for query. If the ALTER statement contains UPDATEGLOBAL INDEX, the original GLOBAL index is still valid and the index function is correct. ## Syntax * Modify the syntax of the table partition. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ``` **action** indicates the following clauses for maintaining partitions. ``` add_clause | drop_clause | split_clause | truncate_clause ``` * The **add\_clause** syntax is used to add one or more partitions to a specified partitioned table. The syntax can be used in level-1 partitions. ``` ADD {partition_less_than_item | partition_list_item } [ ( subpartition_definition_list ) ] ``` It can also be used in level-2 partitions. ``` MODIFY PARTITION partition_name ADD subpartition_definition ``` **partition\_less\_than\_item** defines a range partition. The syntax is as follows: ``` PARTITION partition_name VALUES LESS THAN ( partition_value | MAXVALUE ) [ TABLESPACE tablespacename ] ``` **partition\_list\_item** defines a list partition. The syntax is as follows: ``` PARTITION partition_name VALUES ( partition_value [, ...] | DEFAULT ) [ TABLESPACE tablespacename ] ``` **subpartition\_definition\_list** contains the **subpartition\_definition** object of one or more level-2 partitions. The syntax is as follows: ``` SUBPARTITION subpartition_name { VALUES LESS THAN ( partition_value | MAXVALUE ) | VALUES ( partition_value [, ...] | DEFAULT ) } [ TABLESPACE tablespace ] ``` > \[!TIP]NOTICE > If the level-1 partition is a hash partition, you cannot use **ADD** to add a level-1 partition. If the level-2 partition is a hash partition, you cannot use **MODIFY** to add a level-2 partition. * The **drop\_clause** syntax is used to remove a partition from a specified partitioned table. The syntax can be used in level-1 partitions. ``` DROP PARTITION { partition_name | FOR ( partition_value ) } [ UPDATE GLOBAL INDEX ] ``` It can also be used in level-2 partitions. ``` DROP SUBPARTITION { subpartition_name | FOR ( partition_value, subpartition_value ) } [ UPDATE GLOBAL INDEX ] ``` > \[!TIP]NOTICE > > * If the level-1 partition is a hash partition, the level-1 partition cannot be deleted. If the level-2 partition is a hash partition, the level-2 partition cannot be deleted. > * At least one sub-partition must be retained. * The **split\_clause** syntax is used to split one partition into different partitions. ``` SPLIT SUBPARTITION { subpartition_name} { split_point_clause } [ UPDATE GLOBAL INDEX ] ``` The **split\_point\_clause** syntax used to specify a split point in the range partitioning policy is as follows: ``` AT ( subpartition_value ) INTO ( SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] , SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] ) ``` The **split\_point\_clause** syntax used to specify a split point in the list partitioning policy is as follows: ``` VALUES ( subpartition_value ) INTO ( SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] , SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] ) ``` > \[!TIP]NOTICE > > * The size of the split point should be in the range of the splitting partition key. > * One partition can be split into only two new partitions. > * In the range partitioning policy, the current partition is split into two partitions based on the split point. A partition smaller than the size specified by the split point is regarded as one partition, and a partition larger than the size specified by the split point is regarded as the other partition. Therefore, only one split point can be used in the range partitioning policy. In the list partitioning policy, there can be multiple but no more than 64 split points. These split points are extracted from the boundary values of the current partition as a new partition, and the remaining boundary values of the current partition are used as another new partition. * The **truncate\_clause** syntax is used to remove a specified partition from a partitioned table. ``` TRUNCATE SUBPARTITION { subpartition_name } [ UPDATE GLOBAL INDEX ] ``` ## Parameter Description * **table\_name** Specifies the name of a partitioned table. Value range: an existing partitioned table name. * **subpartition\_name** Specifies the name of a level-2 partition name. Value range: an existing level-2 partition name. * **tablespacename** Specifies which tablespace the partition moves to. Value range: an existing tablespace name. ## Examples See the examples in **CREATE TABLE SUBPARTITION**. --- --- url: /zh/docs/latest-lite/sql_reference/alter_table_subpartition.md --- # ALTER TABLE SUBPARTITION ## 功能描述 修改二级分区表分区,包括增删分区、清空分区、切割分区,以及修改分区属性等。 ## 注意事项 * 添加分区的表空间不能是PG\_GLOBAL。 * 添加分区的名称不能与该分区表已有一级分区和二级分区的名称相同。 * 添加分区的分区键值要和分区表的分区键的类型一致。 * 若添加RANGE分区,添加分区键值要大于分区表中最后一个范围分区的上边界。若需要在有MAXVALUE分区的表上新增分区,建议使用SPLIT语法。 * 若添加LIST分区,添加分区键值不能与现有分区键值重复。若需要在有DEFAULT分区的表上新增分区,建议使用SPLIT语法。 * 不支持添加HASH分区。只有一种情况例外,二级分区表的二级分区方式为HASH且一级分区方式不是HASH,此时支持新增一级分区并创建对应的二级分区。 * 如果目标分区表中已有分区数达到了最大值1048575,则不能继续添加分区。 * 当分区表只有一个一级分区或二级分区时,不能删除该分区。 * 不支持删除HASH分区。 * 选择分区使用PARTITION FOR()或SUBPARTITION FOR(),括号里指定值个数应该与定义分区时使用的列个数相同,并且一一对应。 * 切割分区只能对二级分区(叶子节点)进行切割,被切割分区只能是Range、List分区策略,不支持切割hash分区策略。List分区策略只能是default分区才能被切割。 * 只有分区表的所有者或者被授予了分区表ALTER权限的用户有权限执行ALTER TABLE PARTITION命令,系统管理员默认拥有此权限。 * 删除、切割、清空的操作会使Global索引失效,可以申明UPDATE GLOBAL INDEX子句同步更新索引。 * 如果删除、切割、清空操作不申明UPDATE GLOBAL INDEX子句,并发的DML业务有可能因为索引不可用而报错。 * 二级分区表不支持对一级分区和二级分区的交换分区、重命名分区名称和移动分区表空间的操作。 ## 语法格式 修改二级分区表分区包括修改表分区主语法、修改表分区名称的语法和重置分区ID的语法。 * 修改表分区主语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ``` 其中action统指如下分区维护子语法。当存在多个分区维护子句时,保证了分区的连续性,无论这些子句的排序如何,openGauss总会先执行DROP PARTITION再执行ADD PARTITION操作,最后顺序执行其它分区维护操作。 ``` row_clause | add_clause | drop_clause | split_clause | truncate_clause ``` * row\_clause子语法用于设置分区表的行迁移开关。 ``` { ENABLE | DISABLE } ROW MOVEMENT ``` * add\_clause子语法用于为指定的分区表添加一个或多个分区。语法可以作用在一级分区上。 ``` ADD {partition_less_than_item | partition_list_item } [ ( subpartition_definition_list ) ] ``` 也可以作用在二级分区上。 ``` MODIFY PARTITION partition_name ADD subpartition_definition ``` 其中,分区项partition\_less\_than\_item为RANGE分区定义语法,具体语法如下。 ``` PARTITION partition_name VALUES LESS THAN ( partition_value | MAXVALUE ) [ TABLESPACE tablespacename ] ``` 分区项partition\_list\_item为LIST分区定义语法,具体语法如下。 ``` PARTITION partition_name VALUES ( partition_value [, ...] | DEFAULT ) [ TABLESPACE tablespacename ] ``` subpartition\_definition\_list为1到多个二级分区subpartition\_definition对象,subpartition\_definition具体语法如下。 ``` SUBPARTITION subpartition_name [ VALUES LESS THAN ( partition_value | MAXVALUE ) | VALUES ( partition_value [, ...] | DEFAULT )] [ TABLESPACE tablespace ] ``` > \[!TIP]须知 > 若一级分区为HASH分区,不支持以ADD形式新增一级分区;若二级分区为HASH分区,不支持以MODIFY形式新增二级分区。 * drop\_clause子语法用于删除分区表中的指定分区。语法可以作用在一级分区上。 ``` DROP PARTITION { partition_name | FOR ( partition_value ) } [ UPDATE GLOBAL INDEX ] ``` 也可以作用在二级分区上。 ``` DROP SUBPARTITION { subpartition_name | FOR ( partition_value, subpartition_value ) } [ UPDATE GLOBAL INDEX ] ``` > \[!TIP]须知 > > * 若一级分区为HASH分区,不支持删除一级分区;若二级分区为HASH分区,不支持删除二级分区。 > * 不支持删除唯一子分区。 * split\_clause子语法用于把一个分区切割成多个分区。 ``` SPLIT SUBPARTITION { subpartition_name} { split_point_clause } [ UPDATE GLOBAL INDEX ] ``` 指定Range分区策略切割点split\_point\_clause的语法为: ``` AT ( subpartition_value ) INTO ( SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] , SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] ) ``` 指定List分区策略切割点split\_point\_clause的语法为: ``` VALUES ( subpartition_value ) INTO ( SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] , SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] ) ``` > \[!TIP]须知 > > * 切割点的大小要位于正在被切割的分区的分区键范围内。 > * 只能把一个分区切割成两个新分区。 > * Range分区策略切割点是把当前分区以此切割点分割为两个分区(小于此分割点为一个分区,大于此分割点为另一个分区),所以Range分区策略切割点只能为一个。List分区策略切割点可以为多个,但不超过64个,即把这些切割点从当前分区的边界值提取出来作为一个新分区,当前分区剩余边界值作为另一个新分区。 > * List分区只支持切割Default分区。 * truncate\_clause子语法用于清空分区表中的指定分区。语法可以作用在一级分区上。 ``` TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` 也可以作用在二级分区上。 ``` TRUNCATE SUBPARTITION { subpartition_name | FOR ( subpartition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` * 重置分区ID的语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RESET PARTITION; ``` ## 参数说明 * **table\_name** 分区表名。 取值范围:已存在的分区表名。 * **subpartition\_name** 二级分区名。 取值范围:已存在的二级分区名。 * **tablespacename** 指定分区要移动到哪个表空间。 取值范围:已存在的表空间名。 ## 示例 请参考CREATE TABLE SUBPARTITION的示例。 --- --- url: /zh/docs/latest/sql_reference/alter_table_subpartition.md --- # ALTER TABLE SUBPARTITION ## 功能描述 修改二级分区表分区,包括增删分区、清空分区、切割分区,以及修改分区属性等。 ## 注意事项 * 添加分区的表空间不能是PG\_GLOBAL。 * 添加分区的名称不能与该分区表已有一级分区和二级分区的名称相同。 * 添加分区的分区键值要和分区表的分区键的类型一致。 * 若添加RANGE分区,添加分区键值要大于分区表中最后一个范围分区的上边界。若需要在有MAXVALUE分区的表上新增分区,建议使用SPLIT语法。 * 若添加LIST分区,添加分区键值不能与现有分区键值重复。若需要在有DEFAULT分区的表上新增分区,建议使用SPLIT语法。 * 不支持添加HASH分区。只有一种情况例外,二级分区表的二级分区方式为HASH且一级分区方式不是HASH,此时支持新增一级分区并创建对应的二级分区。 * 如果目标分区表中已有分区数达到了最大值1048575,则不能继续添加分区。 * 当分区表只有一个一级分区或二级分区时,不能删除该分区。 * 不支持删除HASH分区。 * 选择分区使用PARTITION FOR()或SUBPARTITION FOR(),括号里指定值个数应该与定义分区时使用的列个数相同,并且一一对应。 * 切割分区只能对二级分区(叶子节点)进行切割,被切割分区只能是Range、List分区策略,不支持切割hash分区策略。List分区策略只能是default分区才能被切割。 * 只有分区表的所有者或者被授予了分区表ALTER权限的用户有权限执行ALTER TABLE PARTITION命令,系统管理员默认拥有此权限。 * 删除、切割、清空的操作会使Global索引失效,可以申明UPDATE GLOBAL INDEX子句同步更新索引。 * 如果删除、切割、清空操作不申明UPDATE GLOBAL INDEX子句,并发的DML业务有可能因为索引不可用而报错。 * 二级分区表不支持对一级分区和二级分区的交换分区、重命名分区名称和移动分区表空间的操作。 ## 语法格式 修改二级分区表分区包括修改表分区主语法、修改表分区名称的语法和重置分区ID的语法。 * 修改表分区主语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ``` 其中action统指如下分区维护子语法。当存在多个分区维护子句时,保证了分区的连续性,无论这些子句的排序如何,openGauss总会先执行DROP PARTITION再执行ADD PARTITION操作,最后顺序执行其它分区维护操作。 ``` row_clause | add_clause | drop_clause | split_clause | truncate_clause ``` * row\_clause子语法用于设置分区表的行迁移开关。 ``` { ENABLE | DISABLE } ROW MOVEMENT ``` * add\_clause子语法用于为指定的分区表添加一个或多个分区。语法可以作用在一级分区上。 ``` ADD {partition_less_than_item | partition_list_item } [ ( subpartition_definition_list ) ] ``` 也可以作用在二级分区上。 ``` MODIFY PARTITION partition_name ADD subpartition_definition ``` 其中,分区项partition\_less\_than\_item为RANGE分区定义语法,具体语法如下。 ``` PARTITION partition_name VALUES LESS THAN ( partition_value | MAXVALUE ) [ TABLESPACE tablespacename ] ``` 分区项partition\_list\_item为LIST分区定义语法,具体语法如下。 ``` PARTITION partition_name VALUES ( partition_value [, ...] | DEFAULT ) [ TABLESPACE tablespacename ] ``` subpartition\_definition\_list为1到多个二级分区subpartition\_definition对象,subpartition\_definition具体语法如下。 ``` SUBPARTITION subpartition_name [ VALUES LESS THAN ( partition_value | MAXVALUE ) | VALUES ( partition_value [, ...] | DEFAULT )] [ TABLESPACE tablespace ] ``` > \[!TIP]须知 > 若一级分区为HASH分区,不支持以ADD形式新增一级分区;若二级分区为HASH分区,不支持以MODIFY形式新增二级分区。 * drop\_clause子语法用于删除分区表中的指定分区。语法可以作用在一级分区上。 ``` DROP PARTITION { partition_name | FOR ( partition_value ) } [ UPDATE GLOBAL INDEX ] ``` 也可以作用在二级分区上。 ``` DROP SUBPARTITION { subpartition_name | FOR ( partition_value, subpartition_value ) } [ UPDATE GLOBAL INDEX ] ``` > \[!TIP]须知 > > * 若一级分区为HASH分区,不支持删除一级分区;若二级分区为HASH分区,不支持删除二级分区。 > * 不支持删除唯一子分区。 * split\_clause子语法用于把一个分区切割成多个分区。 ``` SPLIT SUBPARTITION { subpartition_name} { split_point_clause } [ UPDATE GLOBAL INDEX ] ``` 指定Range分区策略切割点split\_point\_clause的语法为: ``` AT ( subpartition_value ) INTO ( SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] , SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] ) ``` 指定List分区策略切割点split\_point\_clause的语法为: ``` VALUES ( subpartition_value ) INTO ( SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] , SUBPARTITION subpartition_name [ TABLESPACE tablespacename ] ) ``` > \[!TIP]须知 > > * 切割点的大小要位于正在被切割的分区的分区键范围内。 > * 只能把一个分区切割成两个新分区。 > * Range分区策略切割点是把当前分区以此切割点分割为两个分区(小于此分割点为一个分区,大于此分割点为另一个分区),所以Range分区策略切割点只能为一个。List分区策略切割点可以为多个,但不超过64个,即把这些切割点从当前分区的边界值提取出来作为一个新分区,当前分区剩余边界值作为另一个新分区。 > * List分区只支持切割Default分区。 * truncate\_clause子语法用于清空分区表中的指定分区。语法可以作用在一级分区上。 ``` TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` 也可以作用在二级分区上。 ``` TRUNCATE SUBPARTITION { subpartition_name | FOR ( subpartition_value [, ...] ) } [ UPDATE GLOBAL INDEX ] ``` * 重置分区ID的语法。 ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RESET PARTITION; ``` ## 参数说明 * **table\_name** 分区表名。 取值范围:已存在的分区表名。 * **subpartition\_name** 二级分区名。 取值范围:已存在的二级分区名。 * **tablespacename** 指定分区要移动到哪个表空间。 取值范围:已存在的表空间名。 ## 示例 请参考CREATE TABLE SUBPARTITION的示例。 --- --- url: /en/docs/latest-lite/sql_reference/alter_tablespace.md --- # ALTER TABLESPACE ## Function **ALTER TABLESPACE** modifies the attributes of a tablespace. ## Precautions * Only the tablespace owner or a user granted with the ALTER permission can run the **ALTER TABLESPACE** command. The system administrator has this permission by default. To modify a tablespace owner, you must be the tablespace owner or system administrator and a member of the new owner role. * To change the owner, you must also be a direct or indirect member of the new owning role. > \[!NOTE]NOTE > If **new\_owner** is the same as **old\_owner**, the current user will not be verified. A message indicating successful **ALTER** execution is displayed. ## Syntax * The syntax of renaming a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name; ``` * The syntax of setting the owner of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name OWNER TO new_owner; ``` * The syntax of setting the attributes of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name SET ( {tablespace_option = value} [, ... ] ); ``` * The syntax of resetting the attributes of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name RESET ( { tablespace_option } [, ...] ); ``` * The syntax of setting the quota of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name RESIZE MAXSIZE { UNLIMITED | 'space_size'}; ``` ## Parameter Description * **tablespace\_name** Specifies the tablespace to be modified. Value range: an existing table name * **new\_tablespace\_name** Specifies the new name of a tablespace. The new name cannot start with **PG\_**. Value range: a string. It must comply with the naming convention. * **new\_owner** Specifies the new owner of the tablespace. Value range: an existing username * **tablespace\_option** Sets or resets the parameters of a tablespace. Value range: * seq\_page\_cost: sets the optimizer to calculate the cost of obtaining disk pages in sequence. The default value is **1.0**. * **random\_page\_cost**: sets the optimizer to calculate the cost of obtaining disk pages in a non-sequential manner. The default value is **4.0**. > \[!NOTE]NOTE > > * The value of **random\_page\_cost** is relative to that of **seq\_page\_cost**. It is meaningless when the value is equal to or less than the value of **seq\_page\_cost**. > * The prerequisite for the default value **4.0** is that the optimizer uses indexes to scan table data and the hit ratio of table data in the cache is about 90%. > * If the size of the table data space is smaller than that of the physical memory, decrease the value to a proper level. On the contrary, if the hit ratio of table data in the cache is lower than 90%, increase the value. > * If random-access memory like SSD is adopted, the value can be decreased to a certain degree to reflect the cost of true random scan. Value range: a positive floating point number * **RESIZE MAXSIZE** Resets the maximum size of tablespace. Value range: * **UNLIMITED**: No limit is set for the tablespace. * Determined by **space\_size**. For details about the format, see [CREATE TABLESPACE](create_tablespace.md). > \[!NOTE]NOTE > > * If the adjusted quota is smaller than the current tablespace usage, the adjustment is successful. You need to decrease the tablespace usage to a value less than the new quota before writing data to the tablespace. > * You can also use the following statement to change the value of **MAXSIZE**: > ```` >``` ```` ```` >ALTER TABLESPACE tablespace_name RESIZE MAXSIZE > { 'UNLIMITED' | 'space_size'}; >``` ```` ## Examples See [Examples](create_tablespace.md#en-us_topic_0283137328_en-us_topic_0237122120_en-us_topic_0059777670_s4e5e97caa377440d87fad0d49b56323e) in **CREATE TABLESPACE**. ## Helpful Links [CREATE TABLESPACE](create_tablespace.md) and [DROP TABLESPACE](drop_tablespace.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-alter-tablespace.md --- # ALTER TABLESPACE ## Function Modifies the attributes of a tablespace. ## Precautions Compared with the original openGauss, Dolphin modifies the ALTER TABLESPACE syntax as follows: 1. The WAIT option is added for syntax compatibility only. 2. The ENGINE \[=] engine\_name option is added for syntax compatibility only. ## Syntax * The syntax of renaming a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name [ alter_option_list [ ... ] ]; ``` * The syntax of setting the owner of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name OWNER TO new_owner [ alter_option_list [ ... ] ]; ``` * The syntax of setting the attributes of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name SET ( {tablespace_option = value} [, ... ] ) [ alter_option_list [ ... ] ]; ``` * The syntax of resetting the attributes of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name RESET ( { tablespace_option } [, ...] ) [ alter_option_list [ ... ] ]; ``` * The syntax for setting the quota of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name RESIZE MAXSIZE { UNLIMITED | 'space_size'} [ alter_option_list [ ... ] ]; ``` ``` Where alter_option_list is: WAIT | ENGINE [=] engine_name ``` ## Parameter Description * **tablespace\_name** Specifies the tablespace to be modified. Value range: an existing tablespace name * **new\_tablespace\_name** Specifies the new name of a tablespace. The new name cannot start with PG\_. Value range: a string. It must comply with the naming convention. * **new\_owner** Specifies the new owner of the tablespace. Value range: an existing username * **tablespace\_option** Sets or resets the parameters of a tablespace. Value: * **seq\_page\_cost**: sets the optimizer to calculate the cost of obtaining the disk page in sequence one time. The default value is **1.0**. * **random\_page\_cost**: sets the optimizer to calculate the cost of obtaining the disk page in random sequence one time. The default value is **4.0**. > \[!NOTE]NOTE > > * random\_page\_cost is relative to seq\_page\_cost. It is meaningless when it is equal to or less than seq\_page\_cost. > * The prerequisite of using **4.0** as the default value is that the optimizer uses indexes to scan the table data and that the hit ratio of data in the cache reaches about 90%. > * If the table data space is less than the physical memory, decrease the value to a proper level. If the hit ratio of data in the cache is lower than 90%, increase the value. > * If random-access memory like SSD is adopted, the value can be decreased to a certain degree to reflect the cost of true random scan. A positive floating point. * **RESIZE MAXSIZE** Resets the maximum size of tablespace. Value: * **UNLIMITED**: No limit is set for this tablespace. * The value is determined by space\_size. For details about the format, see [CREATE TABLESPACE](https://docs.opengauss.org/en/docs/latest/sql_reference/create_tablespace.html). > \[!NOTE]NOTE > > * If the adjusted quota is smaller than the current tablespace usage, the adjustment is successful. You need to decrease the tablespace usage to a value less than the new quota before writing data to the tablespace. > * It can be used when you are modifying **MAXSIZE**: > > ``` > ALTER TABLESPACE tablespace_name RESIZE MAXSIZE > { 'UNLIMITED' | 'space_size'}; > ``` * **engine\_name** This parameter is meaningless. Value: a combination of any characters ## Examples ``` --Create a tablespace. openGauss=# CREATE TABLESPACE ds_location1 RELATIVE LOCATION 'tablespace/tablespace_1'; --Create user joe. openGauss=# CREATE ROLE joe IDENTIFIED BY 'xxxxxxxxx'; --Create user jay. openGauss=# CREATE ROLE jay IDENTIFIED BY 'xxxxxxxxx'; --Create an ordinary tablespace and set its owner to user joe. openGauss=# CREATE TABLESPACE ds_location2 OWNER joe RELATIVE LOCATION 'tablespace/tablespace_1'; --Rename the tablespace ds_location1 to ds_location3 and specify option WAIT. The actual function is not affected. openGauss=# ALTER TABLESPACE ds_location1 RENAME TO ds_location3 WAIT; --Change the owner of the ds_location2 tablespace by specifying option ENGINE. The actual function is not affected. openGauss=# ALTER TABLESPACE ds_location2 OWNER TO jay ENGINE = 'test'; --Change the quota of the ds_location2 tablespace and specify the options ENGINE and WAIT. The actual function is not affected. openGauss=# ALTER TABLESPACE ds_location2 RESIZE MAXSIZE UNLIMITED ENGINE = 'test' WAIT; --Delete a tablespace. openGauss=# DROP TABLESPACE ds_location2 ENGINE = 'test2'; openGauss=# DROP TABLESPACE ds_location3; --Delete the user. openGauss=# DROP ROLE joe; openGauss=# DROP ROLE jay; ``` ## Helpful Links [CREATE TABLESPACE](dolphin-create-tablespace.md), [DROP TABLESPACE](dolphin-drop-tablespace.md) --- --- url: /en/docs/latest/sql_reference/alter_tablespace.md --- # ALTER TABLESPACE ## Function **ALTER TABLESPACE** modifies the attributes of a tablespace. ## Precautions * Only the tablespace owner or a user granted with the ALTER permission can run the **ALTER TABLESPACE** command. The system administrator has this permission by default. To modify a tablespace owner, you must be the tablespace owner or system administrator and a member of the new owner role. * To change the owner, you must also be a direct or indirect member of the new owning role. > \[!NOTE]NOTE > If **new\_owner** is the same as **old\_owner**, the current user will not be verified. A message indicating successful **ALTER** execution is displayed. ## Syntax * The syntax of renaming a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name; ``` * The syntax of setting the owner of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name OWNER TO new_owner; ``` * The syntax of setting the attributes of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name SET ( {tablespace_option = value} [, ... ] ); ``` * The syntax of resetting the attributes of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name RESET ( { tablespace_option } [, ...] ); ``` * The syntax of setting the quota of a tablespace is as follows: ``` ALTER TABLESPACE tablespace_name RESIZE MAXSIZE { UNLIMITED | 'space_size'}; ``` ## Parameter Description * **tablespace\_name** Specifies the tablespace to be modified. Value range: an existing table name * **new\_tablespace\_name** Specifies the new name of a tablespace. The new name cannot start with **PG\_**. Value range: a string. It must comply with the naming convention. * **new\_owner** Specifies the new owner of the tablespace. Value range: an existing username * **tablespace\_option** Sets or resets the parameters of a tablespace. Value range: * seq\_page\_cost: sets the optimizer to calculate the cost of obtaining disk pages in sequence. The default value is **1.0**. * **random\_page\_cost**: sets the optimizer to calculate the cost of obtaining disk pages in a non-sequential manner. The default value is **4.0**. > \[!NOTE]NOTE > > * The value of **random\_page\_cost** is relative to that of **seq\_page\_cost**. It is meaningless when the value is equal to or less than the value of **seq\_page\_cost**. > * The prerequisite for the default value **4.0** is that the optimizer uses indexes to scan table data and the hit ratio of table data in the cache is about 90%. > * If the size of the table data space is smaller than that of the physical memory, decrease the value to a proper level. On the contrary, if the hit ratio of table data in the cache is lower than 90%, increase the value. > * If random-access memory like SSD is adopted, the value can be decreased to a certain degree to reflect the cost of true random scan. Value range: a positive floating point number * **RESIZE MAXSIZE** Resets the maximum size of tablespace. Value range: * **UNLIMITED**: No limit is set for the tablespace. * Determined by **space\_size**. For details about the format, see [CREATE TABLESPACE](create_tablespace.md). > \[!NOTE]NOTE > > * If the adjusted quota is smaller than the current tablespace usage, the adjustment is successful. You need to decrease the tablespace usage to a value less than the new quota before writing data to the tablespace. > * You can also use the following statement to change the value of **MAXSIZE**: > ```` >``` ```` ```` >ALTER TABLESPACE tablespace_name RESIZE MAXSIZE > { 'UNLIMITED' | 'space_size'}; >``` ```` ## Examples See [Examples](create_tablespace.md#en-us_topic_0283137328_en-us_topic_0237122120_en-us_topic_0059777670_s4e5e97caa377440d87fad0d49b56323e) in **CREATE TABLESPACE**. ## Helpful Links [CREATE TABLESPACE](create_tablespace.md) and [DROP TABLESPACE](drop_tablespace.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-ALTER-TABLESPACE.md --- # ALTER TABLESPACE ## 功能描述 修改表空间的属性。 ## 注意事项 相比于原始的openGauss,dolphin对于`ALTER TABLESPACE`语法的修改主要为: 1. 新增`WAIT`可选项,无实际意义,仅作语法兼容。 2. 新增`ENGINE [=] engine_name`可选项,无实际意义,仅作语法兼容。 ## 语法格式 * 重命名表空间的语法。 ``` ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name [ alter_option_list [ ... ] ]; ``` * 设置表空间所有者的语法。 ``` ALTER TABLESPACE tablespace_name OWNER TO new_owner [ alter_option_list [ ... ] ]; ``` * 设置表空间属性的语法。 ``` ALTER TABLESPACE tablespace_name SET ( {tablespace_option = value} [, ... ] ) [ alter_option_list [ ... ] ]; ``` * 重置表空间属性的语法。 ``` ALTER TABLESPACE tablespace_name RESET ( { tablespace_option } [, ...] ) [ alter_option_list [ ... ] ]; ``` * 设置表空间限额的语法。 ``` ALTER TABLESPACE tablespace_name RESIZE MAXSIZE { UNLIMITED | 'space_size'} [ alter_option_list [ ... ] ]; ``` ``` 其中 alter_option_list 为: WAIT | ENGINE [=] engine_name ``` ## 参数说明 * **tablespace\_name** 要修改的表空间。 取值范围:已存在的表空间名。 * **new\_tablespace\_name** 表空间的新名称。 新名称不能以“PG\_”开头。 取值范围:字符串,符合标识符命名规范。 * **new\_owner** 表空间的新所有者。 取值范围:已存在的用户名。 * **tablespace\_option** 设置或者重置表空间的参数。 取值范围: * seq\_page\_cost:设置优化器计算一次顺序获取磁盘页面的开销。缺省为1.0。 * random\_page\_cost:设置优化器计算一次非顺序获取磁盘页面的开销。缺省为4.0。 > \[!NOTE]说明 > > * random\_page\_cost是相对于seq\_page\_cost的取值,等于或者小于seq\_page\_cost时毫无意义。 > * 默认值为4.0的前提条件是,优化器采用索引来扫描表数据,并且表数据在cache中命中率可以90%左右。 > * 如果表数据空间要比物理内存小,那么减小该值到一个适当水平;相反地,如果表数据在cache中命中率要低于90%,那么适当增大该值。 > * 如果采用了类似于SSD的随机访问代价较小的存储器,可以适当减小该值,以反映真正的随机扫描代价。 value的取值范围:正的浮点类型。 * **RESIZE MAXSIZE** 重新设置表空间限额的数值。 取值范围: * UNLIMITED,该表空间不设置限额。 * 由space\_size来确定,其格式参考[CREATE TABLESPACE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_tablespace.html)。 > \[!NOTE]说明 > > * 若调整后的限额值比当前表空间实际使用的值要小,调整操作可以执行成功,后续用户需要将该表空间的使用值降低到新限额值之下,才能继续往该表空间中写入数据。 > * 修改参数MAXSIZE时也可使用: > ```` >``` ```` ```` >ALTER TABLESPACE tablespace_name RESIZE MAXSIZE > { 'UNLIMITED' | 'space_size'}; >``` ```` * **engine\_name** 无实际意义。 取值范围:任意字符串。 ## 示例 ``` --创建表空间。 openGauss=# CREATE TABLESPACE ds_location1 RELATIVE LOCATION 'tablespace/tablespace_1'; --创建用户joe。 openGauss=# CREATE ROLE joe IDENTIFIED BY 'xxxxxxxxx'; --创建用户jay。 openGauss=# CREATE ROLE jay IDENTIFIED BY 'xxxxxxxxx'; --创建表空间,且所有者指定为用户joe。 openGauss=# CREATE TABLESPACE ds_location2 OWNER joe RELATIVE LOCATION 'tablespace/tablespace_1'; --把表空间ds_location1重命名为ds_location3,指定option WAIT,不影响实际功能。 openGauss=# ALTER TABLESPACE ds_location1 RENAME TO ds_location3 WAIT; --改变表空间ds_location2的所有者,指定option ENGINE,不影响实际功能。 openGauss=# ALTER TABLESPACE ds_location2 OWNER TO jay ENGINE = 'test'; --改变表空间ds_location2的限额,同时指定option ENGINE和WAIT,不影响实际功能。 openGauss=# ALTER TABLESPACE ds_location2 RESIZE MAXSIZE UNLIMITED ENGINE = 'test' WAIT; --删除表空间。 openGauss=# DROP TABLESPACE ds_location2 ENGINE = 'test2'; openGauss=# DROP TABLESPACE ds_location3; --删除用户。 openGauss=# DROP ROLE joe; openGauss=# DROP ROLE jay; ``` ## 相关链接 [CREATE TABLESPACE](dolphin-CREATE-TABLESPACE.md),[DROP TABLESPACE](dolphin-DROP-TABLESPACE.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_tablespace.md --- # ALTER TABLESPACE ## 功能描述 修改表空间的属性。 ## 注意事项 * 只有表空间的所有者或者被授予了表空间ALTER权限的用户有权限执行ALTER TABLESPACE命令,系统管理员默认拥有此权限。但要修改表空间的所有者,当前用户必须是该表空间的所有者或系统管理员,且该用户是新所有者角色的成员。 * 要修改表空间的所有者A为B,则A必须是B的直接或者间接成员。 > \[!NOTE]说明 > > 如果new\_owner与old\_owner一致,此处不再校验当前执行操作的用户是否具有修改权限,而直接显示ALTER成功。 ## 语法格式 * 重命名表空间的语法。 ``` ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name; ``` * 设置表空间所有者的语法。 ``` ALTER TABLESPACE tablespace_name OWNER TO new_owner; ``` * 设置表空间属性的语法。 ``` ALTER TABLESPACE tablespace_name SET ( {tablespace_option = value} [, ... ] ); ``` * 重置表空间属性的语法。 ``` ALTER TABLESPACE tablespace_name RESET ( { tablespace_option } [, ...] ); ``` * 设置表空间限额的语法 ``` ALTER TABLESPACE tablespace_name RESIZE MAXSIZE { UNLIMITED | 'space_size'}; ``` ## 参数说明 * **tablespace\_name** 要修改的表空间。 取值范围:已存在的表空间名。 * **new\_tablespace\_name** 表空间的新名称。 新名称不能以"PG\_"开头。 取值范围:字符串,符合标识符命名规范。 * **new\_owner** 表空间的新所有者。 取值范围:已存在的用户名。 * **tablespace\_option** 设置或者重置表空间的参数。 取值范围: * seq\_page\_cost:设置优化器计算一次顺序获取磁盘页面的开销。缺省为1.0。 * random\_page\_cost:设置优化器计算一次非顺序获取磁盘页面的开销。缺省为4.0。 > \[!NOTE]说明 > > * random\_page\_cost是相对于seq\_page\_cost的取值,等于或者小于seq\_page\_cost时毫无意义。 > * 默认值为4.0的前提条件是,优化器采用索引来扫描表数据,并且表数据在cache中命中率可以90%左右。 > * 如果表数据空间要比物理内存小,那么减小该值到一个适当水平;相反地,如果表数据在cache中命中率要低于90%,那么适当增大该值。 > * 如果采用了类似于SSD的随机访问代价较小的存储器,可以适当减小该值,以反映真正的随机扫描代价。 value的取值范围:正的浮点类型。 * **RESIZE MAXSIZE** 重新设置表空间限额的数值。 取值范围: * UNLIMITED,该表空间不设置限额。 * 由space\_size来确定,其格式参考[CREATE TABLESPACE](create_tablespace.md)。 > \[!NOTE]说明 > > * 若调整后的限额值比当前表空间实际使用的值要小,调整操作可以执行成功,后续用户需要将该表空间的使用值降低到新限额值之下,才能继续往该表空间中写入数据。 > * 修改参数MAXSIZE时也可使用: > ```` >``` ```` ```` >ALTER TABLESPACE tablespace_name RESIZE MAXSIZE > { 'UNLIMITED' | 'space_size'}; >``` ```` ## 示例 请参考CREATE TABLESPACE的[示例](create_tablespace.md#zh-cn_topic_0283137328_zh-cn_topic_0237122120_zh-cn_topic_0059777670_s4e5e97caa377440d87fad0d49b56323e)。 ## 相关链接 [CREATE TABLESPACE](create_tablespace.md),[DROP TABLESPACE](drop_tablespace.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-ALTER-TABLESPACE.md --- # ALTER TABLESPACE ## 功能描述 修改表空间的属性。 ## 注意事项 相比于原始的openGauss,dolphin对于`ALTER TABLESPACE`语法的修改主要为: 1. 新增`WAIT`可选项,无实际意义,仅作语法兼容。 2. 新增`ENGINE [=] engine_name`可选项,无实际意义,仅作语法兼容。 ## 语法格式 * 重命名表空间的语法。 ``` ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name [ alter_option_list [ ... ] ]; ``` * 设置表空间所有者的语法。 ``` ALTER TABLESPACE tablespace_name OWNER TO new_owner [ alter_option_list [ ... ] ]; ``` * 设置表空间属性的语法。 ``` ALTER TABLESPACE tablespace_name SET ( {tablespace_option = value} [, ... ] ) [ alter_option_list [ ... ] ]; ``` * 重置表空间属性的语法。 ``` ALTER TABLESPACE tablespace_name RESET ( { tablespace_option } [, ...] ) [ alter_option_list [ ... ] ]; ``` * 设置表空间限额的语法。 ``` ALTER TABLESPACE tablespace_name RESIZE MAXSIZE { UNLIMITED | 'space_size'} [ alter_option_list [ ... ] ]; ``` ``` 其中 alter_option_list 为: WAIT | ENGINE [=] engine_name ``` ## 参数说明 * **tablespace\_name** 要修改的表空间。 取值范围:已存在的表空间名。 * **new\_tablespace\_name** 表空间的新名称。 新名称不能以“PG\_”开头。 取值范围:字符串,符合标识符命名规范。 * **new\_owner** 表空间的新所有者。 取值范围:已存在的用户名。 * **tablespace\_option** 设置或者重置表空间的参数。 取值范围: * seq\_page\_cost:设置优化器计算一次顺序获取磁盘页面的开销。缺省为1.0。 * random\_page\_cost:设置优化器计算一次非顺序获取磁盘页面的开销。缺省为4.0。 > \[!NOTE]说明 > > * random\_page\_cost是相对于seq\_page\_cost的取值,等于或者小于seq\_page\_cost时毫无意义。 > * 默认值为4.0的前提条件是,优化器采用索引来扫描表数据,并且表数据在cache中命中率可以90%左右。 > * 如果表数据空间要比物理内存小,那么减小该值到一个适当水平;相反地,如果表数据在cache中命中率要低于90%,那么适当增大该值。 > * 如果采用了类似于SSD的随机访问代价较小的存储器,可以适当减小该值,以反映真正的随机扫描代价。 value的取值范围:正的浮点类型。 * **RESIZE MAXSIZE** 重新设置表空间限额的数值。 取值范围: * UNLIMITED,该表空间不设置限额。 * 由space\_size来确定,其格式参考[CREATE TABLESPACE](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_tablespace.html)。 > \[!NOTE]说明 > > * 若调整后的限额值比当前表空间实际使用的值要小,调整操作可以执行成功,后续用户需要将该表空间的使用值降低到新限额值之下,才能继续往该表空间中写入数据。 > * 修改参数MAXSIZE时也可使用: > > ``` > ALTER TABLESPACE tablespace_name RESIZE MAXSIZE > { 'UNLIMITED' | 'space_size'}; > ``` * **engine\_name** 无实际意义。 取值范围:任意字符串。 ## 示例 ``` --创建表空间。 openGauss=# CREATE TABLESPACE ds_location1 RELATIVE LOCATION 'tablespace/tablespace_1'; --创建用户joe。 openGauss=# CREATE ROLE joe IDENTIFIED BY 'xxxxxxxxx'; --创建用户jay。 openGauss=# CREATE ROLE jay IDENTIFIED BY 'xxxxxxxxx'; --创建表空间,且所有者指定为用户joe。 openGauss=# CREATE TABLESPACE ds_location2 OWNER joe RELATIVE LOCATION 'tablespace/tablespace_1'; --把表空间ds_location1重命名为ds_location3,指定option WAIT,不影响实际功能。 openGauss=# ALTER TABLESPACE ds_location1 RENAME TO ds_location3 WAIT; --改变表空间ds_location2的所有者,指定option ENGINE,不影响实际功能。 openGauss=# ALTER TABLESPACE ds_location2 OWNER TO jay ENGINE = 'test'; --改变表空间ds_location2的限额,同时指定option ENGINE和WAIT,不影响实际功能。 openGauss=# ALTER TABLESPACE ds_location2 RESIZE MAXSIZE UNLIMITED ENGINE = 'test' WAIT; --删除表空间。 openGauss=# DROP TABLESPACE ds_location2 ENGINE = 'test2'; openGauss=# DROP TABLESPACE ds_location3; --删除用户。 openGauss=# DROP ROLE joe; openGauss=# DROP ROLE jay; ``` ## 相关链接 [CREATE TABLESPACE](dolphin-CREATE-TABLESPACE.md),[DROP TABLESPACE](dolphin-DROP-TABLESPACE.md) --- --- url: /zh/docs/latest/ograc/sql_reference/alter_tablespace.md --- # ALTER TABLESPACE ## 功能描述 修改一个已存在的表空间的属性。 ## 注意事项 * 只有表空间的所有者或者被授予了表空间ALTER权限的用户有权限执行ALTER TABLESPACE命令,系统管理员默认拥有此权限。 * 执行如下操作时需要在数据库为open的状态下执行: * 增加数据文件 * 删除数据文件 * 修改文件的AUTOEXTEND属性 * 重命名表空间 * 执行如下操作时需要在数据库为open restricted的状态下执行: * 修改数据文件名称 * 只能对用户的表空间设置AUTOOFFLINE的属性 ## 语法格式 重命名表空间: ```sql ALTER TABLESPACE 'tablespace_name' RENAME TO 'new_tablespace_name' ``` 收缩表空间大小和压缩表空间大小: ``` ALTER TABLESPACE 'tablespace_name' { SHRINK SPACE KEEP integer [ K | M | G | T ] | PUNCH { SIZE integer [ K | M | G ] } } ``` 修改表空间的AUTOOFFLINE和AUTOEXTEND属性: ``` ALTER TABLESPACE 'tablespace_name' { AUTOOFFLINE { ON | OFF } | AUTOEXTEND { OFF | ON [ NEXT integer [ K | M | G ] ] [ MAXSIZE { integer [ K | M | G ] | UNLIMITED }] } } ``` 向表空间中添加和删除数据文件: ``` ALTER TABLESPACE 'tablespace_name' { ADD DATAFILE { 'file_name' SIZE integer [ K | M | G ] [COMPRESS] [AUTOEXTEND { OFF | ON [ NEXT integer [ K | M | G ] ] [ MAXSIZE { integer [ K | M | G ] | UNLIMITED }] } ] [ segments integer ] } | DROP DATAFILE 'file_name' } ``` 重命名表空间中数据文件: ``` ALTER TABLESPACE 'tablespace_name' RENAME DATAFILE 'old_file_name' TO 'new_file_name' ``` ## 参数说明 * **公共参数**: integer: 表示非0的正整数范围。 K: 单位KB M: 单位MB G: 单位GB T: 单位TB * **tablespace\_name**: 要修改的表空间。 取值范围:已存在的表空间名。 * **new\_tablespace\_name**: 表空间的新名称。 取值范围:字符串,符合标识符命名规范。 * **RENAME TO 'new\_tablespace\_name'**: 修改表空间的名称 * **SHRINK SPACE KEEP integer \[ K | M | G | T ]**: 收缩表空间大小。 * 在RESTRICTED模式且保证无残留事务的前提下,可以用于重建UNDO表空间。 * 在OPEN模式下可以对除了TEMP表空间之外的其他表空间进行收缩。 * TEMP表空间需要在OPEN RESTRICT模式下进行收缩。 * 表空间实际可收缩的空间大小依赖当前表空间中的各个数据文件从高水位线开始的连续空闲空间大小。 * 当用户指定的KEEP SIZE小于实际可保留的空间时,以用户指定的保留空间大小为准,当用户指定的KEEP SIZE大于等于实际可保留的空间时,以实际可保留的空间大小为准 * SHRINK操作被中断后可能造成信息残留。 取值范围:`1M - 8000T` * **PUNCH { SIZE integer \[ K | M | G ] }**: 压缩表空间大小,对表空间中的空闲页面进行压缩 * 加密、临时、UNDO、默认表空间不可进行压缩。 * 被压缩的页面无法被原表空间复用。 取值范围:`1M - 500G` * **AUTOOFFLINE { ON | OFF }**: 设置表空间开启自动离线的功能 * 开启自动离线的表空间,在数据库启动过程中如果存在文件打开失败的问题时,会自动离线,启动之后异常不会自动离线 * 开启自动离线的表空间,在数据库启动过程中如果存在文件发生损坏或其他故障时,可以将数据库加载到Mount状态;如果没有开启自动离线,表空间中文件发生损坏或其他故障时,数据库将无法正常启动 * **AUTOEXTEND { OFF | ON \[ NEXT integer \[ K | M | G ] ] \[ MAXSIZE { integer \[ K | M | G ] | UNLIMITED }] }**: 设置表空间或数据文件的自动扩展属性 * 不指定AUTOEXTEND子句或者设置AUTOEXTEND为OFF时,默认不自动扩展空间 * **设置AUTOEXTEND为ON时,可设置的子属性如下**: * NEXT指定自动扩展的大小,未指定时默认16MB * MAXSIZE指定数据文件自动扩展的上限,未指定或设置为UNLIMITED时,UNDO表空间的上限为32GB,其他表空间的上限为8TB,用户指定的上限大小不可超过该范围。 * 当MAXSIZE和NEXT同时设置时,指定的上限值不得小于指定的自动扩展值 * **ADD DATAFILE { 'file\_name' SIZE integer \[ K | M | G ] \[COMPRESS] \[AUTOEXTEND ...] \[ segments integer ] }**: 向表空间中添加数据文件 * `file_name`为数据文件名,如果指定文件名是相对路径的格式时,默认保存在数据目录的data目录下 * COMPRESS表示指定新增的数据文件为压缩属性,压缩文件用于存储压缩属性的表,当使用压缩表特性时,需要同步在对应表空间下创建压缩文件。 * AUTOEXTEND属性参考上一个描述 * **segments integer** 表示需要扩展的SEGMENT数量,SEGMENTS子句仅在RESTRICT模式下可用,且仅支持UNDO表空间,仅支持单次添加单个数据文件。SEGMENTS子句的取值下限为1,在\_UNDO\_SEGMENTS尚未达到1024上限时,子句的上限取值为`1024 - 当前UNDO_SEGMENTS的大小`。若\_UNDO\_SEGMENTS已经为1024了,那么此时无法继续扩展。SEGMENTS子句是一种在受限模式下使用的补救措施,其过程包含了多个涉及资源持久化的过程,所以无法保证整个端到端操作的原子性。如果在使用SEGMENTS子句的过程中出现异常,用户需要根据实际情况自行处理。 * UNDO SEGMENTS扩展和UNDO SPACE切换在机制上冲突,当数据库执行过UNDO SEGMENTS扩展后,再执行UNDO SPACE切换时会报错。 * **RENAME DATAFILE 'old\_file\_name' TO 'new\_file\_name'**: 重命名表空间中的数据文件 ## 示例 * **向表空间tbs\_student中添加数据文件。** ``` -- 创建表空间tbs_student。 CREATE TABLESPACE tbs_student DATAFILE '-dfile_tbs_01' SIZE 32M AUTOEXTEND ON NEXT 10M; -- 向表空间tbs_student中添加数据文件my_datafile(大小是32M),manager_dfile(大小是32M)和section_dfile(大小是32M)。 ALTER TABLESPACE tbs_student ADD DATAFILE '-my_datafile' SIZE 32M, 'manager_dfile' SIZE 32M, 'section_dfile' SIZE 32M; ``` * **删除表空间tbs\_student中的数据文件manager\_dfile。** ``` ALTER TABLESPACE tbs_student DROP DATAFILE 'manager_dfile'; ``` * **OPEN RESTRICTED状态下将表空间tbs\_student中的数据文件my\_datafile重命名为new\_my\_datafile。** ``` -- OPEN RESTRICTED状态下将表空间tbs_student中的数据文件my_datafile重命名为new_my_datafile ALTER TABLESPACE tbs_student RENAME DATAFILE 'my_datafile' TO 'new_my_datafile'; ``` * **修改表空间tbs\_student为自动扩展,数据插满时,表空间自动扩展,可手动指定每次扩展大小。** ``` ALTER TABLESPACE tbs_student AUTOEXTEND ON NEXT 5M; ``` * **将表空间名称tbs\_student修改为data\_tbs\_student:** ``` ALTER TABLESPACE tbs_student RENAME TO data_tbs_student; ``` --- --- url: /zh/docs/latest/sql_reference/alter_tablespace.md --- # ALTER TABLESPACE ## 功能描述 修改表空间的属性。 ## 注意事项 * 只有表空间的所有者或者被授予了表空间ALTER权限的用户有权限执行ALTER TABLESPACE命令,系统管理员默认拥有此权限。但要修改表空间的所有者,当前用户必须是该表空间的所有者或系统管理员,且该用户是新所有者角色的成员。 * 要修改表空间的所有者A为B,则A必须是B的直接或者间接成员。 > \[!NOTE]说明 > 如果new\_owner与old\_owner一致,此处不再校验当前执行操作的用户是否具有修改权限,而直接显示ALTER成功。 ## 语法格式 * 重命名表空间的语法。 ``` ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name; ``` * 设置表空间所有者的语法。 ``` ALTER TABLESPACE tablespace_name OWNER TO new_owner; ``` * 设置表空间属性的语法。 ``` ALTER TABLESPACE tablespace_name SET ( {tablespace_option = value} [, ... ] ); ``` * 重置表空间属性的语法。 ``` ALTER TABLESPACE tablespace_name RESET ( { tablespace_option } [, ...] ); ``` * 设置表空间限额的语法。 ``` ALTER TABLESPACE tablespace_name RESIZE MAXSIZE { UNLIMITED | 'space_size'}; ``` ## 参数说明 * **tablespace\_name** 要修改的表空间。 取值范围:已存在的表空间名。 * **new\_tablespace\_name** 表空间的新名称。 新名称不能以“PG\_”开头。 取值范围:字符串,符合标识符命名规范。 * **new\_owner** 表空间的新所有者。 取值范围:已存在的用户名。 * **tablespace\_option** 设置或者重置表空间的参数。 取值范围: * seq\_page\_cost:设置优化器计算一次顺序获取磁盘页面的开销。缺省为1.0。 * random\_page\_cost:设置优化器计算一次非顺序获取磁盘页面的开销。缺省为4.0。 > \[!NOTE]说明 > > * random\_page\_cost是相对于seq\_page\_cost的取值,等于或者小于seq\_page\_cost时毫无意义。 > * 默认值为4.0的前提条件是,优化器采用索引来扫描表数据,并且表数据在cache中命中率可以90%左右。 > * 如果表数据空间要比物理内存小,那么减小该值到一个适当水平;相反地,如果表数据在cache中命中率要低于90%,那么适当增大该值。 > * 如果采用了类似于SSD的随机访问代价较小的存储器,可以适当减小该值,以反映真正的随机扫描代价。 value的取值范围:正的浮点类型。 * **RESIZE MAXSIZE** 重新设置表空间限额的数值。 取值范围: * UNLIMITED,该表空间不设置限额。 * 由space\_size来确定,其格式参考[CREATE TABLESPACE](create_tablespace.md)。 > \[!NOTE]说明 > > * 若调整后的限额值比当前表空间实际使用的值要小,调整操作可以执行成功,后续用户需要将该表空间的使用值降低到新限额值之下,才能继续往该表空间中写入数据。 > * 修改参数MAXSIZE时也可使用: > ```` >``` ```` ```` >ALTER TABLESPACE tablespace_name RESIZE MAXSIZE > { 'UNLIMITED' | 'space_size'}; >``` ```` ## 示例 请参考CREATE TABLESPACE的[示例](create_tablespace.md#zh-cn_topic_0283137328_zh-cn_topic_0237122120_zh-cn_topic_0059777670_s4e5e97caa377440d87fad0d49b56323e)。 ## 相关链接 [CREATE TABLESPACE](create_tablespace.md),[DROP TABLESPACE](drop_tablespace.md) --- --- url: /zh/docs/latest-lite/brief_tutorial/alter_table_statement.md --- # ALTER TABLE语句 修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关。 ## 语法格式 * 在一张已经存在的表上添加列。 ``` ALTER TABLE table_name ADD column_name data_type; ``` * 在一张已经存在的表上删除列。 ``` ALTER TABLE table_name DROP [ COLUMN ] column_name; ``` * 修改表的字段类型。 ``` ALTER TABLE table_name MODIFY column_name data_type; ``` * 为一张已经存在的表的列增加/删除非空约束(NOT NULL)。 ``` ALTER TABLE table_name ALTER column_name { SET | DROP } NOT NULL ``` * 重命名表中指定的列。 ``` ALTER TABLE table_name RENAME column_name TO new_column_name; ``` * 更新多个列。 ``` ALTER TABLE table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ``` * 对名称的修改不会影响所存储的数据。 ``` ALTER TABLE table_name RENAME TO new_table_name; ``` ## 参数说明 * **table\_name** table\_name是需要修改的表名。 若声明了ONLY选项,则只有那个表被更改。若未声明ONLY,该表及其所有子表都将会被更改。另外,可以在表名称后面显示地增加\*选项来指定包括子表,即表示所有后代表都被扫描,这是默认行为。 * **column\_name** 现存的或新字段的名称。 * **data\_type** 新字段的类型,或者现存字段的新类型。 * **new\_table\_name** 修改后新的表名称。 * **new\_column\_name** 表中指定列修改后新的列名称。 * **constraint\_name** 约束的名称。 ## 示例 表customer\_t1的数据如下。 ``` openGauss=# SELECT * FROM customer_t1; c_customer_sk | c_customer_id | c_first_name | c_last_name | amount ---------------+---------------+--------------+-------------+-------- 3869 | hello | Grace | | 1000 3869 | hello | Grace | | 1000 3869 | | Grace | | 3869 | hello | | | 3869 | hello | | | | | | | 6985 | maps | Joes | | 2200 9976 | world | James | | 5000 4421 | Admin | Local | | 3000 6881 | maps | Lily | | 1000 4320 | tpcds | Lily | | 2000 (11 rows) ``` * 新增列 在上面的表中添加新的列。 ``` openGauss=# ALTER TABLE customer_t1 ADD date time; ``` 查询表customer\_t1的结构如下,新增列date成功。 ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(8) | amount | integer | date | time without time zone | ``` * 修改列数据类型 修改列c\_last\_name的数据类型character(8) 为character(12)。 ``` openGauss=# ALTER TABLE customer_t1 MODIFY c_last_name character(12); ``` 查询表customer\_t1结构,列c\_last\_name修改数据类型成功。 ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | date | time without time zone | ``` * 新增列约束 删除列c\_customer\_sk为空的行。 ``` openGauss=# DELETE FROM customer_t1 WHERE c_customer_sk is NULL; ``` 为列c\_customer\_sk增加非空约束。 ``` openGauss=# ALTER TABLE customer_t1 ALTER c_customer_sk SET NOT NULL; ``` 查询表customer\_t1结构,列c\_customer\_sk新增约束成功。 ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | not null c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | date | time without time zone | ``` * 修改列名称 修改列date名称为purchase\_date。 ``` openGauss=# ALTER TABLE customer_t1 RENAME date TO purchase_date; ``` 查询表customer\_t1结构,列date名称修改成功。 ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | not null c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | purchase_date | time without time zone | ``` * 删除列 删除列purchase\_date。 ``` openGauss=# ALTER TABLE customer_t1 DROP purchase_date; ``` 删除后,表customer\_t1的数据如下。 ``` openGauss=# SELECT * FROM customer_t1; c_customer_sk | c_customer_id | c_first_name | c_last_name | amount ---------------+---------------+--------------+-------------+-------- 3869 | hello | Grace | | 1000 3869 | hello | Grace | | 1000 3869 | | Grace | | 3869 | hello | | | 3869 | hello | | | 6985 | maps | Joes | | 2200 9976 | world | James | | 5000 4421 | Admin | Local | | 3000 6881 | maps | Lily | | 1000 4320 | tpcds | Lily | | 2000 (10 rows) ``` --- --- url: /zh/docs/latest/sql_reference/brief_tutorial/alter_table_statement.md --- # ALTER TABLE语句 修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关。 ## 语法格式 * 在一张已经存在的表上添加列。 ``` ALTER TABLE table_name ADD column_name data_type; ``` * 在一张已经存在的表上删除列。 ``` ALTER TABLE table_name DROP [ COLUMN ] column_name; ``` * 修改表的字段类型。 ``` ALTER TABLE table_name MODIFY column_name data_type; ``` * 为一张已经存在表的列增加/删除非空约束(NOT NULL)。 ``` ALTER TABLE table_name ALTER column_name { SET | DROP } NOT NULL; ``` * 重命名表中指定的列。 ``` ALTER TABLE table_name RENAME column_name TO new_column_name; ``` * 更新多个列。 ``` ALTER TABLE table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ``` * 对名称的修改不会影响所存储的数据。 ``` ALTER TABLE table_name RENAME TO new_table_name; ``` ## 参数说明 * **table\_name** table\_name是需要修改的表名。 若声明了ONLY选项,则只有那个表被更改。若未声明ONLY,该表及其所有子表都将会被更改。另外,可以在表名称后面显示地增加\*选项来指定包括子表,即表示所有后代表都被扫描,这是默认行为。 * **column\_name** 现存的或新字段的名称。 * **data\_type** 新字段的类型,或者现存字段的新类型。 * **new\_table\_name** 修改后新的表名称。 * **new\_column\_name** 表中指定列修改后新的列名称。 * **constraint\_name** 约束的名称。 ## 示例 表customer\_t1的数据如下。 ``` openGauss=# SELECT * FROM customer_t1; c_customer_sk | c_customer_id | c_first_name | c_last_name | amount ---------------+---------------+--------------+-------------+-------- 3869 | hello | Grace | | 1000 3869 | hello | Grace | | 1000 3869 | | Grace | | 3869 | hello | | | 3869 | hello | | | | | | | 6985 | maps | Joes | | 2200 9976 | world | James | | 5000 4421 | Admin | Local | | 3000 6881 | maps | Lily | | 1000 4320 | tpcds | Lily | | 2000 (11 rows) ``` * 新增列 在上面的表中添加新的列。 ``` openGauss=# ALTER TABLE customer_t1 ADD date time; ``` 查询表customer\_t1的结构如下,新增列date成功。 ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(8) | amount | integer | date | time without time zone | ``` * 修改列数据类型 修改列`c_last_name`的数据类型character(8) 为character(12)。 ``` openGauss=# ALTER TABLE customer_t1 MODIFY c_last_name character(12); ``` 查询表customer\_t1结构,列c\_last\_name修改数据类型成功。 ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | date | time without time zone | ``` * 新增列约束 删除列c\_customer\_sk为空的行。 ``` openGauss=# DELETE FROM customer_t1 WHERE c_customer_sk is NULL; ``` 为列c\_customer\_sk增加非空约束。 ``` openGauss=# ALTER TABLE customer_t1 ALTER c_customer_sk SET NOT NULL; ``` 查询表customer\_t1结构,列c\_customer\_sk新增约束成功。 ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | not null c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | date | time without time zone | ``` * 修改列名称 修改列date名称为purchase date。 ``` openGauss=# ALTER TABLE customer_t1 RENAME date TO purchase_date; ``` 查询表customer\_t1结构,列date名称修改成功。 ``` openGauss=# \d customer_t1 Table "public.customer_t1" Column | Type | Modifiers ---------------+------------------------+----------- c_customer_sk | integer | not null c_customer_id | character(5) | c_first_name | character(6) | c_last_name | character(12) | amount | integer | purchase_date | time without time zone | ``` * 删除列 删除列purchase\_date。 ``` openGauss=# ALTER TABLE customer_t1 DROP purchase_date; ``` 删除后,表customer\_t1的数据如下。 ``` openGauss=# SELECT * FROM customer_t1; c_customer_sk | c_customer_id | c_first_name | c_last_name | amount ---------------+---------------+--------------+-------------+-------- 3869 | hello | Grace | | 1000 3869 | hello | Grace | | 1000 3869 | | Grace | | 3869 | hello | | | 3869 | hello | | | 6985 | maps | Joes | | 2200 9976 | world | James | | 5000 4421 | Admin | Local | | 3000 6881 | maps | Lily | | 1000 4320 | tpcds | Lily | | 2000 (10 rows) ``` --- --- url: /en/docs/latest-lite/sql_reference/alter_text_search_configuration.md --- # ALTER TEXT SEARCH CONFIGURATION ## Function **ALTER TEXT SEARCH CONFIGURATION** modifies the definition of a text search configuration. You can modify its mappings from token types to dictionaries, change the configuration's name or owner, or modify the parameters. The **ADD MAPPING FOR** form installs a list of dictionaries to be consulted for the specified token types; an error will be generated if there is already a mapping for any of the token types. The **ALTER MAPPING FOR** form removes existing mapping for those token types and then adds specified mappings. **ALTER MAPPING REPLACE ...** **WITH ...** and **ALTER MAPPING FOR...** **REPLACE ...** **WITH ...** options replace **old\_dictionary** with **new\_dictionary**. Note that only when **pg\_ts\_config\_map** has tuples corresponding to **maptokentype** and **old\_dictionary**, the update will succeed. If the update fails, no messages are returned. The **DROP MAPPING FOR** form deletes all dictionaries for the specified token types in the text search configuration. If **IF EXISTS** is not specified and the string type mapping specified by **DROP MAPPING FOR** does not exist in text search configuration, an error will occur in the database. ## Precautions * If a search configuration is referenced (to create indexes), users are not allowed to modify the text search configuration. * To use **ALTER TEXT SEARCH CONFIGURATION**, you must be the owner of the configuration. ## Syntax * Add text search configuration string mapping. ``` ALTER TEXT SEARCH CONFIGURATION name ADD MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ]; ``` * Modify the text search configuration dictionary syntax. ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] REPLACE old_dictionary WITH new_dictionary; ``` * Modify the text search configuration string. ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ]; ``` * Change the text search configuration dictionary. ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING REPLACE old_dictionary WITH new_dictionary; ``` * Remove text search configuration string mapping. ``` ALTER TEXT SEARCH CONFIGURATION name DROP MAPPING [ IF EXISTS ] FOR token_type [, ... ]; ``` * Rename the owner of text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name OWNER TO new_owner; ``` * Rename the text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name RENAME TO new_name; ``` * Rename the namespace of text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name SET SCHEMA new_schema; ``` * Modify the attributes of the text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name SET ( { configuration_option = value } [, ...] ); ``` * Reset the attributes of text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name RESET ( {configuration_option} [, ...] ); ``` ## Parameter Description * **name** Specifies the name (optionally schema-qualified) of an existing text search configuration. * **token\_type** Specifies the name of a token type that is emitted by the configuration's parser. For details, see [Parser](parser.md). * **dictionary\_name** Specifies the name of a text search dictionary. If multiple dictionaries are listed, they are searched in the specified order. * **old\_dictionary** Specifies the name of a text search dictionary to be replaced in the mapping. * **new\_dictionary** Specifies the name of a text search dictionary to be substituted for **old\_dictionary**. * **new\_owner** Specifies the new owner of the text search configuration. * **new\_name** Specifies the new name of the text search configuration. * **new\_schema** Specifies the new schema for the text search configuration. * **configuration\_option** Specifies the text search configuration option. For details, see [CREATE TEXT SEARCH CONFIGURATION](create_text_search_configuration.md). * **value** Specifies the value of text search configuration option. ## Examples ``` -- Create a text search configuration. openGauss=# CREATE TEXT SEARCH CONFIGURATION english_1 (parser=default); CREATE TEXT SEARCH CONFIGURATION -- Add text search configuration string mapping. openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR word WITH simple,english_stem; ALTER TEXT SEARCH CONFIGURATION -- Add text search configuration string mapping. openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR email WITH english_stem, french_stem; ALTER TEXT SEARCH CONFIGURATION -- Query information about the text search configuration. openGauss=# SELECT b.cfgname,a.maptokentype,a.mapseqno,a.mapdict,c.dictname FROM pg_ts_config_map a,pg_ts_config b, pg_ts_dict c WHERE a.mapcfg=b.oid AND a.mapdict=c.oid AND b.cfgname='english_1' ORDER BY 1,2,3,4,5; cfgname | maptokentype | mapseqno | mapdict | dictname -----------+--------------+----------+---------+-------------- english_1 | 2 | 1 | 3765 | simple english_1 | 2 | 2 | 12960 | english_stem english_1 | 4 | 1 | 12960 | english_stem english_1 | 4 | 2 | 12964 | french_stem (4 rows) -- Add text search configuration string mapping. openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ALTER MAPPING REPLACE french_stem with german_stem; ALTER TEXT SEARCH CONFIGURATION -- Query information about the text search configuration. openGauss=# SELECT b.cfgname,a.maptokentype,a.mapseqno,a.mapdict,c.dictname FROM pg_ts_config_map a,pg_ts_config b, pg_ts_dict c WHERE a.mapcfg=b.oid AND a.mapdict=c.oid AND b.cfgname='english_1' ORDER BY 1,2,3,4,5; cfgname | maptokentype | mapseqno | mapdict | dictname -----------+--------------+----------+---------+-------------- english_1 | 2 | 1 | 3765 | simple english_1 | 2 | 2 | 12960 | english_stem english_1 | 4 | 1 | 12960 | english_stem english_1 | 4 | 2 | 12966 | german_stem (4 rows) ``` See [Examples](create_text_search_configuration.md#en-us_topic_0283137399_en-us_topic_0237122121_en-us_topic_0059777835_sc3a4aef5c0c0420eaf5a2e67097004a2) in **CREATE TEXT SEARCH CONFIGURATION**. ## Helpful Links [CREATE TEXT SEARCH CONFIGURATION](create_text_search_configuration.md) and [DROP TEXT SEARCH CONFIGURATION](drop_text_search_configuration.md) --- --- url: /en/docs/latest/sql_reference/alter_text_search_configuration.md --- # ALTER TEXT SEARCH CONFIGURATION ## Function **ALTER TEXT SEARCH CONFIGURATION** modifies the definition of a text search configuration. You can modify its mappings from token types to dictionaries, change the configuration's name or owner, or modify the parameters. The **ADD MAPPING FOR** form installs a list of dictionaries to be consulted for the specified token types; an error will be generated if there is already a mapping for any of the token types. The **ALTER MAPPING FOR** form removes existing mapping for those token types and then adds specified mappings. **ALTER MAPPING REPLACE ...** **WITH ...** and **ALTER MAPPING FOR...** **REPLACE ...** **WITH ...** options replace **old\_dictionary** with **new\_dictionary**. Note that only when **pg\_ts\_config\_map** has tuples corresponding to **maptokentype** and **old\_dictionary**, the update will succeed. If the update fails, no messages are returned. The **DROP MAPPING FOR** form deletes all dictionaries for the specified token types in the text search configuration. If **IF EXISTS** is not specified and the string type mapping specified by **DROP MAPPING FOR** does not exist in text search configuration, an error will occur in the database. ## Precautions * If a search configuration is referenced (to create indexes), users are not allowed to modify the text search configuration. * To use **ALTER TEXT SEARCH CONFIGURATION**, you must be the owner of the configuration. ## Syntax * Add text search configuration string mapping. ``` ALTER TEXT SEARCH CONFIGURATION name ADD MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ]; ``` * Modify the text search configuration dictionary syntax. ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] REPLACE old_dictionary WITH new_dictionary; ``` * Modify the text search configuration string. ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ]; ``` * Change the text search configuration dictionary. ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING REPLACE old_dictionary WITH new_dictionary; ``` * Remove text search configuration string mapping. ``` ALTER TEXT SEARCH CONFIGURATION name DROP MAPPING [ IF EXISTS ] FOR token_type [, ... ]; ``` * Rename the owner of text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name OWNER TO new_owner; ``` * Rename the text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name RENAME TO new_name; ``` * Rename the namespace of text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name SET SCHEMA new_schema; ``` * Modify the attributes of the text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name SET ( { configuration_option = value } [, ...] ); ``` * Reset the attributes of text search configuration. ``` ALTER TEXT SEARCH CONFIGURATION name RESET ( {configuration_option} [, ...] ); ``` ## Parameter Description * **name** Specifies the name (optionally schema-qualified) of an existing text search configuration. * **token\_type** Specifies the name of a token type that is emitted by the configuration's parser. For details, see [Parser](parser.md). * **dictionary\_name** Specifies the name of a text search dictionary. If multiple dictionaries are listed, they are searched in the specified order. * **old\_dictionary** Specifies the name of a text search dictionary to be replaced in the mapping. * **new\_dictionary** Specifies the name of a text search dictionary to be substituted for **old\_dictionary**. * **new\_owner** Specifies the new owner of the text search configuration. * **new\_name** Specifies the new name of the text search configuration. * **new\_schema** Specifies the new schema for the text search configuration. * **configuration\_option** Specifies the text search configuration option. For details, see [CREATE TEXT SEARCH CONFIGURATION](create_text_search_configuration.md). * **value** Specifies the value of text search configuration option. ## Examples ``` -- Create a text search configuration. openGauss=# CREATE TEXT SEARCH CONFIGURATION english_1 (parser=default); CREATE TEXT SEARCH CONFIGURATION -- Add text search configuration string mapping. openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR word WITH simple,english_stem; ALTER TEXT SEARCH CONFIGURATION -- Add text search configuration string mapping. openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR email WITH english_stem, french_stem; ALTER TEXT SEARCH CONFIGURATION -- Query information about the text search configuration. openGauss=# SELECT b.cfgname,a.maptokentype,a.mapseqno,a.mapdict,c.dictname FROM pg_ts_config_map a,pg_ts_config b, pg_ts_dict c WHERE a.mapcfg=b.oid AND a.mapdict=c.oid AND b.cfgname='english_1' ORDER BY 1,2,3,4,5; cfgname | maptokentype | mapseqno | mapdict | dictname -----------+--------------+----------+---------+-------------- english_1 | 2 | 1 | 3765 | simple english_1 | 2 | 2 | 12960 | english_stem english_1 | 4 | 1 | 12960 | english_stem english_1 | 4 | 2 | 12964 | french_stem (4 rows) -- Add text search configuration string mapping. openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ALTER MAPPING REPLACE french_stem with german_stem; ALTER TEXT SEARCH CONFIGURATION -- Query information about the text search configuration. openGauss=# SELECT b.cfgname,a.maptokentype,a.mapseqno,a.mapdict,c.dictname FROM pg_ts_config_map a,pg_ts_config b, pg_ts_dict c WHERE a.mapcfg=b.oid AND a.mapdict=c.oid AND b.cfgname='english_1' ORDER BY 1,2,3,4,5; cfgname | maptokentype | mapseqno | mapdict | dictname -----------+--------------+----------+---------+-------------- english_1 | 2 | 1 | 3765 | simple english_1 | 2 | 2 | 12960 | english_stem english_1 | 4 | 1 | 12960 | english_stem english_1 | 4 | 2 | 12966 | german_stem (4 rows) ``` See [Examples](create_text_search_configuration.md#en-us_topic_0283137399_en-us_topic_0237122121_en-us_topic_0059777835_sc3a4aef5c0c0420eaf5a2e67097004a2) in **CREATE TEXT SEARCH CONFIGURATION**. ## Helpful Links [CREATE TEXT SEARCH CONFIGURATION](create_text_search_configuration.md) and [DROP TEXT SEARCH CONFIGURATION](drop_text_search_configuration.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_text_search_configuration.md --- # ALTER TEXT SEARCH CONFIGURATION ## 功能描述 更改文本搜索配置的定义。用户可以将映射从字串类型调整为字典,或者改变配置的名称或者所有者,或者修改搜索配置的配置参数。 ADD MAPPING FOR选项为文本搜索配置增加字串类型映射;如果ADD MAPPING FOR后面任何一个字串类型的映射已经存在于此文本搜索配置中,那么系统将会报错。 ALTER MAPPING FOR选项会首先清除已有的字串类型映射,然后添加指定的字串类型映射。 ALTER MAPPING REPLACE ... WITH ... 与ALTER MAPPING FOR ... REPLACE ... WITH ...选项会直接使用new\_dictionary替换old\_dictionary。需要注意的是,只有pg\_ts\_config\_map系统表中存在maptokentype与old\_dictionary对应关系的元组时,才能更新成功,否则不会成功,也不会有任何提示信息返回。 DROP MAPPING FOR选项会删除当前文本搜索配置中指定的字串类型映射。 如果没有指定IF EXISTS选项,当DROP MAPPING FOR选项指定的字串类型映射在文本搜索配置中不存在时,数据库会报错。 ## 注意事项 * 当一个搜索配置已经被引用(如被用来创建索引),则不允许用户修改此文本搜索配置。 * 要使用ALTER TEXT SEARCH CONFIGURATION,用户必须是配置的所有者。 ## 语法格式 * 增加文本搜索配置字串类型映射语法 ``` ALTER TEXT SEARCH CONFIGURATION name ADD MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ]; ``` * 修改文本搜索配置字典语法 ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] REPLACE old_dictionary WITH new_dictionary; ``` * 修改文本搜索配置字串类型语法 ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ]; ``` * 更改文本搜索配置字典语法 ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING REPLACE old_dictionary WITH new_dictionary; ``` * 删除文本搜索配置字串类型映射语法 ``` ALTER TEXT SEARCH CONFIGURATION name DROP MAPPING [ IF EXISTS ] FOR token_type [, ... ]; ``` * 重命名文本搜索配置所有者语法 ``` ALTER TEXT SEARCH CONFIGURATION name OWNER TO new_owner; ``` * 重命名文本搜索配置名称语法 ``` ALTER TEXT SEARCH CONFIGURATION name RENAME TO new_name; ``` * 重命名文本搜索配置命名空间语法 ``` ALTER TEXT SEARCH CONFIGURATION name SET SCHEMA new_schema; ``` * 修改文本搜索配置属性语法 ``` ALTER TEXT SEARCH CONFIGURATION name SET ( { configuration_option = value } [, ...] ); ``` * 重置文本搜索配置属性语法 ``` ALTER TEXT SEARCH CONFIGURATION name RESET ( {configuration_option} [, ...] ); ``` ## 参数说明 * **name** 已有文本搜索配置的名称(可以有模式修饰)。 * **token\_type** 与配置的语法解析器关联的字串类型的名称。详细信息参见[解析器](resolver.md)。 * **dictionary\_name** 文本搜索字典名称。 如果有多个字典,则它们会按指定的顺序搜索。 * **old\_dictionary** 映身中拟被替换的文本搜索字典名称。 * **new\_dictionary** 替换old\_dictionary的文本搜索字典的名称。 * **new\_owner** 文本搜索配置的新所有者。 * **new\_name** 文本搜索配置的新名称。 * **new\_schema** 文本搜索配置的新模式名。 * **configuration\_option** 文本搜索配置项。详细信息参见[CREATE TEXT SEARCH CONFIGURATION](create_text_search_configuration.md)。 * **value** 文本搜索配置项的值。 ## 示例 ``` --创建文本搜索配置。 openGauss=# CREATE TEXT SEARCH CONFIGURATION english_1 (parser=default); CREATE TEXT SEARCH CONFIGURATION --增加文本搜索配置字串类型映射语法。 openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR word WITH simple,english_stem; ALTER TEXT SEARCH CONFIGURATION --增加文本搜索配置字串类型映射语法。 openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR email WITH english_stem, french_stem; ALTER TEXT SEARCH CONFIGURATION --查询文本搜索配置相关信息。 openGauss=# SELECT b.cfgname,a.maptokentype,a.mapseqno,a.mapdict,c.dictname FROM pg_ts_config_map a,pg_ts_config b, pg_ts_dict c WHERE a.mapcfg=b.oid AND a.mapdict=c.oid AND b.cfgname='english_1' ORDER BY 1,2,3,4,5; cfgname | maptokentype | mapseqno | mapdict | dictname -----------+--------------+----------+---------+-------------- english_1 | 2 | 1 | 3765 | simple english_1 | 2 | 2 | 12960 | english_stem english_1 | 4 | 1 | 12960 | english_stem english_1 | 4 | 2 | 12964 | french_stem (4 rows) --增加文本搜索配置字串类型映射语法。 openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ALTER MAPPING REPLACE french_stem with german_stem; ALTER TEXT SEARCH CONFIGURATION --查询文本搜索配置相关信息。 openGauss=# SELECT b.cfgname,a.maptokentype,a.mapseqno,a.mapdict,c.dictname FROM pg_ts_config_map a,pg_ts_config b, pg_ts_dict c WHERE a.mapcfg=b.oid AND a.mapdict=c.oid AND b.cfgname='english_1' ORDER BY 1,2,3,4,5; cfgname | maptokentype | mapseqno | mapdict | dictname -----------+--------------+----------+---------+-------------- english_1 | 2 | 1 | 3765 | simple english_1 | 2 | 2 | 12960 | english_stem english_1 | 4 | 1 | 12960 | english_stem english_1 | 4 | 2 | 12966 | german_stem (4 rows) ``` 请参见CREATE TEXT SEARCH CONFIGURATION的[示例](create_text_search_configuration.md#zh-cn_topic_0283137399_zh-cn_topic_0237122121_zh-cn_topic_0059777835_sc3a4aef5c0c0420eaf5a2e67097004a2)。 ## 相关链接 [CREATE TEXT SEARCH CONFIGURATION](create_text_search_configuration.md), [DROP TEXT SEARCH CONFIGURATION](drop_text_search_configuration.md) --- --- url: /zh/docs/latest/sql_reference/alter_text_search_configuration.md --- # ALTER TEXT SEARCH CONFIGURATION ## 功能描述 更改文本搜索配置的定义。用户可以将映射从字串类型调整为字典,或者改变配置的名称或者所有者,或者修改搜索配置的配置参数。 ADD MAPPING FOR选项为文本搜索配置增加字串类型映射;如果ADD MAPPING FOR后面任何一个字串类型的映射已经存在于此文本搜索配置中,那么系统将会报错。 ALTER MAPPING FOR选项会首先清除已有的字串类型映射,然后添加指定的字串类型映射。 ALTER MAPPING REPLACE ... WITH ... 与ALTER MAPPING FOR ... REPLACE ... WITH ...选项会直接使用new\_dictionary替换old\_dictionary。需要注意的是,只有pg\_ts\_config\_map系统表中存在maptokentype与old\_dictionary对应关系的元组时,才能更新成功,否则不会成功,也不会有任何提示信息返回。 DROP MAPPING FOR选项会删除当前文本搜索配置中指定的字串类型映射。 如果没有指定IF EXISTS选项,当DROP MAPPING FOR选项指定的字串类型映射在文本搜索配置中不存在时,数据库会报错。 ## 注意事项 * 当一个搜索配置已经被引用(如被用来创建索引),则不允许用户修改此文本搜索配置。 * 要使用ALTER TEXT SEARCH CONFIGURATION,用户必须是配置的所有者。 ## 语法格式 * 增加文本搜索配置字串类型映射语法 ``` ALTER TEXT SEARCH CONFIGURATION name ADD MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ]; ``` * 修改文本搜索配置字典语法 ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] REPLACE old_dictionary WITH new_dictionary; ``` * 修改文本搜索配置字串类型语法 ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ]; ``` * 更改文本搜索配置字典语法 ``` ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING REPLACE old_dictionary WITH new_dictionary; ``` * 删除文本搜索配置字串类型映射语法 ``` ALTER TEXT SEARCH CONFIGURATION name DROP MAPPING [ IF EXISTS ] FOR token_type [, ... ]; ``` * 重命名文本搜索配置所有者语法 ``` ALTER TEXT SEARCH CONFIGURATION name OWNER TO new_owner; ``` * 重命名文本搜索配置名称语法 ``` ALTER TEXT SEARCH CONFIGURATION name RENAME TO new_name; ``` * 重命名文本搜索配置命名空间语法 ``` ALTER TEXT SEARCH CONFIGURATION name SET SCHEMA new_schema; ``` * 修改文本搜索配置属性语法 ``` ALTER TEXT SEARCH CONFIGURATION name SET ( { configuration_option = value } [, ...] ); ``` * 重置文本搜索配置属性语法 ``` ALTER TEXT SEARCH CONFIGURATION name RESET ( {configuration_option} [, ...] ); ``` ## 参数说明 * **name** 已有文本搜索配置的名称(可以有模式修饰)。 * **token\_type** 与配置的语法解析器关联的字串类型的名称。详细信息参见[解析器](parser.md)。 * **dictionary\_name** 文本搜索字典名称。 如果有多个字典,则它们会按指定的顺序搜索。 * **old\_dictionary** 映身中拟被替换的文本搜索字典名称。 * **new\_dictionary** 替换old\_dictionary的文本搜索字典的名称。 * **new\_owner** 文本搜索配置的新所有者。 * **new\_name** 文本搜索配置的新名称。 * **new\_schema** 文本搜索配置的新模式名。 * **configuration\_option** 文本搜索配置项。详细信息参见[CREATE TEXT SEARCH CONFIGURATION](create_text_search_configuration.md)。 * **value** 文本搜索配置项的值。 ## 示例 ``` --创建文本搜索配置。 openGauss=# CREATE TEXT SEARCH CONFIGURATION english_1 (parser=default); CREATE TEXT SEARCH CONFIGURATION --增加文本搜索配置字串类型映射语法。 openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR word WITH simple,english_stem; ALTER TEXT SEARCH CONFIGURATION --增加文本搜索配置字串类型映射语法。 openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR email WITH english_stem, french_stem; ALTER TEXT SEARCH CONFIGURATION --查询文本搜索配置相关信息。 openGauss=# SELECT b.cfgname,a.maptokentype,a.mapseqno,a.mapdict,c.dictname FROM pg_ts_config_map a,pg_ts_config b, pg_ts_dict c WHERE a.mapcfg=b.oid AND a.mapdict=c.oid AND b.cfgname='english_1' ORDER BY 1,2,3,4,5; cfgname | maptokentype | mapseqno | mapdict | dictname -----------+--------------+----------+---------+-------------- english_1 | 2 | 1 | 3765 | simple english_1 | 2 | 2 | 12960 | english_stem english_1 | 4 | 1 | 12960 | english_stem english_1 | 4 | 2 | 12964 | french_stem (4 rows) --增加文本搜索配置字串类型映射语法。 openGauss=# ALTER TEXT SEARCH CONFIGURATION english_1 ALTER MAPPING REPLACE french_stem with german_stem; ALTER TEXT SEARCH CONFIGURATION --查询文本搜索配置相关信息。 openGauss=# SELECT b.cfgname,a.maptokentype,a.mapseqno,a.mapdict,c.dictname FROM pg_ts_config_map a,pg_ts_config b, pg_ts_dict c WHERE a.mapcfg=b.oid AND a.mapdict=c.oid AND b.cfgname='english_1' ORDER BY 1,2,3,4,5; cfgname | maptokentype | mapseqno | mapdict | dictname -----------+--------------+----------+---------+-------------- english_1 | 2 | 1 | 3765 | simple english_1 | 2 | 2 | 12960 | english_stem english_1 | 4 | 1 | 12960 | english_stem english_1 | 4 | 2 | 12966 | german_stem (4 rows) ``` 请参见CREATE TEXT SEARCH CONFIGURATION的[示例](create_text_search_configuration.md#zh-cn_topic_0283137399_zh-cn_topic_0237122121_zh-cn_topic_0059777835_sc3a4aef5c0c0420eaf5a2e67097004a2)。 ## 相关链接 [CREATE TEXT SEARCH CONFIGURATION](create_text_search_configuration.md), [DROP TEXT SEARCH CONFIGURATION](drop_text_search_configuration.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_text_search_dictionary.md --- # ALTER TEXT SEARCH DICTIONARY ## Function **ALTER TEXT SEARCH DICTIONARY** modifies the definition of a full-text search dictionary, including its parameters, name, owner, and schema. ## Precautions * Predefined dictionaries do not support the **ALTER** operations. * Only the owner of a dictionary or a system administrator can perform the **ALTER** operations. * After a dictionary is created or modified, any modification to the customized dictionary definition file in the **filepath** directory does not affect the dictionary in the database. To use these modifications in the database, run the **ALTER TEXT SEARCH DICTIONARY** statement to update the definition file of the corresponding dictionary. ## Syntax * Modify the dictionary definition. ``` ALTER TEXT SEARCH DICTIONARY name ( option [ = value ] [, ... ] ); ``` * Rename a dictionary. ``` ALTER TEXT SEARCH DICTIONARY name RENAME TO new_name; ``` * Set the schema of the dictionary. ``` ALTER TEXT SEARCH DICTIONARY name SET SCHEMA new_schema; ``` * Change the owner of the dictionary. ``` ALTER TEXT SEARCH DICTIONARY name OWNER TO new_owner; ``` ## Parameter Description * **name** Specifies the name of an existing dictionary. (If you do not specify a schema name, the dictionary in the current schema will be used.) Value range: an existing dictionary name * **option** Specifies the parameter name to be modified. Each type of dictionaries has a template containing their custom parameters. Parameters function in a way irrelevant to their setting sequence. For details about the parameters, see [option](create_text_search_dictionary.md). > \[!NOTE]NOTE > > * The value of **TEMPLATE** in the dictionary cannot be changed. > * To specify a dictionary, specify both the dictionary definition file path (**FILEPATH**) and the file name. > * The name of a dictionary definition file can contain only lowercase letters, digits, and underscores (\_). * **value** Specifies the new value of a parameter. If the equal sign (=) and *value* are omitted, the previous settings of the option are deleted and the default value is used. Value range: valid values defined by **option**. * **new\_name** Specifies the new name of a dictionary. Value range: a string, which complies with the identifier naming convention. A value can contain a maximum of 63 characters. * **new\_owner** Specifies the new owner of a dictionary. Value range: an existing username * **new\_schema** Specifies the new schema of a dictionary. Value range: an existing schema ## Examples ``` -- Modify the definition of stop words in Snowball dictionaries. Retain the values of other parameters. openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( StopWords = newrussian, FilePath = 'file:///home/dicts' ); -- Modify the Language parameter in Snowball dictionaries and delete the definition of stop words. openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict (Language = dutch, StopWords); -- Update the dictionary definition and do not change any other content. openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( dummy ); ``` ## Helpful Links [CREATE TEXT SEARCH DICTIONARY](create_text_search_dictionary.md) and [DROP TEXT SEARCH DICTIONARY](drop_text_search_dictionary.md) --- --- url: /en/docs/latest/sql_reference/alter_text_search_dictionary.md --- # ALTER TEXT SEARCH DICTIONARY ## Function **ALTER TEXT SEARCH DICTIONARY** modifies the definition of a full-text search dictionary, including its parameters, name, owner, and schema. ## Precautions * Predefined dictionaries do not support the **ALTER** operations. * Only the owner of a dictionary or a system administrator can perform the **ALTER** operations. * After a dictionary is created or modified, any modification to the customized dictionary definition file in the **filepath** directory does not affect the dictionary in the database. To use these modifications in the database, run the **ALTER TEXT SEARCH DICTIONARY** statement to update the definition file of the corresponding dictionary. ## Syntax * Modify the dictionary definition. ``` ALTER TEXT SEARCH DICTIONARY name ( option [ = value ] [, ... ] ); ``` * Rename a dictionary. ``` ALTER TEXT SEARCH DICTIONARY name RENAME TO new_name; ``` * Set the schema of the dictionary. ``` ALTER TEXT SEARCH DICTIONARY name SET SCHEMA new_schema; ``` * Change the owner of the dictionary. ``` ALTER TEXT SEARCH DICTIONARY name OWNER TO new_owner; ``` ## Parameter Description * **name** Specifies the name of an existing dictionary. (If you do not specify a schema name, the dictionary in the current schema will be used.) Value range: an existing dictionary name * **option** Specifies the parameter name to be modified. Each type of dictionaries has a template containing their custom parameters. Parameters function in a way irrelevant to their setting sequence. For details about the parameters, see [option](create_text_search_dictionary.md). > \[!NOTE]NOTE > > * The value of **TEMPLATE** in the dictionary cannot be changed. > * To specify a dictionary, specify both the dictionary definition file path (**FILEPATH**) and the file name. > * The name of a dictionary definition file can contain only lowercase letters, digits, and underscores (\_). * **value** Specifies the new value of a parameter. If the equal sign (=) and *value* are omitted, the previous settings of the option are deleted and the default value is used. Value range: valid values defined by **option**. * **new\_name** Specifies the new name of a dictionary. Value range: a string, which complies with the identifier naming convention. A value can contain a maximum of 63 characters. * **new\_owner** Specifies the new owner of a dictionary. Value range: an existing username * **new\_schema** Specifies the new schema of a dictionary. Value range: an existing schema ## Examples ``` -- Modify the definition of stop words in Snowball dictionaries. Retain the values of other parameters. openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( StopWords = newrussian, FilePath = 'file:///home/dicts' ); -- Modify the Language parameter in Snowball dictionaries and delete the definition of stop words. openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict (Language = dutch, StopWords); -- Update the dictionary definition and do not change any other content. openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( dummy ); ``` ## Helpful Links [CREATE TEXT SEARCH DICTIONARY](create_text_search_dictionary.md) and [DROP TEXT SEARCH DICTIONARY](drop_text_search_dictionary.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_text_search_dictionary.md --- # ALTER TEXT SEARCH DICTIONARY ## 功能描述 修改全文检索词典的相关定义,包括参数、名称、所有者、以及模式等。 ## 注意事项 * 预定义词典不支持ALTER操作。 * 只有词典的所有者可以执行ALTER操作,系统管理员默认拥有此权限。 * 创建或修改词典之后,任何对于filepath路径下用户自定义的词典定义文件的修改,将不会影响到数据库中的词典。如果需要在数据库中使用这些修改,需使用ALTER TEXT SEARCH DICTIONARY语句更新对应词典的定义文件。 ## 语法格式 * 修改词典定义。 ``` ALTER TEXT SEARCH DICTIONARY name ( option [ = value ] [, ... ] ); ``` * 重命名词典。 ``` ALTER TEXT SEARCH DICTIONARY name RENAME TO new_name; ``` * 设置词典的所属模式。 ``` ALTER TEXT SEARCH DICTIONARY name SET SCHEMA new_schema; ``` * 修改词典的所属者。 ``` ALTER TEXT SEARCH DICTIONARY name OWNER TO new_owner; ``` ## 参数说明 * **name** 已存在的词典名(可指定模式名,否则默认在当前模式下)。 取值范围:已存在的词典名。 * **option** 要修改的参数名。与template对应,不同的词典类型具有不同的参数列表,且与指定顺序无关。详细参数说明请见[option](create_text_search_dictionary.md##zh-cn_topic_0283137399_zh-cn_topic_0237122121_zh-cn_topic_0059777835_s3935d7de401a4ccd97361e7b2b485805)。 > \[!NOTE]说明 > > * 不支持修改词典的TEMPLATE参数值。 > * 不支持仅修改FILEPATH参数而不修改对应的词典定义文件参数。 > * 词典定义文件的文件名仅支持小写字母、数据、下划线混合。 * **value** 要修改的参数值。如果省略等号(=)和value,则表示删除该option的先前设置,使用默认值。 取值范围:对应option定义。 * **new\_name** 词典的新名称。 取值范围:符合标识符命名规范的字符串,且最大长度不超过63个字符。 * **new\_owner** 词典新的所有者。 取值范围:已存在的用户。 * **new\_schema** 词典的新模式。 取值范围:已存在的模式。 ## 示例 ``` --更改Snowball类型字典的停用词定义,其他参数保持不变。 openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( StopWords = newrussian, FilePath = 'file:///home/dicts' ); --更改Snowball类型字典的Language参数,并删除停用词定义。 openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( Language = dutch, StopWords ); --更新词典定义,不实际更改任何内容。 openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( dummy ); ``` ## 相关链接 [CREATE TEXT SEARCH DICTIONARY](create_text_search_dictionary.md),[DROP TEXT SEARCH DICTIONARY](drop_text_search_dictionary.md) --- --- url: /zh/docs/latest/sql_reference/alter_text_search_dictionary.md --- # ALTER TEXT SEARCH DICTIONARY ## 功能描述 修改全文检索词典的相关定义,包括参数、名称、所有者以及模式等。 ## 注意事项 * 预定义词典不支持ALTER操作。 * 只有词典的所有者可以执行ALTER操作,系统管理员默认拥有此权限。 * 创建或修改词典之后,任何对于filepath路径下用户自定义的词典定义文件的修改,将不会影响到数据库中的词典。如果需要在数据库中使用这些修改,需使用ALTER TEXT SEARCH DICTIONARY语句更新对应词典的定义文件。 ## 语法格式 * 修改词典定义。 ``` ALTER TEXT SEARCH DICTIONARY name ( option [ = value ] [, ... ] ); ``` * 重命名词典。 ``` ALTER TEXT SEARCH DICTIONARY name RENAME TO new_name; ``` * 设置词典的所属模式。 ``` ALTER TEXT SEARCH DICTIONARY name SET SCHEMA new_schema; ``` * 修改词典的所属者。 ``` ALTER TEXT SEARCH DICTIONARY name OWNER TO new_owner; ``` ## 参数说明 * **name** 已存在的词典名(可指定模式名,否则默认在当前模式下)。 取值范围:已存在的词典名。 * **option** 要修改的参数名。与template对应,不同的词典类型具有不同的参数列表,且与指定顺序无关。详细参数说明请见[option](create_text_search_dictionary.md)。 > \[!NOTE]说明 > > * 不支持修改词典的TEMPLATE参数值。 > * 不支持仅修改FILEPATH参数而不修改对应的词典定义文件参数。 > * 词典定义文件的文件名仅支持小写字母、数据、下划线混合。 * **value** 要修改的参数值。如果省略等号(=)和value,则表示删除该option的先前设置,使用默认值。 取值范围:对应option定义。 * **new\_name** 词典的新名称。 取值范围:符合标识符命名规范的字符串,且最大长度不超过63个字符。 * **new\_owner** 词典新的所有者。 取值范围:已存在的用户。 * **new\_schema** 词典的新模式。 取值范围:已存在的模式。 ## 示例 ``` --更改Snowball类型字典的停用词定义,其他参数保持不变。 openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( StopWords = newrussian, FilePath = 'file:///home/dicts' ); --更改Snowball类型字典的Language参数,并删除停用词定义。 openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( Language = dutch, StopWords ); --更新词典定义,不实际更改任何内容。 openGauss=# ALTER TEXT SEARCH DICTIONARY my_dict ( dummy ); ``` ## 相关链接 [CREATE TEXT SEARCH DICTIONARY](create_text_search_dictionary.md),[DROP TEXT SEARCH DICTIONARY](drop_text_search_dictionary.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_trigger.md --- # ALTER TRIGGER ## Function **ALTER TRIGGER** renames a trigger. > \[!NOTE]NOTE > Currently, only the name can be modified. ## Precautions The owner of the table where a trigger resides or a user granted the ALTER ANY SEQUENCE permission can perform the ALTER TRIGGER operation. A system administrator has this permission by default. ## Syntax ``` ALTER TRIGGER trigger_name ON table_name RENAME TO new_name; ``` ## Parameter Description * **trigger\_name** Specifies the name of the trigger to be modified. Value range: an existing trigger * **table\_name** Specifies the name of the table where the trigger to be modified is located. Value range: an existing table having a trigger * **new\_name** Specifies the new name after modification. Value range: a string, which complies with the identifier naming convention. A value contains a maximum of 63 characters and cannot be the same as other triggers on the same table. ## Examples See examples in [CREATE TRIGGER](create_trigger.md). ## Helpful Links [CREATE TRIGGER](create_trigger.md), [DROP TRIGGER](drop_trigger.md), and [ALTER TABLE](alter_table.md) --- --- url: /en/docs/latest/sql_reference/alter_trigger.md --- # ALTER TRIGGER ## Function **ALTER TRIGGER** modifies the name of a trigger. > \[!NOTE]NOTE > > Only the name modification is currently supported. ## Precautions The owner of the table where a trigger resides or a user granted the ALTER ANY SEQUENCE permission can perform the ALTER TRIGGER operation. A system administrator has this permission by default. ## Syntax ``` ALTER TRIGGER trigger_name ON table_name RENAME TO new_name; ``` ## Parameter Description * **trigger\_name** Specifies the name of the trigger to be modified. Value range: an existing trigger * **table\_name** Specifies the name of the table where the trigger to be modified is located. Value range: an existing table having a trigger * **new\_name** Specifies the new name after modification. Value range: a string, which complies with the identifier naming convention. A value contains a maximum of 63 characters and cannot be the same as other triggers on the same table. ## Examples See examples in [CREATE TRIGGER](create_trigger.md). ## Helpful Links [CREATE TRIGGER](create_trigger.md), [DROP TRIGGER](drop_trigger.md), and [ALTER TABLE](alter_table.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_trigger.md --- # ALTER TRIGGER ## 功能描述 修改触发器名称、所有者及单个触发器的启用/禁用。 > \[!NOTE]说明 > > 目前只支持修改名称、所有者及单个触发器的启用/禁用。 ## 注意事项 * 触发器所在表的所有者或者被授予了ALTER ANY TRIGGER权限的用户可以执行ALTER TRIGGER操作,系统管理员默认拥有此权限。 * 若要修改触发器owner,当前用户必须是该触发器的所有者或者系统管理员,且当前用户必须是新owner所属角色的直接或者间接成员。新owner必须有触发器所在模式上的CREATE权限。`enableSeparationOfDuty = off`时,系统管理员默认拥有该权限。`enableSeparationOfDuty = on`时,系统管理员默认没有该权限。 * 只有初始用户才能修改触发器的owner为初始用户。 ## 语法格式 * 修改触发器名称。 ``` ALTER TRIGGER trigger_name ON table_name RENAME TO new_name; ``` * 修改触发器owner ``` ALTER TRIGGER trigger_name ON table_name OWNER TO new_owner; ``` * 启用/禁用单个触发器。 ``` ALTER TRIGGER trigger_name ENABLE|DISABLE; ``` ## 参数说明 * **trigger\_name** 要修改的触发器名称。 取值范围:已存在的触发器。 * **table\_name** 要修改的触发器所在的表名称。 取值范围:已存在的含触发器的表。 * **new\_name** 修改后的新名称。 取值范围:符合标识符命名规范的字符串,最大长度不超过63个字符,且不能与所在表上其他触发器同名。 * **new\_owner** 修改后的触发器新owner名称。 取值范围:数据库中存在的用户。 * **ENABLE|DISABLE** ENABLE: 启用单个触发器。 DISABLE:禁用单个触发器。 ## 示例 请参见[CREATE TRIGGER](create_trigger.md)的示例。 ## 相关链接 [CREATE TRIGGER](create_trigger.md),[DROP TRIGGER](drop_trigger.md),[ALTER TABLE](alter_table.md) --- --- url: /zh/docs/latest/sql_reference/alter_trigger.md --- # ALTER TRIGGER ## 功能描述 修改触发器名称、所有者及单个触发器的启用/禁用。 > \[!NOTE]说明 > > 目前只支持修改名称、所有者及单个触发器的启用/禁用。 ## 注意事项 * 触发器所在表的所有者或者被授予了ALTER ANY TRIGGER权限的用户可以执行ALTER TRIGGER操作,系统管理员默认拥有此权限。 * 若要修改触发器owner,当前用户必须是该触发器的所有者或者系统管理员,且当前用户必须是新owner所属角色的直接或者间接成员。新owner必须有触发器所在模式上的CREATE权限。`enableSeparationOfDuty = off`时,系统管理员默认拥有该权限。`enableSeparationOfDuty = on`时,系统管理员默认没有该权限。 * 只有初始用户才能修改触发器的owner为初始用户。 ## 语法格式 * 修改触发器名称。 ``` ALTER TRIGGER trigger_name ON table_name RENAME TO new_name; ``` * 修改触发器owner ``` ALTER TRIGGER trigger_name ON table_name OWNER TO new_owner; ``` * 启用/禁用单个触发器。 ``` ALTER TRIGGER trigger_name ENABLE|DISABLE; ``` ## 参数说明 * **trigger\_name** 要修改的触发器名称。 取值范围:已存在的触发器。 * **table\_name** 要修改的触发器所在的表名称。 取值范围:已存在的含触发器的表。 * **new\_name** 修改后的新名称。 取值范围:符合标识符命名规范的字符串,最大长度不超过63个字符,且不能与所在表上其他触发器同名。 * **new\_owner** 修改后的触发器新owner名称。 取值范围:数据库中存在的用户。 * **ENABLE|DISABLE** ENABLE: 启用单个触发器。 DISABLE:禁用单个触发器。 ## 示例 请参见[CREATE TRIGGER](create_trigger.md)的示例。 ## 相关链接 [CREATE TRIGGER](create_trigger.md),[DROP TRIGGER](drop_trigger.md),[ALTER TABLE](alter_table.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_type.md --- # ALTER TYPE ## Function **ALTER TYPE** modifies the definition of a type. ## Precautions The owner of a type, a user granted the ALTER permission on a type, or a user granted the ALTER ANY TYPE permission on a type can run the **ALTER TYPE** command. The system administrator has this permission by default. To modify the owner or schema of a type, you must be a type owner or system administrator and a member of the new owner role. ## Syntax * Modify a type. ``` ALTER TYPE name action [, ... ] ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ALTER TYPE name RENAME TO new_name ALTER TYPE name SET SCHEMA new_schema ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value where action is one of: ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * Add a new attribute to a composite type. ``` ALTER TYPE name ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * Delete an attribute from a composite type. ``` ALTER TYPE name DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ``` * Change the type of an attribute in a composite type. ``` ALTER TYPE name ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * Change the owner of a type. ``` ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * Change the name of a type or the name of an attribute in a composite type. ``` ALTER TYPE name RENAME TO new_name ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ``` * Move a type to a new schema. ``` ALTER TYPE name SET SCHEMA new_schema ``` * Add a new value to an enumerated type. ``` ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ``` * Change an enumerated value in the value list. ``` ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value ``` ## Parameter Description * **name** Specifies the name of an existing type that needs to be modified (optionally schema-qualified). * **new\_name** Specifies the new name of the type. * **new\_owner** Specifies the new owner of the type. * **new\_schema** Specifies the new schema of the type. * **attribute\_name** Specifies the name of the attribute to be added, modified, or deleted. * **new\_attribute\_name** Specifies the new name of the attribute to be renamed. * **data\_type** Specifies the data type of the attribute to be added, or the new type of the attribute to be modified. * **new\_enum\_value** Specifies a new enumerated value. It is a non-null string with a maximum length of 63 bytes. * **neighbor\_enum\_value** Specifies an existing enumerated value before or after which a new enumerated value will be added. * **existing\_enum\_value** Specifies an enumerated value to be changed. It is a non-null string with a maximum length of 63 bytes. * **CASCADE** Determines that the type to be modified, its associated records, and subtables that inherit the type will all be updated. * **RESTRICT** Refuses to update the associated records of the modified type. This is the default action. > \[!TIP]NOTICE > > * **ADD ATTRIBUTE**, **DROP ATTRIBUTE**, and **ALTER ATTRIBUTE** can be combined for processing. For example, it is possible to add several attributes or change the types of several attributes at the same time in one command. > * To modify a schema of a type, you must have the **CREATE** permission on the new schema. To change the owner, you must be a direct or indirect member of the new owning role, and the member must have the **CREATE** permission on the schema of this type. (These restrictions enforce that the user can only recreate and delete the type. However, the system administrator can change ownership of any type in any way.) To add an attribute or modify the type of an attribute, you must also have the **USAGE** permission of this type. ## Examples See [Examples](create_type.md#en-us_topic_0283136568_en-us_topic_0237122124_en-us_topic_0059779377_s66a0b4a6a1df4ba4a116c6c565a0fe9d) in **CREATE TYPE**. ## Helpful Links [CREATE TYPE](create_type.md) and [DROP TYPE](drop_type.md) --- --- url: /en/docs/latest/sql_reference/alter_type.md --- # ALTER TYPE ## Function **ALTER TYPE** modifies the definition of a type. ## Precautions The owner of a type, a user granted the ALTER permission on a type, or a user granted the ALTER ANY TYPE permission on a type can run the **ALTER TYPE** command. The system administrator has this permission by default. To modify the owner or schema of a type, you must be a type owner or system administrator and a member of the new owner role. ## Syntax * Modify a type. ``` ALTER TYPE name action [, ... ] ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ALTER TYPE name RENAME TO new_name ALTER TYPE name SET SCHEMA new_schema ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value where action is one of: ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * Add a new attribute to a composite type. ``` ALTER TYPE name ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * Delete an attribute from a composite type. ``` ALTER TYPE name DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ``` * Change the type of an attribute in a composite type. ``` ALTER TYPE name ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * Change the owner of a type. ``` ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * Change the name of a type or the name of an attribute in a composite type. ``` ALTER TYPE name RENAME TO new_name ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ``` * Move a type to a new schema. ``` ALTER TYPE name SET SCHEMA new_schema ``` * Add a new value to an enumerated type. ``` ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ``` * Change an enumerated value in the value list. ``` ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value ``` ## Parameter Description * **name** Specifies the name of an existing type that needs to be modified (optionally schema-qualified). * **new\_name** Specifies the new name of the type. * **new\_owner** Specifies the new owner of the type. * **new\_schema** Specifies the new schema of the type. * **attribute\_name** Specifies the name of the attribute to be added, modified, or deleted. * **new\_attribute\_name** Specifies the new name of the attribute to be renamed. * **data\_type** Specifies the data type of the attribute to be added, or the new type of the attribute to be modified. * **new\_enum\_value** Specifies a new enumerated value. It is a non-null string with a maximum length of 63 bytes. * **neighbor\_enum\_value** Specifies an existing enumerated value before or after which a new enumerated value will be added. * **existing\_enum\_value** Specifies an enumerated value to be changed. It is a non-null string with a maximum length of 63 bytes. * **CASCADE** Determines that the type to be modified, its associated records, and subtables that inherit the type will all be updated. * **RESTRICT** Refuses to update the associated records of the modified type. This is the default action. > \[!TIP]NOTICE > > * **ADD ATTRIBUTE**, **DROP ATTRIBUTE**, and **ALTER ATTRIBUTE** can be combined for processing. For example, it is possible to add several attributes or change the types of several attributes at the same time in one command. > * To modify a schema of a type, you must have the **CREATE** permission on the new schema. To change the owner, you must be a direct or indirect member of the new owning role, and the member must have the **CREATE** permission on the schema of this type. (These restrictions enforce that the user can only recreate and delete the type. However, the system administrator can change ownership of any type in any way.) To add an attribute or modify the type of an attribute, you must also have the **USAGE** permission of this type. ## Example See [Examples](create_type.md#en-us_topic_0283136568_en-us_topic_0237122124_en-us_topic_0059779377_s66a0b4a6a1df4ba4a116c6c565a0fe9d) in **CREATE TYPE**. ## Helpful Links [CREATE TYPE](create_type.md) and [DROP TYPE](drop_type.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_type.md --- # ALTER TYPE ## 功能描述 修改一个类型的定义。 ## 注意事项 类型的所有者或者被授予了类型ALTER权限的用户或者被授予了ALTER ANY TYPE权限的用户可以执行ALTER TYPE命令,系统管理员默认拥有此权限。但要修改类型的所有者或者修改类型的模式,当前用户必须是该类型的所有者或者系统管理员,且该用户是新所有者角色的成员。 ## 语法格式 * 修改类型。 ``` ALTER TYPE name action [, ... ] ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ALTER TYPE name RENAME TO new_name ALTER TYPE name SET SCHEMA new_schema ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value where action is one of: ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * 给复合类型增加新的属性。 ``` ALTER TYPE name ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * 从复合类型删除一个属性。 ``` ALTER TYPE name DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ``` * 改变一种复合类型中某个属性的类型。 ``` ALTER TYPE name ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * 改变类型的所有者。 ``` ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * 改变类型的名称或是一个复合类型中的一个属性的名称。 ``` ALTER TYPE name RENAME TO new_name ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ``` * 将类型移至一个新的模式中。 ``` ALTER TYPE name SET SCHEMA new_schema ``` * 为枚举类型增加一个新值。 ``` ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ``` * 重命名枚举类型的一个标签值。 ``` ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value ``` ## 参数说明 * **name** 一个需要修改的现有的类型的名称(可以有模式修饰) 。 * **new\_name** 该类型的新名称。 * **new\_owner** 新所有者的用户名 。 * **new\_schema** 该类型的新模式 。 * **attribute\_name** 拟增加、更改或删除的属性的名称。 * **new\_attribute\_name** 拟改名的属性的新名称。 * **data\_type** 拟新增属性的数据类型或是拟更改的属性的新类型名。 * **new\_enum\_value** 枚举类型新增加的标签值,是一个非空的长度不超过63个字节的字符串。 * **neighbor\_enum\_value** 一个已有枚举标签值,新值应该被增加在紧接着该枚举值之前或者之后的位置上。 * **existing\_enum\_value** 现有的要重命名的枚举值,是一个非空的长度不超过63个字节的字符串 * **CASCADE** 自动级联更新需更新类型以及相关联的记录和继承它们的子表。 * **RESTRICT** 如果需联动更新类型是已更新类型的关联记录,则拒绝更新。这是缺省选项。 > \[!TIP]须知 > > * ADD ATTRIBUTE、DROP ATTRIBUTE和ALTER ATTRIBUTE选项可以组合成一个列表同时处理。 例如,在一条命令中同时增加几个属性或是更改几个属性的类型是可以实现的。 > * 要修改一个类型的模式,必须在新模式上拥有CREATE权限。 要修改所有者,必须是新的所有角色的直接或间接成员, 并且该成员必须在此类型的模式上有CREATE权限。 (这些限制强制了修改所有者不会做任何通过删除和重建类型不能做的事情。 不过,系统管理员可以以任何方式修改任意类型的所有权。) 要增加一个属性或是修改一个属性的类型,也必须有该类型的USAGE权限。 ## 示例 请参考CREATE TYPE的[示例](create_type.md#zh-cn_topic_0283136568_zh-cn_topic_0237122124_zh-cn_topic_0059779377_s66a0b4a6a1df4ba4a116c6c565a0fe9d)。 ## 相关链接 [CREATE TYPE](create_type.md),[DROP TYPE](drop_type.md) --- --- url: /zh/docs/latest/sql_reference/alter_type.md --- # ALTER TYPE ## 功能描述 修改一个类型的定义。 ## 注意事项 类型的所有者或者被授予了类型ALTER权限的用户或者被授予了ALTER ANY TYPE权限的用户可以执行ALTER TYPE命令,系统管理员默认拥有此权限。但要修改类型的所有者或者修改类型的模式,当前用户必须是该类型的所有者或者系统管理员,且该用户是新所有者角色的成员。 ## 语法格式 * 修改类型。 ``` ALTER TYPE name action [, ... ] ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ALTER TYPE name RENAME TO new_name ALTER TYPE name SET SCHEMA new_schema ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value where action is one of: ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * 给复合类型增加新的属性。 ``` ALTER TYPE name ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * 从复合类型删除一个属性。 ``` ALTER TYPE name DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ``` * 改变一种复合类型中某个属性的类型。 ``` ALTER TYPE name ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` * 改变类型的所有者。 ``` ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ``` * 改变类型的名称或是一个复合类型中的一个属性的名称。 ``` ALTER TYPE name RENAME TO new_name ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ``` * 将类型移至一个新的模式中。 ``` ALTER TYPE name SET SCHEMA new_schema ``` * 为枚举类型增加一个新值。 ``` ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ``` * 重命名枚举类型的一个标签值。 ``` ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value ``` ## 参数说明 * **name** 一个需要修改的现有的类型的名称(可以有模式修饰) 。 * **new\_name** 该类型的新名称。 * **new\_owner** 新所有者的用户名 。 * **new\_schema** 该类型的新模式 。 * **attribute\_name** 拟增加、更改或删除的属性的名称。 * **new\_attribute\_name** 拟改名的属性的新名称。 * **data\_type** 拟新增属性的数据类型或是拟更改的属性的新类型名。 * **new\_enum\_value** 枚举类型新增加的标签值,是一个非空的长度不超过63个字节的字符串。 * **neighbor\_enum\_value** 一个已有枚举标签值,新值应该被增加在紧接着该枚举值之前或者之后的位置上。 * **existing\_enum\_value** 现有的要重命名的枚举值,是一个非空的长度不超过63个字节的字符串 * **CASCADE** 自动级联更新需更新类型以及相关联的记录和继承它们的子表。 * **RESTRICT** 如果需联动更新类型是已更新类型的关联记录,则拒绝更新。这是缺省选项。 > \[!TIP]须知 > > * ADD ATTRIBUTE、DROP ATTRIBUTE和ALTER ATTRIBUTE选项可以组合成一个列表同时处理。 例如,在一条命令中同时增加几个属性或是更改几个属性的类型是可以实现的。 > * 要修改一个类型的模式,必须在新模式上拥有CREATE权限。 要修改所有者,必须是新的所有角色的直接或间接成员, 并且该成员必须在此类型的模式上有CREATE权限。 (这些限制强制了修改所有者不会做任何通过删除和重建类型不能做的事情。 不过,系统管理员可以以任何方式修改任意类型的所有权。) 要增加一个属性或是修改一个属性的类型,也必须有该类型的USAGE权限。 ## 示例 请参考CREATE TYPE的[示例](create_type.md#zh-cn_topic_0283136568_zh-cn_topic_0237122124_zh-cn_topic_0059779377_s66a0b4a6a1df4ba4a116c6c565a0fe9d)。 ## 相关链接 [CREATE TYPE](create_type.md),[DROP TYPE](drop_type.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_user.md --- # ALTER USER ## Function **ALTER USER** modifies the attributes of a database user. ## Precautions Session parameters modified by **ALTER USER** apply to a specified user and take effect in the next session. ## Syntax * Modify user permissions or other information. ``` ALTER USER user_name [ [ WITH ] option [ ... ] ]; ``` The **option** clause is as follows: ``` { CREATEDB | NOCREATEDB } | { CREATEROLE | NOCREATEROLE } | { INHERIT | NOINHERIT } | { AUDITADMIN | NOAUDITADMIN } | { SYSADMIN | NOSYSADMIN } | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | { USEFT | NOUSEFT } | { LOGIN | NOLOGIN } | { REPLICATION | NOREPLICATION } | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' [EXPIRED] | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' | EXPIRED ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | PGUSER ``` * Change the username. ``` ALTER USER user_name RENAME TO new_name; ``` * Lock or unlock. ``` ALTER USER user_name ACCOUNT { LOCK | UNLOCK }; ``` * Change the value of a specified parameter associated with the user. ``` ALTER USER user_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ``` * Reset the value of a specified parameter associated with the user. ``` ALTER USER user_name RESET { configuration_parameter | ALL }; ``` ## Parameter Description * **user\_name** Specifies the current username. Value range: an existing username * **new\_password** Specifies a new password. The new password must: * Differ from the old password. * Contain at least eight characters. This is the default length. * Differ from the username or the username spelled backward. * Contain at least three types of the following four types of characters: uppercase characters (A to Z), lowercase characters (a to z), digits (0 to 9), and special characters, including: ~!@#$%^&\*()-\_=+\\|\[{}];:,<.>/? Value range: a string * **old\_password** Specifies the old password. * **ACCOUNT LOCK | ACCOUNT UNLOCK** * **ACCOUNT LOCK**: locks an account to forbid login to databases. * **ACCOUNT UNLOCK**: unlocks an account to allow login to databases. * **PGUSER** In the current version, the **PGUSER** attribute of a user cannot be modified. For details about other parameters, see "Parameter Description" in [CREATE ROLE](create_role.md) and [ALTER ROLE](alter_role.md). ## Example See [Examples](create_user.md#en-us_topic_0283136891_en-us_topic_0237122125_en-us_topic_0059778166_sfbca773f5bcd4799b3ea668b3eb074fa) in **CREATE USER**. ## Helpful Links [CREATE ROLE](create_role.md), [CREATE USER](create_user.md), and [DROP USER](drop_user.md) --- --- url: /en/docs/latest/sql_reference/alter_user.md --- # ALTER USER ## Function **ALTER USER** modifies the attributes of a database user. ## Precautions Session parameters modified by **ALTER USER** apply to a specified user and take effect in the next session. ## Syntax * Modify user permissions or other information. ``` ALTER USER [IF EXISTS] user_name [ [ WITH ] option [ ... ] ]; ``` The **option** clause is as follows: ``` { CREATEDB | NOCREATEDB } | { CREATEROLE | NOCREATEROLE } | { INHERIT | NOINHERIT } | { AUDITADMIN | NOAUDITADMIN } | { SYSADMIN | NOSYSADMIN } | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | { USEFT | NOUSEFT } | { LOGIN | NOLOGIN } | { REPLICATION | NOREPLICATION } | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' [EXPIRED] | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' | EXPIRED ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | PGUSER ``` * Change the username. ``` ALTER USER user_name RENAME TO new_name; ``` * Lock or unlock. ``` ALTER USER user_name ACCOUNT { LOCK | UNLOCK }; ``` * Change the value of a specified parameter associated with the user. ``` ALTER USER user_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ``` * Reset the value of a specified parameter associated with the user. ``` ALTER USER user_name RESET { configuration_parameter | ALL }; ``` ## Parameter Description * **user\_name** Specifies the current username. Value range: an existing username * **new\_password** Specifies a new password. The new password must: * Differ from the old password. * Contain at least eight characters. This is the default length. * Differ from the username or the username spelled backward. * Contain at least three types of the following four types of characters: uppercase characters (A to Z), lowercase characters (a to z), digits (0 to 9), and special characters, including: ~!@#$%^&\*()-\_=+\\|\[{}];:,<.>/? Value range: a string * **old\_password** Specifies the old password. * **ACCOUNT LOCK | ACCOUNT UNLOCK** * **ACCOUNT LOCK**: locks an account to forbid login to databases. * **ACCOUNT UNLOCK**: unlocks an account to allow login to databases. * **PGUSER** In the current version, the **PGUSER** attribute of a user cannot be modified. For details about other parameters, see "Parameter Description" in [CREATE ROLE](create_role.md) and [ALTER ROLE](alter_role.md). ## Example See [Examples](create_user.md#en-us_topic_0283136891_en-us_topic_0237122125_en-us_topic_0059778166_sfbca773f5bcd4799b3ea668b3eb074fa) in **CREATE USER**. ## Helpful Links [CREATE ROLE](create_role.md), [CREATE USER](create_user.md), and [DROP USER](drop_user.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_user.md --- # ALTER USER ## 功能描述 修改数据库用户的属性。 ## 注意事项 ALTER USER中修改的会话参数只针对指定的用户,且在下一次会话中有效。 ## 语法格式 * 修改用户的权限等信息。 ``` ALTER USER user_name [ [ WITH ] option [ ... ] ]; ``` 其中option子句为。 ``` { CREATEDB | NOCREATEDB } | { CREATEROLE | NOCREATEROLE } | { INHERIT | NOINHERIT } | { AUDITADMIN | NOAUDITADMIN } | { SYSADMIN | NOSYSADMIN } | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | { USEFT | NOUSEFT } | { LOGIN | NOLOGIN } | { REPLICATION | NOREPLICATION } | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' [EXPIRED] | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' | EXPIRED ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | PGUSER ``` * 修改用户名。 ``` ALTER USER user_name RENAME TO new_name; ``` * 锁定或解锁。 ``` ALTER USER user_name ACCOUNT { LOCK | UNLOCK }; ``` * 修改与用户关联的指定会话参数值。 ``` ALTER USER user_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ``` * 重置与用户关联的指定会话参数值。 ``` ALTER USER user_name RESET { configuration_parameter | ALL }; ``` ## 参数说明 * **user\_name** 现有用户名。 取值范围:已存在的用户名。 * **new\_password** 新密码。 密码规则如下: * 不能与当前密码相同。 * 密码默认不少于8个字符。 * 不能与用户名及用户名倒序相同。 * 至少包含大写字母(A-Z),小写字母(a-z),数字(0-9),非字母数字字符(限定为~!@#$%^&\*()-\_=+\\|\[{}];:,<.>/?)四类字符中的三类字符。 取值范围:字符串。 * **old\_password** 旧密码。 * **ACCOUNT LOCK | ACCOUNT UNLOCK** * ACCOUNT LOCK:锁定帐户,禁止登录数据库。 * ACCOUNT UNLOCK:解锁帐户,允许登录数据库。 * **PGUSER** 当前版本不允许修改用户的PGUSER属性。 其他参数请参见[CREATE ROLE](create_role.md)和[ALTER ROLE](alter_role.md)的参数说明。 ## 示例 请参考CREATE USER的[示例](create_user.md#zh-cn_topic_0283136891_zh-cn_topic_0237122125_zh-cn_topic_0059778166_sfbca773f5bcd4799b3ea668b3eb074fa)。 ## 相关链接 [CREATE ROLE](create_role.md),[CREATE USER](create_user.md),[DROP USER](drop_user.md) --- --- url: /zh/docs/latest/ograc/sql_reference/alter_user.md --- # ALTER USER ## 功能描述 `ALTER USER` 用于对**已存在的数据库用户**进行属性调整,包括但不限于: * 登录密码修改 * 用户账户锁定 / 解锁 * Profile 绑定变更 * 默认表空间设置 ## 注意事项 ### 权限要求 * 修改**其他用户**的属性:需要系统权限 `ALTER USER` * 仅修改**自身密码**:不需要该权限 ### 权限生效范围 * **普通用户(具备 `ALTER USER`)** * 可修改非 `DBA` 角色、非 `SYS` 用户的密码 * **具备 `DBA` 角色的用户** * 可修改除 `SYS` 之外的所有用户密码 * **`SYS` 用户** * 不受限制,可修改任意用户 ### 其他约束 * 目标用户不存在时,返回错误:user \ does not exist * 数据库处于**重启回滚阶段**时,不支持执行该语句 * 审计日志中,SQL 语句里的密码字段将以 `*` 进行脱敏记录 ## 语法格式 ```sql ALTER USER user_name { IDENTIFIED BY newPassword [REPLACE oldPassword] | PASSWORD EXPIRE | ACCOUNT { LOCK | UNLOCK } | PROFILE profileName | DEFAULT TABLESPACE tableSpaceName } [ , ... ]; ``` ## 参数说明 ### 用户名 * **userName**: * 必须是数据库中已存在的用户 ### 密码相关参数 * **IDENTIFIED BY**: * 用于为用户设置新密码。 * **newPassword**: > **说明:** 密码需满足以下规则: > > * **长度要求**: 不小于所属 Profile 的 `PASSWORD_MIN_LEN` > 最大不超过 64 个字符 > > * **Profile 同步校验**: 若同时修改 `PASSWORD_MIN_LEN`,以修改后的值为准 > > * **字符规则**: 未使用单引号时,首字符必须为字母、`#` 或 `_` > 不得与用户名或其倒序相同(忽略大小写) > > * **复杂度要求**: 至少满足以下 **3 类**字符: > \- 数字 > \- 小写字母 > \- 大写字母 > \- 空格或特殊字符 > > * **特殊字符处理**: 含空格或 `_`、`#`、`$` 以外的特殊字符时,需使用单引号 > > * **新旧密码差异**: 新密码与旧密码至少有 **2 个字符位不同** > > * **ctsql 特殊说明**: 密码中包含 `$` 时,需使用 `\` 转义 * **REPLACE oldPassword**: * **未指定 `REPLACE`**: 不校验旧密码 * **指定 `REPLACE`**: 必须提供正确的旧密码 * **参数限制**: 当 `REPLACE_PASSWORD_VERIFY=TRUE` 时,普通用户修改密码必须使用 `REPLACE` ### 账户与属性控制 * **PASSWORD EXPIRE**: * 将用户密码设置为过期状态 * 用户下次登录时需修改密码(ctsql 会提示) * **ACCOUNT LOCK**: * 锁定用户账户,禁止登录 * **ACCOUNT UNLOCK**: * 解锁用户账户,恢复登录能力 * **PROFILE profileName**: * 为用户指定一个已存在的 Profile * **DEFAULT TABLESPACE tableSpaceName**: * 设置用户默认表空间 ### 可用特殊字符列表 * **常用符号**: `` ` ~ ! @ # $ % ^ `` * **运算与连接符**: `& * ( ) - _ = +` * **分隔与结构符**: `[ ] { } | : ' "` * **比较与路径符**: `< > . , / ?` *** ## 示例 ### 创建用户并指定初始密码 ``` CREATE USER userName IDENTIFIED BY oldPassword; ``` ### 修改密码并校验旧密码 ``` ALTER USER userName IDENTIFIED BY newPassword REPLACE oldPassword; ``` ### 锁定用户 ``` ALTER USER userName ACCOUNT LOCK; ``` ### 解锁用户 ``` ALTER USER userName ACCOUNT UNLOCK; ``` ### 设置密码过期 ``` ALTER USER userName PASSWORD EXPIRE; ``` --- --- url: /zh/docs/latest/sql_reference/alter_user.md --- # ALTER USER ## 功能描述 修改数据库用户的属性。 ## 注意事项 ALTER USER中修改的会话参数只针对指定的用户,且在下一次会话中有效。 ## 语法格式 * 修改用户的权限等信息。 ``` ALTER USER [IF EXISTS] user_name [ [ WITH ] option [ ... ] ]; ``` 其中option子句为: ``` { CREATEDB | NOCREATEDB } | { CREATEROLE | NOCREATEROLE } | { INHERIT | NOINHERIT } | { AUDITADMIN | NOAUDITADMIN } | { SYSADMIN | NOSYSADMIN } | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | { USEFT | NOUSEFT } | { LOGIN | NOLOGIN } | { REPLICATION | NOREPLICATION } | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' [EXPIRED] | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' | EXPIRED ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | PGUSER ``` * 修改用户名。 ``` ALTER USER user_name RENAME TO new_name; ``` * 锁定或解锁。 ``` ALTER USER user_name ACCOUNT { LOCK | UNLOCK }; ``` * 修改与用户关联的指定会话参数值。 ``` ALTER USER user_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ``` * 重置与用户关联的指定会话参数值。 ``` ALTER USER user_name RESET { configuration_parameter | ALL }; ``` ## 参数说明 * **user\_name** 现有用户名。 取值范围:已存在的用户名。 * **new\_password** 新密码。 密码规则如下: * 不能与当前密码相同。 * 密码默认不少于8个字符。 * 不能与用户名及用户名倒序相同。 * 至少包含大写字母(A-Z)、小写字母(a-z)、数字(0-9)、非字母数字字符(限定为~!@#$%^&\*()-\_=+\\|\[{}];:,<.>/?)四类字符中的三类字符。 取值范围:字符串。 * **old\_password** 旧密码。 * **ACCOUNT LOCK | ACCOUNT UNLOCK** * ACCOUNT LOCK:锁定帐户,禁止登录数据库。 * ACCOUNT UNLOCK:解锁帐户,允许登录数据库。 * **PGUSER** 当前版本不允许修改用户的PGUSER属性。 其他参数请参见[CREATE ROLE](create_role.md)和[ALTER ROLE](alter_role.md)的参数说明。 ## 示例 请参考CREATE USER的[示例](create_user.md#zh-cn_topic_0283136891_zh-cn_topic_0237122125_zh-cn_topic_0059778166_sfbca773f5bcd4799b3ea668b3eb074fa)。 ## 相关链接 [CREATE ROLE](create_role.md),[CREATE USER](create_user.md),[DROP USER](drop_user.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_user_mapping.md --- # ALTER USER MAPPING ## Function **ALTER USER MAPPING** changes the definition of a user mapping. ## Precautions If the **password** option is displayed, ensure that the **usermapping.key.cipher** and **usermapping.key.rand** files exist in the *\\$GAUSSHOME*\*\*/bin\*\* directory of each node in openGauss. If the two files do not exist, use the **gs\_guc** tool to generate them and use the **gs\_ssh** tool to release them to the *$GAUSSHOME*\*\*/bin\*\* directory on each node. ## Syntax ``` ALTER USER MAPPING FOR { user_name | USER | CURRENT_USER | PUBLIC } SERVER server_name OPTIONS ( [ ADD | SET | DROP ] option ['value'] [, ... ] ) ``` In **OPTIONS**, **ADD**, **SET**, and **DROP** are operations to be performed. If these operations are not specified, **ADD** operations will be performed by default. **option** and **value** are the parameters and values of the corresponding operation. ## Parameter Description * **user\_name** Specifies the username of the mapping. CURRENT\_USER and USER match the name of the current user. PUBLIC is used to match all current and future user names in the system. * **server\_name** Specifies name of the server to which the user is mapped. * **OPTIONS** Changes an option for the user mapping. The new option overwrites any previously specified option. **ADD**, **SET**, and **DROP** are operations to be performed. If the operation is not set explicitly, **ADD** is used. The option name must be unique and will be validated with the foreign data wrapper of the server. * Options supported by **oracle\_fdw** are as follows: * **user** Oracle server username. * **password** Password of the Oracle user. * Options supported by **mysql\_fdw** are as follows: * **username** Username of the MySQL server or MariaDB. * **password** User password of the MySQL server or MariaDB. * Options supported by **postgres\_fdw** are as follows: * **user** Username of the remote openGauss database. * **password** User password of the remote openGauss database. ## Helpful Links [CREATE USER MAPPING](create_user_mapping.md) and [DROP USER MAPPING](drop_user_mapping.md) > \[!NOTE]NOTE > In the Lite scenario, openGauss provides this syntax, but the USER MAPPING functions are unavailable. --- --- url: /en/docs/latest/sql_reference/alter_user_mapping.md --- # ALTER USER MAPPING ## Function **ALTER USER MAPPING** changes the definition of a user mapping. ## Precautions If the **password** option is displayed, ensure that the **usermapping.key.cipher** and **usermapping.key.rand** files exist in the *$GAUSSHOME***/bin** directory of each node in openGauss. If the two files do not exist, use the **gs\\\_guc** tool to generate them and use the **gs\\\_ssh** tool to release them to the *$GAUSSHOME***/bin** directory on each node. ## Syntax ``` ALTER USER MAPPING FOR { user_name | USER | CURRENT_USER | PUBLIC } SERVER server_name OPTIONS ( [ ADD | SET | DROP ] option ['value'] [, ... ] ) ``` In **OPTIONS**, **ADD**, **SET**, and **DROP** are operations to be performed. If these operations are not specified, **ADD** operations will be performed by default. **option** and **value** are the parameters and values of the corresponding operation. ## Parameter Description * **user\_name** Specifies user name of the mapping. CURRENT\_USER and USER match the name of the current user. PUBLIC is used to match all current and future user names in the system. * **server\_name** Specifies name of the server to which the user is mapped. * **OPTIONS** Changes an option for the user mapping. The new option overwrites any previously specified option. **ADD**, **SET**, and **DROP** are operations to be performed. If the operation is not set explicitly, **ADD** is used. The option name must be unique and will be validated with the foreign data wrapper of the server. * Options supported by **oracle\_fdw** are as follows: * **user** Oracle server user name. * **password** Password of the Oracle user. * Options supported by **mysql\_fdw** are as follows: * **username** User name of the MySQL server or MariaDB. * **password** User password of the MySQL server or MariaDB. * Options supported by **postgres\_fdw** are as follows: * **user** User name of the remote openGauss database. * **password** User password of the remote openGauss database. ## Helpful Links [CREATE USER MAPPING](create_user_mapping.md) and [DROP USER MAPPING](drop_user_mapping.md) --- --- url: /zh/docs/latest-lite/sql_reference/alter_user_mapping.md --- # ALTER USER MAPPING ## 功能描述 更改一个用户映射的定义。 ## 注意事项 当在OPTIONS中出现password选项时,需要保证openGauss每个节点的\\$GAUSSHOME/bin目录下存在usermapping.key.cipher和usermapping.key.rand文件,如果不存在这两个文件,请使用gs\_guc工具生成并放入每个节点的$GAUSSHOME/bin目录下。 ## 语法格式 ``` ALTER USER MAPPING FOR { user_name | USER | CURRENT_USER | PUBLIC } SERVER server_name OPTIONS ( [ ADD | SET | DROP ] option ['value'] [, ... ] ) ``` 在OPTIONS选项里,ADD、SET和DROP指定要执行的操作,未指定时默认为ADD操作。option和value为对应操作的参数及参数值。 ## 参数说明 * **user\_name** 该映射的用户名。 CURRENT\_USER和USER匹配当前用户的名称。PUBLIC被用来匹配系统中所有当前以及未来的用户名。 * **server\_name** 该用户映射的服务器名。 * **OPTIONS** 为该用户映射更改选项。新选项会覆盖任何之前指定的选项。ADD、 SET和DROP指定要被执行的动作。如果没有显式地指定操作,将假定为ADD。选项名称必须为唯一,该服务器的外部数据包装器也会验证选项。 * oracle\_fdw支持的options包括: * **user** oracle server的用户名。 * **password** oracle用户对应的密码。 * mysql\_fdw支持的options包括: * **username** MySQL Server/MariaDB的用户名。 * **password** MySQL Server/MariaDB用户对应的密码。 * postgres\_fdw支持的options包括: * **user** 远端openGauss数据库用户的用户名。 * **password** 远端openGauss数据库用户对应的密码。 ## 相关链接 [CREATE USER MAPPING](create_user_mapping.md),[DROP USER MAPPING](drop_user_mapping.md) > \[!NOTE]说明 > > 轻量版场景下,openGauss提供此语法,但USER MAPPING功能不可用。 --- --- url: /zh/docs/latest/sql_reference/alter_user_mapping.md --- # ALTER USER MAPPING ## 功能描述 更改一个用户映射的定义。 ## 注意事项 当在OPTIONS中出现password选项时,需要保证openGauss每个节点的$GAUSSHOME/bin目录下存在usermapping.key.cipher和usermapping.key.rand文件,如果不存在这两个文件,请使用gs\\\_guc工具生成并使用gs\\\_ssh工具发布到每个节点的$GAUSSHOME/bin目录下。 ## 语法格式 ``` ALTER USER MAPPING FOR { user_name | USER | CURRENT_USER | PUBLIC } SERVER server_name OPTIONS ( [ ADD | SET | DROP ] option ['value'] [, ... ] ) ``` 在OPTIONS选项里,ADD、SET和DROP指定要执行的操作,未指定时默认为ADD操作。option和value为对应操作的参数及参数值。 ## 参数说明 * **user\_name** 该映射的用户名。 CURRENT\_USER和USER匹配当前用户的名称。PUBLIC被用来匹配系统中所有当前以及未来的用户名。 * **server\_name** 该用户映射的服务器名。 * **OPTIONS** 为该用户映射更改选项。新选项会覆盖任何之前指定的选项。ADD、SET和DROP指定要被执行的动作。如果没有显式地指定操作,将假定为ADD。选项名称必须为唯一,该服务器的外部数据包装器也会验证选项。 * oracle\_fdw支持的options包括: * **user** oracle server的用户名。 * **password** oracle用户对应的密码。 * mysql\_fdw支持的options包括: * **username** MySQL Server/MariaDB的用户名。 * **password** MySQL Server/MariaDB用户对应的密码。 * postgres\_fdw支持的options包括: * **user** 远端openGauss数据库用户的用户名。 * **password** 远端openGauss数据库用户对应的密码。 ## 相关链接 [CREATE USER MAPPING](create_user_mapping.md),[DROP USER MAPPING](drop_user_mapping.md) --- --- url: /en/docs/latest-lite/sql_reference/alter_view.md --- # ALTER VIEW ## Function **ALTER VIEW** modifies all auxiliary attributes of a view. (To modify the query definition of a view, use **CREATE OR REPLACE VIEW**.) ## Precautions Only the view owner or a user granted with the ALTER permission can run the **ALTER VIEW** command. The system administrator has this permission by default. The following is permission constraints depending on attributes to be modified: * To modify the schema of a view, you must be the owner of the view or system administrator and have the CREATE permission on the new schema. * To modify the owner of a view, you must be the owner of the view or system administrator and a member of the new owner role, with the CREATE permission on the schema of the view. ## Syntax * Set the default value of a view column. ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name SET DEFAULT expression; ``` * Remove the default value of a view column. ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name DROP DEFAULT; ``` * Change the owner of a view. ``` ALTER VIEW [ IF EXISTS ] view_name OWNER TO new_owner; ``` * Rename a view. ``` ALTER VIEW [ IF EXISTS ] view_name RENAME TO new_name; ``` * Set the schema of a view. ``` ALTER VIEW [ IF EXISTS ] view_name SET SCHEMA new_schema; ``` * Set the options of a view. ``` ALTER VIEW [ IF EXISTS ] view_name SET ( { view_option_name [ = view_option_value ] } [, ... ] ); ``` * Reset the options of a view. ``` ALTER VIEW [ IF EXISTS ] view_name RESET ( view_option_name [, ... ] ); ``` ## Parameter Description * **IF EXISTS** If this option is used, no error is generated when the view does not exist, and only a message is displayed. * **view\_name** Specifies the view name, which can be schema-qualified. Value range: a string. It must comply with the naming convention. * **column\_name** Specifies an optional list of names to be used for columns of the view. If not given, the column names are deduced from the query. Value range: a string. It must comply with the naming convention. * **SET/DROP DEFAULT** Sets or deletes the default value of a column. This parameter does not take effect. * **new\_owner** Specifies the new owner of a view. * **new\_name** Specifies the new view name. * **new\_schema** Specifies the new schema of the view. * **view\_option\_name \[ = view\_option\_value ]** Specifies an optional parameter for a view. * **security\_barrier** This parameter is used when the view attempts to provide row-level security. Value range: Boolean type, **TRUE**, and **FALSE**. * **check\_option** Specifies the check options of the view. Value range: **LOCAL** or **CASCADED**. ## Examples ``` --Create a view consisting of rows with c_customer_sk less than 150. openGauss=# CREATE VIEW tpcds.customer_details_view_v1 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; --Rename a view. openGauss=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2; --Change the schema of a view. openGauss=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public; --Delete a view. openGauss=# DROP VIEW public.customer_details_view_v2; ``` ## Helpful Links [CREATE VIEW](create_view.md) and [DROP VIEW](drop_view.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-alter-view.md --- # ALTER VIEW ## Function **ALTER VIEW** modifies all auxiliary attributes of a view. (To modify the query definition of a view, use **CREATE OR REPLACE VIEW**.) ## Precautions Only the view owner or a user granted with the ALTER permission can run the **ALTER VIEW** command. The system administrator has this permission by default. The following is permission constraints depending on attributes to be modified: * To modify the schema of a view, you must be the owner of the view or system administrator and have the CREATE permission on the new schema. * To modify the owner of a view, you must be the owner of the view or system administrator and a member of the new owner role, with the CREATE permission on the schema of the view. ## Syntax * Set the default value of a view column. ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name SET DEFAULT expression; ``` * Remove the default value of a view column. ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name DROP DEFAULT; ``` * Change the owner of a view. ``` ALTER VIEW [ IF EXISTS ] view_name OWNER TO new_owner; ``` * Rename a view. ``` ALTER VIEW [ IF EXISTS ] view_name RENAME TO new_name; ``` * Set the schema of a view. ``` ALTER VIEW [ IF EXISTS ] view_name SET SCHEMA new_schema; ``` * Set the options of a view. ``` ALTER VIEW [ IF EXISTS ] view_name SET ( { view_option_name [ = view_option_value ] } [, ... ] ); ``` * Reset the options of a view. ``` ALTER VIEW [ IF EXISTS ] view_name RESET ( view_option_name [, ... ] ); ``` * Set the definition of a view. (This syntax can be used only in B-compatible mode.) ``` ALTER [DEFINER = user] VIEW view_name [ ( column_name [, ...] ) ] [ WITH ( {view_option_name [= view_option_value]} [, ... ] ) ] AS query; ``` ## Parameter Description * **IF EXISTS** If this option is used, no error is generated when the view does not exist, and only a message is displayed. * **view\_name** Specifies the view name, which can be schema-qualified. Value range: a string. It must comply with the naming convention. * **column\_name** Specifies an optional list of names to be used for columns of the view. If not given, the column names are deduced from the query. Value range: a string. It must comply with the naming convention. * **SET/DROP DEFAULT** Sets or deletes the default value of a column. This parameter does not take effect. * **new\_owner** Specifies the new owner of a view. * **new\_name** Specifies the new view name. * **new\_schema** Specifies the new schema of the view. * **view\_option\_name \[ = view\_option\_value ]** Specifies an optional parameter for a view. * **security\_barrier** This parameter is used when the view attempts to provide row-level security. Value range: Boolean type, **TRUE**, and **FALSE**. * **check\_option** Specifies the check options of the view. Value range: **LOCAL** or **CASCADED**. ## Examples ``` --Create a view consisting of rows with c_customer_sk less than 150. openGauss=# CREATE VIEW tpcds.customer_details_view_v1 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; --Rename a view. openGauss=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2; --Change the schema of a view. openGauss=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public; --Delete a view. openGauss=# DROP VIEW public.customer_details_view_v2; ``` ## Helpful Links [CREATE VIEW](https://docs.opengauss.org/en/docs/latest/sql_reference/create_view.html) and [DROP VIEW](https://docs.opengauss.org/en/docs/latest/sql_reference/drop_view.html) --- --- url: /en/docs/latest/sql_reference/alter_view.md --- # ALTER VIEW ## Function **ALTER VIEW** modifies all auxiliary attributes of a view. (To modify the query definition of a view, use **CREATE OR REPLACE VIEW**.) ## Precautions Only the view owner or a user granted with the ALTER permission can run the **ALTER VIEW** command. The system administrator has this permission by default. The following is permission constraints depending on attributes to be modified: * To modify the schema of a view, you must be the owner of the view or system administrator and have the CREATE permission on the new schema. * To modify the owner of a view, you must be the owner of the view or system administrator and a member of the new owner role, with the CREATE permission on the schema of the view. ## Syntax * Set the default value of a view column. ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name SET DEFAULT expression; ``` * Remove the default value of a view column. ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name DROP DEFAULT; ``` * Change the owner of a view. ``` ALTER VIEW [ IF EXISTS ] view_name OWNER TO new_owner; ``` * Rename a view. ``` ALTER VIEW [ IF EXISTS ] view_name RENAME TO new_name; ``` * Set the schema of a view. ``` ALTER VIEW [ IF EXISTS ] view_name SET SCHEMA new_schema; ``` * Set the options of a view. ``` ALTER VIEW [ IF EXISTS ] view_name SET ( { view_option_name [ = view_option_value ] } [, ... ] ); ``` * Reset the options of a view. ``` ALTER VIEW [ IF EXISTS ] view_name RESET ( view_option_name [, ... ] ); ``` * Set the definition of a view. (This syntax can be used only in B-compatible mode.) ``` ALTER [DEFINER = user] VIEW view_name [ ( column_name [, ...] ) ] [ WITH ( {view_option_name [= view_option_value]} [, ... ] ) ] AS query; ``` ## Parameter Description * **IF EXISTS** If this option is used, no error is generated when the view does not exist, and only a message is displayed. * **view\_name** Specifies the view name, which can be schema-qualified. Value range: a string. It must comply with the naming convention rule. * **column\_name** Specifies an optional list of names to be used for columns of the view. If not given, the column names are deduced from the query. Value range: a string. It must comply with the naming convention. * **SET/DROP DEFAULT** Sets or deletes the default value of a column. This parameter does not take effect. * **new\_owner** Specifies the new owner of a view. * **new\_name** Specifies the new view name. * **new\_schema** Specifies the new schema of the view. * **view\_option\_name \[ = view\_option\_value ]** Specifies an optional parameter for a view. Currently, **view\_option\_name** supports only the **security\_barrier** parameter. This parameter is used when the view attempts to provide row-level security. Value range: Boolean type, **TRUE**, and **FALSE**. ## Examples ``` -- Create a view consisting of rows with c_customer_sk less than 150. openGauss=# CREATE VIEW tpcds.customer_details_view_v1 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; -- Rename a view. openGauss=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2; -- Change the schema of a view. openGauss=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public; -- Delete a view. openGauss=# DROP VIEW public.customer_details_view_v2; ``` ## Helpful Links [CREATE VIEW](create_view.md) and [DROP VIEW](drop_view.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-ALTER-VIEW.md --- # ALTER VIEW ## 功能描述 ALTER VIEW更改视图的各种辅助属性。(如果用户是更改视图的查询定义,要使用CREATE OR REPLACE VIEW。) ## 注意事项 只有视图的所有者或者被授予了视图ALTER权限的用户才可以执行ALTER VIEW命令,系统管理员默认拥有该权限。针对所要修改属性的不同,对其还有以下权限约束: * 修改视图的模式,当前用户必须是视图的所有者或者系统管理员,且要有新模式的CREATE权限,且不能与新模式中已存在的synonym产生命名冲突。 * 修改视图的所有者,当前用户必须是视图的所有者或者系统管理员,且该用户必须是新所有者角色的成员,并且此角色必须有视图所在模式的CREATE权限。 * 修改视图的命名,不能与当前模式中已存在的synonym产生命名冲突。 新增可以指定 ALGORITHM 选项语法。 ## 语法格式 * 设置视图列的默认值。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name SET DEFAULT expression; ``` * 取消列视图列的默认值。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name DROP DEFAULT; ``` * 修改视图的所有者。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name OWNER TO new_owner; ``` * 重命名视图。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name RENAME TO new_name; ``` * 设置视图的所属模式。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name SET SCHEMA new_schema; ``` * 设置视图的选项。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name SET ( { view_option_name [ = view_option_value ] } [, ... ] ); ``` * 重置视图的选项。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name RESET ( view_option_name [, ... ] ); ``` * 设置视图的定义(该语法仅支持在B兼容模式下才能使用) ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = user] VIEW view_name [ ( column_name [, ...] ) ] AS query [WITH [CASCADE | LOCAL] CHECK OPTION]; ``` > \[!NOTE]说明\ > ALTER VIEW AS 中的 query 新查询不能改变原查询的列定义,包括顺序、列名、数据类型、类型精度等,只可在列表末尾添加其他的列。 ## 参数说明 * **IF EXISTS** 使用这个选项,如果视图不存在时不会产生错误,仅有会有一个提示信息。 * **ALGORITHM** 指定算法,可选项:UNDEFINED、MERGE、TEMPTABLE。当前只做语法兼容,暂无实际功能。 * **view\_name** 视图名称,可以用模式修饰。 取值范围:字符串,符合标识符命名规范。 * **column\_name** 可选的名称列表,视图的字段名。如果没有给出,字段名取自查询中的字段名。 取值范围:字符串,符合标识符命名规范。 * **SET/DROP DEFAULT** 设置或删除一个列的缺省值,该参数暂无实际意义。 * **new\_owner** 视图新所有者的用户名称。 * **new\_name** 视图的新名称。 * **new\_schema** 视图的新模式。 * **view\_option\_name \[ = view\_option\_value ]** 该子句为视图指定一个可选的参数。 * **security\_barrier** 当VIEW试图提供行级安全时,应使用该参数。 取值范围:Boolean类型,TRUE、FALSE。 * **check\_option** 指定该视图的检查选项。 取值范围:LOCAL、CASCADED。 ## 示例 ``` --创建一个由c_customer_sk小于150的内容组成的视图。 openGauss=# CREATE VIEW tpcds.customer_details_view_v1 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; --修改视图名称。 openGauss=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2; --修改视图所属schema。 openGauss=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public; --删除视图。 openGauss=# DROP VIEW public.customer_details_view_v2; ``` ## 相关链接 [CREATE VIEW](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_view.html),[DROP VIEW](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/drop_view.html) --- --- url: /zh/docs/latest-lite/sql_reference/alter_view.md --- # ALTER VIEW ## 功能描述 ALTER VIEW更改视图的各种辅助属性。(如果用户是更改视图的查询定义,要使用CREATE OR REPLACE VIEW。) ## 注意事项 只有视图的所有者或者被授予了视图ALTER权限的用户才可以执行ALTER VIEW命令,系统管理员默认拥有该权限。针对所要修改属性的不同,对其还有以下权限约束: * 修改视图的模式,当前用户必须是视图的所有者或者系统管理员,且要有新模式的CREATE权限,且不能与新模式中已存在的synonym产生命名冲突。 * 修改视图的所有者,当前用户必须是视图的所有者或者系统管理员,且该用户必须是新所有者角色的成员,并且此角色必须有视图所在模式的CREATE权限。 * 重命名视图,不能与当前模式中已存在的synonym产生命名冲突。 ## 语法格式 * 设置视图列的默认值。 ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name SET DEFAULT expression; ``` * 取消列视图列的默认值。 ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name DROP DEFAULT; ``` * 修改视图的所有者。 ``` ALTER VIEW [ IF EXISTS ] view_name OWNER TO new_owner; ``` * 重命名视图。 ``` ALTER VIEW [ IF EXISTS ] view_name RENAME TO new_name; ``` * 设置视图的所属模式。 ``` ALTER VIEW [ IF EXISTS ] view_name SET SCHEMA new_schema; ``` * 设置视图的选项。 ``` ALTER VIEW [ IF EXISTS ] view_name SET ( { view_option_name [ = view_option_value ] } [, ... ] ); ``` * 重置视图的选项。 ``` ALTER VIEW [ IF EXISTS ] view_name RESET ( view_option_name [, ... ] ); ``` * 设置视图的定义(该语法仅支持在B兼容模式下才能使用) ``` ALTER [DEFINER = user] VIEW view_name [ ( column_name [, ...] ) ] AS query [WITH [CASCADE | LOCAL] CHECK OPTION]; ``` > \[!NOTE]说明\ > ALTER VIEW AS 中的 query 新查询不能改变原查询的列定义,包括顺序、列名、数据类型、类型精度等,只可在列表末尾添加其他的列,且需要保证当前操作的视图对象有效。 ## 参数说明 * **DEFINER = user** 指定user作为视图的属主。该选项仅在B兼容模式下使用。 * **IF EXISTS** 使用这个选项,如果视图不存在时不会产生错误,仅有会有一个提示信息。 * **view\_name** 视图名称,可以用模式修饰。 取值范围:字符串,符合标识符命名规范。 * **column\_name** 可选的名称列表,视图的字段名。如果没有给出,字段名取自查询中的字段名。 取值范围:字符串,符合标识符命名规范。 * **SET/DROP DEFAULT** 设置或删除一个列的缺省值,该参数暂无实际意义。 * **new\_owner** 视图新所有者的用户名称。 * **new\_name** 视图的新名称。 * **new\_schema** 视图的新模式。 * **view\_option\_name \[ = view\_option\_value ]** 该子句为视图指定一个可选的参数。 * **security\_barrier** 当VIEW试图提供行级安全时,应使用该参数。 取值范围:Boolean类型,TRUE、FALSE。 * **check\_option** 指定该视图的检查选项。 取值范围:LOCAL、CASCADED。 ## 示例 ``` --创建一个由c_customer_sk小于150的内容组成的视图。 openGauss=# CREATE VIEW tpcds.customer_details_view_v1 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; --修改视图名称。 openGauss=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2; --修改视图所属schema。 openGauss=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public; --删除视图。 openGauss=# DROP VIEW public.customer_details_view_v2; --修改视图的鉴权规则 openGauss=# ALTER sql security definer VIEW v2 AS select * from sql_security_1144425; --修改视图的定义者 openGauss=# ALTER definer=use_a_1144425 VIEW v2 as select * from sql_security_1144425; ``` ## 相关链接 [CREATE VIEW](create_view.md),[DROP VIEW](drop_view.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-ALTER-VIEW.md --- # ALTER VIEW ## 功能描述 ALTER VIEW更改视图的各种辅助属性。(如果用户是更改视图的查询定义,要使用CREATE OR REPLACE VIEW。) ## 注意事项 只有视图的所有者或者被授予了视图ALTER权限的用户才可以执行ALTER VIEW命令,系统管理员默认拥有该权限。针对所要修改属性的不同,对其还有以下权限约束: * 修改视图的模式,当前用户必须是视图的所有者或者系统管理员,且要有新模式的CREATE权限,且不能与新模式中已存在的synonym产生命名冲突。 * 修改视图的所有者,当前用户必须是视图的所有者或者系统管理员,且该用户必须是新所有者角色的成员,并且此角色必须有视图所在模式的CREATE权限。 * 修改视图的命名,不能与当前模式中已存在的synonym产生命名冲突。 新增可以指定 ALGORITHM 选项语法。 ## 语法格式 * 设置视图列的默认值。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name SET DEFAULT expression; ``` * 取消列视图列的默认值。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name DROP DEFAULT; ``` * 修改视图的所有者。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name OWNER TO new_owner; ``` * 重命名视图。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name RENAME TO new_name; ``` * 设置视图的所属模式。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name SET SCHEMA new_schema; ``` * 设置视图的选项。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name SET ( { view_option_name [ = view_option_value ] } [, ... ] ); ``` * 重置视图的选项。 ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW [ IF EXISTS ] view_name RESET ( view_option_name [, ... ] ); ``` * 设置视图的定义(该语法仅支持在B兼容模式下才能使用) ``` ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = user] VIEW view_name [ ( column_name [, ...] ) ] AS query [WITH [CASCADE | LOCAL] CHECK OPTION]; ``` > \[!NOTE]说明\ > ALTER VIEW AS 中的 query 新查询不能改变原查询的列定义,包括顺序、列名、数据类型、类型精度等,只可在列表末尾添加其他的列。 ## 参数说明 * **IF EXISTS** 使用这个选项,如果视图不存在时不会产生错误,仅有会有一个提示信息。 * **ALGORITHM** 指定算法,可选项:UNDEFINED、MERGE、TEMPTABLE。当前只做语法兼容,暂无实际功能。 * **view\_name** 视图名称,可以用模式修饰。 取值范围:字符串,符合标识符命名规范。 * **column\_name** 可选的名称列表,视图的字段名。如果没有给出,字段名取自查询中的字段名。 取值范围:字符串,符合标识符命名规范。 * **SET/DROP DEFAULT** 设置或删除一个列的缺省值,该参数暂无实际意义。 * **new\_owner** 视图新所有者的用户名称。 * **new\_name** 视图的新名称。 * **new\_schema** 视图的新模式。 * **view\_option\_name \[ = view\_option\_value ]** 该子句为视图指定一个可选的参数。 * **security\_barrier** 当VIEW试图提供行级安全时,应使用该参数。 取值范围:Boolean类型,TRUE、FALSE。 * **check\_option** 指定该视图的检查选项。 取值范围:LOCAL、CASCADED。 ## 示例 ``` --创建一个由c_customer_sk小于150的内容组成的视图。 openGauss=# CREATE VIEW tpcds.customer_details_view_v1 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; --修改视图名称。 openGauss=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2; --修改视图所属schema。 openGauss=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public; --删除视图。 openGauss=# DROP VIEW public.customer_details_view_v2; ``` ## 相关链接 [CREATE VIEW](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_view.html),[DROP VIEW](https://docs.opengauss.org/zh/docs/latest/sql_reference/drop_view.html) --- --- url: /zh/docs/latest/sql_reference/alter_view.md --- # ALTER VIEW ## 功能描述 ALTER VIEW更改视图的各种辅助属性。(如果用户是更改视图的查询定义,要使用CREATE OR REPLACE VIEW。) ## 注意事项 只有视图的所有者或者被授予了视图ALTER权限的用户才可以执行ALTER VIEW命令,系统管理员默认拥有该权限。针对所要修改属性的不同,对其还有以下权限约束: * 修改视图的模式,当前用户必须是视图的所有者或者系统管理员,且要有新模式的CREATE权限,且不能与新模式中已存在的synonym产生命名冲突。 * 修改视图的所有者,当前用户必须是视图的所有者或者系统管理员,且该用户必须是新所有者角色的成员,并且此角色必须有视图所在模式的CREATE权限。 * 修改视图的命名,不能与当前模式中已存在的synonym产生命名冲突。 ## 语法格式 * 设置视图列的默认值。 ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name SET DEFAULT expression; ``` * 取消列视图列的默认值。 ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name DROP DEFAULT; ``` * 修改视图的所有者。 ``` ALTER VIEW [ IF EXISTS ] view_name OWNER TO new_owner; ``` * 重命名视图。 ``` ALTER VIEW [ IF EXISTS ] view_name RENAME TO new_name; ``` * 设置视图的所属模式。 ``` ALTER VIEW [ IF EXISTS ] view_name SET SCHEMA new_schema; ``` * 设置视图的选项。 ``` ALTER VIEW [ IF EXISTS ] view_name SET ( { view_option_name [ = view_option_value ] } [, ... ] ); ``` * 重置视图的选项。 ``` ALTER VIEW [ IF EXISTS ] view_name RESET ( view_option_name [, ... ] ); ``` * 设置视图的定义(该语法仅支持在B兼容模式下才能使用) ``` ALTER [DEFINER = user] [ security_option ] VIEW view_name [ ( column_name [, ...] ) ] AS query [WITH [CASCADE | LOCAL] CHECK OPTION]; ``` > \[!NOTE]说明\ > ALTER VIEW AS 中的 query 新查询不能改变原查询的列定义,包括顺序、列名、数据类型、类型精度等,只可在列表末尾添加其他的列,且需要保证当前操作的视图对象有效。 ## 参数说明 * **DEFINER = user** 指定user作为视图的属主。该选项仅在B兼容模式下使用。 * **IF EXISTS** 使用这个选项,如果视图不存在时不会产生错误,仅有会有一个提示信息。 * **view\_name** 视图名称,可以用模式修饰。 取值范围:字符串,符合标识符命名规范。 * **column\_name** 可选的名称列表,视图的字段名。如果没有给出,字段名取自查询中的字段名。 取值范围:字符串,符合标识符命名规范。 * **SET/DROP DEFAULT** 设置或删除一个列的缺省值,该参数暂无实际意义。 * **new\_owner** 视图新所有者的用户名称。 * **new\_name** 视图的新名称。 * **new\_schema** 视图的新模式。 * **security\_option** 指定视图的鉴权规则。 取值范围: SQL SECURITY { DEFINER | INVOKER } * **view\_option\_name \[ = view\_option\_value ]** 该子句为视图指定一个可选的参数。 * **security\_barrier** 当VIEW试图提供行级安全时,应使用该参数。 取值范围:Boolean类型,TRUE、FALSE。 * **check\_option** 指定该视图的检查选项。 取值范围:LOCAL、CASCADED。 ## 示例 ``` --创建一个由c_customer_sk小于150的内容组成的视图。 openGauss=# CREATE VIEW tpcds.customer_details_view_v1 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; --修改视图名称。 openGauss=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2; --修改视图所属schema。 openGauss=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public; --删除视图。 openGauss=# DROP VIEW public.customer_details_view_v2; --修改视图的鉴权规则 openGauss=# ALTER sql security definer VIEW v2 AS select * from sql_security_1144425; --修改视图的定义者 openGauss=# ALTER definer=use_a_1144425 VIEW v2 as select * from sql_security_1144425; ``` ## 相关链接 [CREATE VIEW](create_view.md),[DROP VIEW](drop_view.md) --- --- url: >- /en/docs/latest-lite/database_om_guide/an_error_is_reported_when_the_table_partition_is_modified.md --- # An Error Is Reported When the Table Partition Is Modified ## Symptom When **ALTER TABLE PARTITION** is performed, the following error message is displayed: ``` ERROR:start value of partition "XX" NOT EQUAL up-boundary of last partition. ``` ## Cause Analysis If the **ALTER TABLE PARTITION** statement involves both the DROP PARTITION operation and the ADD PARTITION operation, openGauss always performs the DROP PARTITION operation before the ADD PARTITION operation regardless of their orders. However, performing DROP PARTITION before ADD PARTITION causes a partition gap. As a result, an error is reported. ## Procedure To prevent partition gaps, set **END** in DROP PARTITION to the value of **START** in ADD PARTITION. The following is an example: ``` -- Create a partitioned table partitiontest. openGauss=# CREATE TABLE partitiontest ( c_int integer, c_time TIMESTAMP WITHOUT TIME ZONE ) PARTITION BY range (c_int) ( partition p1 start(100)end(108), partition p2 start(108)end(120) ); -- An error is reported when the following statements are used: openGauss=# ALTER TABLE partitiontest ADD PARTITION p3 start(120)end(130), DROP PARTITION p2; ERROR: start value of partition "p3" NOT EQUAL up-boundary of last partition. openGauss=# ALTER TABLE partitiontest DROP PARTITION p2,ADD PARTITION p3 start(120)end(130); ERROR: start value of partition "p3" NOT EQUAL up-boundary of last partition. -- Change them as follows: openGauss=# ALTER TABLE partitiontest ADD PARTITION p3 start(108)end(130), DROP PARTITION p2; openGauss=# ALTER TABLE partitiontest DROP PARTITION p2,ADD PARTITION p3 start(108)end(130); ``` --- --- url: >- /en/docs/latest/resource_pooling/an_error_is_reported_when_the_table_partition_is_modified.md --- # An Error Is Reported When the Table Partition Is Modified ## Symptom When **ALTER TABLE PARTITION** is performed, the following error message is displayed: ``` ERROR:start value of partition "XX" NOT EQUAL up-boundary of last partition. ``` ## Cause Analysis If the **ALTER TABLE PARTITION** statement involves both the DROP PARTITION operation and the ADD PARTITION operation, openGauss always performs the DROP PARTITION operation before the ADD PARTITION operation regardless of their orders. However, performing DROP PARTITION before ADD PARTITION causes a partition gap. As a result, an error is reported. ## Procedure To prevent partition gaps, set **END** in DROP PARTITION to the value of **START** in ADD PARTITION. The following is an example: ``` -- Create a partitioned table partitiontest. postgres=# CREATE TABLE partitiontest ( c_int integer, c_time TIMESTAMP WITHOUT TIME ZONE ) PARTITION BY range (c_int) ( partition p1 start(100)end(108), partition p2 start(108)end(120) ); -- An error is reported when the following statements are used: postgres=# ALTER TABLE partitiontest ADD PARTITION p3 start(120)end(130), DROP PARTITION p2; ERROR: start value of partition "p3" NOT EQUAL up-boundary of last partition. postgres=# ALTER TABLE partitiontest DROP PARTITION p2,ADD PARTITION p3 start(120)end(130); ERROR: start value of partition "p3" NOT EQUAL up-boundary of last partition. -- Change them as follows: postgres=# ALTER TABLE partitiontest ADD PARTITION p3 start(108)end(130), DROP PARTITION p2; postgres=# ALTER TABLE partitiontest DROP PARTITION p2,ADD PARTITION p3 start(108)end(130); ``` --- --- url: >- /en/docs/latest-lite/database_om_guide/an_error_occurs_during_integer_conversion.md --- # An Error Occurs During Integer Conversion ## Symptom The following error is reported during integer conversion: ``` Invalid input syntax for integer: "13." ``` ## Cause Analysis Some data types cannot be converted to the target data type. ## Procedure Gradually narrow down the range of SQL statements to determine the data types that cannot be converted. --- --- url: /en/docs/latest/resource_pooling/an_error_occurs_during_integer_conversion.md --- # An Error Occurs During Integer Conversion ## Symptom The following error is reported during integer conversion: ``` Invalid input syntax for integer: "13." ``` ## Cause Analysis Some data types cannot be converted to the target data type. ## Procedure Gradually narrow down the range of SQL statements to determine the data types that cannot be converted. --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-ANALYZE.md --- # ANALYZE ## 功能描述 用于收集与数据库中普通表内容相关的统计信息,统计结果存储在系统表PG\_STATISTIC下。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。 如果没有指定参数,ANALYZE会分析当前数据库中的每个表和分区表。同时也可以通过指定table\_name、column和partition\_name参数把分析限定在特定的表、列或分区表中。 ANALYZE VERIFY用于检测数据库中普通表(行存表、列存表)的数据文件是否损坏。 ## 注意事项 \[!NOTE]说明 注意事项可见[ANALYZE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/analyze_analyse.html)。 ## 语法格式 * 收集表的统计信息 ``` { ANALYZE } [ (VERBOSE) ] [ NO_WRITE_TO_BINLOG | LOCAL ] TABLE { [schema.]table_name } [, ... ] ``` ## 参数说明 * **NO\_WRITE\_TO\_BINLOG | LOCAL** 仅作语法,无实际用途 \[!NOTE]说明 涉及的参数可见[ANALYZE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/analyze_analyse.html)。 ## 示例 \--- 创建表。 ``` openGauss=# CREATE TABLE customer_info ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) ; ``` \--- 创建分区表。 ``` openGauss=# CREATE TABLE customer_par ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2452275), PARTITION P2 VALUES LESS THAN(2452640), PARTITION P3 VALUES LESS THAN(2453000), PARTITION P4 VALUES LESS THAN(MAXVALUE) ) ENABLE ROW MOVEMENT; ``` \--- 使用ANALYZE语句更新统计信息。 ``` openGauss=# ANALYZE TABLE customer_info, customer_par; Table | Op | Msg_type | Msg_text ----------------------+---------+----------+---------- public.customer_info | analyze | status | OK public.customer_par | analyze | status | OK (2 row) ``` \--- 删除表。 ``` openGauss=# DROP TABLE customer_info; openGauss=# DROP TABLE customer_par; ``` ## 相关链接 [ANALYZE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/analyze_analyse.html) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-ANALYZE.md --- # ANALYZE ## 功能描述 用于收集与数据库中普通表内容相关的统计信息,统计结果存储在系统表PG\_STATISTIC下。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。 如果没有指定参数,ANALYZE会分析当前数据库中的每个表和分区表。同时也可以通过指定table\_name、column和partition\_name参数把分析限定在特定的表、列或分区表中。 ANALYZE VERIFY用于检测数据库中普通表(行存表、列存表)的数据文件是否损坏。 ## 注意事项 \[!NOTE]说明 注意事项可见[ANALYZE](https://docs.opengauss.org/zh/docs/latest/sql_reference/analyze_analyse.html)。 ## 语法格式 * 收集表的统计信息 ``` { ANALYZE } [ (VERBOSE) ] [ NO_WRITE_TO_BINLOG | LOCAL ] TABLE { [schema.]table_name } [, ... ] ``` ## 参数说明 * **NO\_WRITE\_TO\_BINLOG | LOCAL** 仅作语法,无实际用途 \[!NOTE]说明 涉及的参数可见[ANALYZE](https://docs.opengauss.org/zh/docs/latest/sql_reference/analyze_analyse.html)。 ## 示例 \--- 创建表。 ``` openGauss=# CREATE TABLE customer_info ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) ; ``` \--- 创建分区表。 ``` openGauss=# CREATE TABLE customer_par ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2452275), PARTITION P2 VALUES LESS THAN(2452640), PARTITION P3 VALUES LESS THAN(2453000), PARTITION P4 VALUES LESS THAN(MAXVALUE) ) ENABLE ROW MOVEMENT; ``` \--- 使用ANALYZE语句更新统计信息。 ``` openGauss=# ANALYZE TABLE customer_info, customer_par; Table | Op | Msg_type | Msg_text ----------------------+---------+----------+---------- public.customer_info | analyze | status | OK public.customer_par | analyze | status | OK (2 row) ``` \--- 删除表。 ``` openGauss=# DROP TABLE customer_info; openGauss=# DROP TABLE customer_par; ``` ## 相关链接 [ANALYZE](https://docs.opengauss.org/zh/docs/latest/sql_reference/analyze_analyse.html) --- --- url: /zh/docs/latest/ograc/sql_reference/analyze.md --- # ANALYZE ## 功能描述 用于收集数据库中有关表和索引的对象属性的统计信息。 ## 注意事项 * 只允许在database为open模式的状态下执行 * SYS用户和DBA具有收集、删除所有用户或对象的统计信息的权限 * 普通用户具有收集自己的表的统计信息的权限,具备ANALYZE ANY权限可以操作除SYS外所有用户的统计信息(包括收集、删除等) ## 语法格式 收集表统计信息: ```sql ANALYZE { TABLE [ schema_name. ]table_name COMPUTE STATISTICS } [ FOR REPORT [ SAMPLE sample_percent ]] ``` 收集索引统计信息: ``` ANALYZE { INDEX [ schema_name. ]index_name { COMPUTE STATISTICS | ESTIMATE STATISTICS sample_percent }} ``` ## 参数说明 * **\[ schema\_name. ]table\_name**: 要获取其统计信息的表名,不能和用户下的表重名。 * **COMPUTE STATISTICS**: 收集统计信息,固定语法 * **ESTIMATE STATISTICS sample\_percent**: 使用采样的方式收集,其中sample\_percent为采样率,取值范围是`[0, 100]`的整数 * **FOR REPORT**: 生成统计信息正确性检测报告,用于比较在某个采样率下的统计信息与系统中已收集的统计信息的偏差率。生成的检测报告会保存在LOG\_HOME的opt目录下,其中LOG\_HOME是安装时的日志目录 * **SAMPLE sample\_percent**: 使用采样率采样统计生成检测报告,sample\_percent为采样率,取值范围是`[0, 100]`的整数,默认为100 ## 示例 * **分析收集tester用户下表名为student的相关统计信息** ``` -- 删除表tester.student DROP TABLE IF EXISTS tester.student; -- 创建表tester.student CREATE TABLE tester.student (student_id INT, student_name CHAR(100) NOT NULL, class_name VARCHAR(64), birthday_date DATETIME, other_info VARCHAR(100)); -- 分析收集tester.student的表统计信息 ANALYZE TABLE tester.student COMPUTE STATISTICS; ANALYZE TABLE tester.student COMPUTE STATISTICS FOR REPORT; ANALYZE TABLE tester.student COMPUTE STATISTICS FOR REPORT SAMPLE 10; -- 创建索引 CREATE INDEX tester.idx on tester.student (student_id); -- 分析收集tester.idx的索引统计信息 ANALYZE INDEX tester.idx COMPUTE STATISTICS; ANALYZE INDEX tester.idx ESTIMATE STATISTICS 10; ``` --- --- url: /en/docs/latest-lite/sql_reference/analyze_analyse.md --- # ANALYZE | ANALYSE ## Function **ANALYZE** collects statistics about ordinary tables in a database, and stores the results in the **PG\_STATISTIC** system catalog. The execution plan generator uses these statistics to determine which one is the most effective execution plan. If no parameter is specified, **ANALYZE** analyzes each table and partitioned table in the current database. You can also specify the **table\_name**, **column**, and **partition\_name** parameters to restrict the analysis to a specific table, column, or partitioned table. **ANALYZE | ANALYSE VERIFY** is used to check whether data files of common tables (row-store and column-store tables) in a database are damaged. ## Precautions * Non-temporary tables cannot be analyzed in an anonymous block, transaction block, function, or stored procedure. Temporary tables in a stored procedure can be analyzed but their statistics updates cannot be rolled back. * The **ANALYZE VERIFY** operation is used to detect abnormal scenarios. The **RELEASE** version is required. In the **ANALYZE VERIFY** scenario, remote read is not triggered. Therefore, the remote read parameter does not take effect. If the system detects that a page is damaged due to an error in a key system table, the system directly reports an error and does not continue the detection. * With no table specified, **ANALYZE** processes all the tables that the current user has permission to analyze in the current database. With tables specified, **ANALYZE** processes only the specified tables. * To perform ANALYZE operation to a table, you must be a table owner or a user granted the VACUUM permission on the table. By default, the system administrator has this permission. However, database owners are allowed to **ANALYZE** all tables in their databases, except shared catalogs. (The restriction for shared catalogs means that a true database-wide **ANALYZE** can only be executed by the system administrator). **ANALYZE** skips tables on which users do not have permissions. ## Syntax * Collect statistics information about a table. ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ]; ``` * Collect statistics about a partitioned table. ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ] PARTITION ( partition_name ) ; ``` > \[!NOTE]NOTE > An ordinary partitioned table supports the syntax but not the function of collecting statistics about specified partitions. * Collect statistics about multiple columns. ``` {ANALYZE | ANALYSE} [ VERBOSE ] table_name (( column_1_name, column_2_name [, ...] )); ``` > \[!NOTE]NOTE > > * When collecting statistics about multiple columns, set the GUC parameter [default\_statistics\_target](../database_reference/other_optimizer_options.md#en-us_topic_0283137690_en-us_topic_0237124719_en-us_topic_0059779049_se18c86fcdf5e4a22870f71187436d815) to a negative value to sample data in percentage. > * If the GUC parameter **enable\_functional\_dependency** is disabled, the statistics about a maximum of 32 columns can be collected at a time. If the GUC parameter **enable\_functional\_dependency** is enabled, the statistics about a maximum of 4 columns can be collected at a time. > * You are not allowed to collect statistics about multiple columns in system catalogs. * Check the data files in the current database. ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE}; ``` > \[!NOTE]NOTE > > * In fast mode, DML operations need to be performed on the tables to be verified concurrently. As a result, an error is reported during the verification. In the current fast mode, data is directly read from the disk. When other threads modify files concurrently, the obtained data is incorrect. Therefore, you are advised to perform the verification offline. > * You can perform operations on the entire database. Because a large number of tables are involved, you are advised to save the result **gsql -d database -p port -f "verify.sql"> verify\_warning.txt 2>&1** in redirection mode. > * NOTICE is used to check only tables that are visible to external systems. The detection of internal tables is included in the external tables on which NOTICE depends and is not displayed externally. > * This statement can be executed with error tolerance. The **Assert** of the debug version may cause the core to fail to execute commands. Therefore, you are advised to perform the operations in release mode. > * If a key system table is damaged during a full database operation, an error is reported and the operation stops. * Check data files of tables and indexes. ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name|index_name [CASCADE]; ``` > \[!NOTE]NOTE > > * Operations on ordinary tables and index tables are supported, but **CASCADE** operations on indexes of index tables are not supported. The **CASCADE** mode is used to process all index tables of the primary table. When the index tables are checked separately, the **CASCADE** mode is not required. > * When the primary table is checked, the internal tables of the primary table, such as the toast table and cudesc table, are also checked. > * When the system displays a message indicating that the index table is damaged, you are advised to run the **reindex** command to recreate the index. * Check the data files of the table partition. ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name PARTITION {(partition_name)}[CASCADE]; ``` > \[!NOTE]NOTE > You can check a single partition of a table, but cannot perform the **CASCADE** operation on the indexes of an index table. ## Parameter Description * **VERBOSE** Enables the display of progress messages. > \[!NOTE]NOTE > If **VERBOSE** is specified, **ANALYZE** displays the progress information, indicating the table that is being processed. Statistics about tables are also displayed. * **table\_name** Specifies the name (possibly schema-qualified) of a specific table to analyze. If omitted, all regular tables (but not foreign tables) in the current database are analyzed. Currently, you can use **ANALYZE** to collect statistics only from row-store tables and column-store tables. Value range: an existing table name * **column\_name**, column\_1\_name, column\_2\_name Specifies the name of a specific column to analyze. All columns are analyzed by default. Value range: an existing column name * **partition\_name** Assumes the table is a partitioned table. You can specify **partition\_name** following the keyword **PARTITION** to analyze the statistics of this table. Currently, **ANALYZE** can be performed on partitioned tables, but statistics of specified partitions cannot be analyzed. Value range: a partition name of a table * **index\_name** Specifies the name of the specific index table to be analyzed (possibly schema-qualified). Value range: an existing table name * **FAST|COMPLETE** For a row-store table, the **FAST** mode verifies the CRC and page header of the row-store table. If the verification fails, an alarm is generated. In **COMPLETE** mode, the pointer and tuple of the row-store table are parsed and verified. For a column-store table, the **FAST** mode verifies the CRC and magic of the column-store table. If the verification fails, an alarm is generated. In **COMPLETE** mode, the CU of the column-store table is parsed and verified. * **CASCADE** In **CASCADE** mode, all indexes of the current table are verified. ## Examples \-- Create a table. ``` openGauss=# CREATE TABLE customer_info ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) ; ``` \-- Create a partitioned table. ``` openGauss=# CREATE TABLE customer_par ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2452275), PARTITION P2 VALUES LESS THAN(2452640), PARTITION P3 VALUES LESS THAN(2453000), PARTITION P4 VALUES LESS THAN(MAXVALUE) ) ENABLE ROW MOVEMENT; ``` \-- Run **ANALYZE** to update statistics. ``` openGauss=# ANALYZE customer_info; openGauss=# ANALYZE customer_par; ``` \-- Run the **ANALYZE VERBOSE** statement to update statistics and display table information. ``` openGauss=# ANALYZE VERBOSE customer_info; INFO: analyzing "cstore.pg_delta_3394584009"(cn_5002 pid=53078) INFO: analyzing "public.customer_info"(cn_5002 pid=53078) INFO: analyzing "public.customer_info" inheritance tree(cn_5002 pid=53078) ANALYZE ``` > \[!NOTE]NOTE > If any environment-related fault occurs, check the logs of the primary node of the database. \-- Delete the table. ``` openGauss=# DROP TABLE customer_info; openGauss=# DROP TABLE customer_par; ``` --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-analyze-analyse.md --- # ANALYZE | ANALYSE ## Function **ANALYZE** collects statistics on ordinary tables in a database, and stores the results in the **PG\_STATISTIC** system catalog. The execution plan generator uses these statistics to determine which one is the most effective execution plan. If no parameter is specified, **ANALYZE** analyzes each table and partitioned table in the current database. You can also specify **table\_name**, **column**, and **partition\_name** to limit the analysis to a specified table, column, or partitioned table. **ANALYZE|ANALYSE VERIFY** is used to check whether data files of ordinary tables (row-store tables and column-store tables) in a database are damaged. ## Precautions \[!NOTE]NOTE For details about the precautions, see [ANALYZE](https://docs.opengauss.org/en/docs/latest/sql_reference/analyze_analyse.html). ## Syntax * Table Statistics ``` {ANALYZE | ANALYSE} [ VERBOSE ] [ NO_WRITE_TO_BINLOG | LOCAL ] TABLE { [schema.]table_name } [, ... ] ``` ## Parameter Description * **NO\_WRITE\_TO\_BINLOG | LOCAL** It is used only for syntax and has no actual purpose. \[!NOTE]NOTE For details about the involved parameters, see [ANALYZE](https://docs.opengauss.org/en/docs/latest/sql_reference/analyze_analyse.html). ## Examples \--- Create a table. ``` openGauss=# CREATE TABLE customer_info ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) ; ``` \--- Creates a partitioned table. ``` openGauss=# CREATE TABLE customer_par ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2452275), PARTITION P2 VALUES LESS THAN(2452640), PARTITION P3 VALUES LESS THAN(2453000), PARTITION P4 VALUES LESS THAN(MAXVALUE) ) ENABLE ROW MOVEMENT; ``` \--- Run **ANALYZE** to update statistics. ``` openGauss=# ANALYZE TABLE customer_info, customer_par; Table | Op | Msg_type | Msg_text ----------------------+---------+----------+---------- public.customer_info | analyze | status | OK public.customer_par | analyze | status | OK (2 row) ``` \--- Delete a table. ``` openGauss=# DROP TABLE customer_info; openGauss=# DROP TABLE customer_par; ``` ## Helpful Links [ANALYZE](https://docs.opengauss.org/en/docs/latest/sql_reference/analyze_analyse.html) --- --- url: /en/docs/latest/sql_reference/analyze_analyse.md --- # ANALYZE | ANALYSE ## Function **ANALYZE** collects statistics about ordinary tables in a database, and stores the results in the **PG\_STATISTIC** system catalog. The execution plan generator uses these statistics to determine which one is the most effective execution plan. If no parameter is specified, **ANALYZE** analyzes each table and partitioned table in the current database. You can also specify the **table\_name**, **column**, and **partition\_name** parameters to restrict the analysis to a specific table, column, or partitioned table. **ANALYZE | ANALYSE VERIFY** is used to check whether data files of common tables (row-store and column-store tables) in a database are damaged. ## Precautions * Non-temporary tables cannot be analyzed in an anonymous block, transaction block, function, or stored procedure. Temporary tables in a stored procedure can be analyzed but their statistics updates cannot be rolled back. * The **ANALYZE VERIFY** operation is used to detect abnormal scenarios. The **RELEASE** version is required. In the **ANALYZE VERIFY** scenario, remote read is not triggered. Therefore, the remote read parameter does not take effect. If the system detects that a page is damaged due to an error in a key system table, the system directly reports an error and does not continue the detection. * With no table specified, **ANALYZE** processes all the tables that the current user has permission to analyze in the current database. With tables specified, **ANALYZE** processes only the specified tables. * To perform ANALYZE operation to a table, you must be a table owner or a user granted the VACUUM permission on the table. By default, the system administrator has this permission. However, database owners are allowed to **ANALYZE** all tables in their databases, except shared catalogs. (The restriction for shared catalogs means that a true database-wide **ANALYZE** can only be executed by the system administrator). **ANALYZE** skips tables on which users do not have permissions. ## Syntax * Collect statistics information about a table. ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ]; ``` * Collect statistics about a partitioned table. ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ] PARTITION ( partition_name ) ; ``` > \[!NOTE]NOTE > An ordinary partitioned table supports the syntax but not the function of collecting statistics about specified partitions. * Collect statistics about multiple columns. ``` {ANALYZE | ANALYSE} [ VERBOSE ] table_name (( column_1_name, column_2_name [, ...] )); ``` > \[!NOTE]NOTE > > * When collecting statistics about multiple columns, set the GUC parameter [default\_statistics\_target](../database_reference/other_optimizer_options.md#en-us_topic_0283137690_en-us_topic_0237124719_en-us_topic_0059779049_se18c86fcdf5e4a22870f71187436d815) to a negative value to sample data in percentage. > > * If the GUC parameter **enable\_functional\_dependency** is disabled, the statistics about a maximum of 32 columns can be collected at a time. If the GUC parameter **enable\_functional\_dependency** is enabled, the statistics about a maximum of 4 columns can be collected at a time. > > * You are not allowed to collect statistics about multiple columns in system catalogs. * Check the data files in the current database. ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE}; ``` > \[!NOTE]NOTE > > * In fast mode, DML operations need to be performed on the tables to be verified concurrently. As a result, an error is reported during the verification. In the current fast mode, data is directly read from the disk. When other threads modify files concurrently, the obtained data is incorrect. Therefore, you are advised to perform the verification offline. > > * You can perform operations on the entire database. Because a large number of tables are involved, you are advised to save the result **gsql -d database -p port -f "verify.sql"> verify\_warning.txt 2>&1** in redirection mode. > > * NOTICE is used to check only tables that are visible to external systems. The detection of internal tables is included in the external tables on which NOTICE depends and is not displayed externally. > > * This statement can be executed with error tolerance. The **Assert** of the debug version may cause the core to fail to execute commands. Therefore, you are advised to perform the operations in release mode. > > * If a key system table is damaged during a full database operation, an error is reported and the operation stops. * Check data files of tables and indexes. ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name|index_name [CASCADE]; ``` > \[!NOTE]NOTE > > * Operations on ordinary tables and index tables are supported, but **CASCADE** operations on indexes of index tables are not supported. The **CASCADE** mode is used to process all index tables of the primary table. When the index tables are checked separately, the **CASCADE** mode is not required. > > * When the primary table is checked, the internal tables of the primary table, such as the toast table and cudesc table, are also checked. > > * When the system displays a message indicating that the index table is damaged, you are advised to run the **reindex** command to recreate the index. * Check the data files of the table partition. ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name PARTITION {(partition_name)}[CASCADE]; ``` > \[!NOTE]NOTE > You can check a single partition of a table, but cannot perform the **CASCADE** operation on the indexes of an index table. ## Parameter Description * **VERBOSE** Enables the display of progress messages. > \[!NOTE]NOTE > If **VERBOSE** is specified, **ANALYZE** displays the progress information, indicating the table that is being processed. Statistics about tables are also displayed. * **table\_name** Specifies the name (possibly schema-qualified) of a specific table to analyze. If omitted, all regular tables (but not foreign tables) in the current database are analyzed. Currently, you can use **ANALYZE** to collect statistics only from row-store tables and column-store tables. Value range: an existing table name * **column\_name**, column\_1\_name, column\_2\_name Specifies the name of a specific column to analyze. All columns are analyzed by default. Value range: an existing column name * **partition\_name** Specifies a partitioned table after the keyword **PARTITION** to analyze the table statistics. Currently the partitioned table supports the syntax of analyzing a partitioned table, but does not execute this syntax. Value range: a partition name of a table * **index\_name** Specifies the name of the specific index table to be analyzed (possibly schema-qualified). Value range: an existing table name * **FAST|COMPLETE** For a row-store table, the **FAST** mode verifies the CRC and page header of the row-store table. If the verification fails, an alarm is generated. In **COMPLETE** mode, the pointer and tuple of the row-store table are parsed and verified. For a column-store table, the **FAST** mode verifies the CRC and magic of the column-store table. If the verification fails, an alarm is generated. In **COMPLETE** mode, the CU of the column-store table is parsed and verified. * **CASCADE** In **CASCADE** mode, all indexes of the current table are verified. ## Examples \-- Create a table. ``` openGauss=# CREATE TABLE customer_info ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) ; -- Create a partitioned table. openGauss=# CREATE TABLE customer_par ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2452275), PARTITION P2 VALUES LESS THAN(2452640), PARTITION P3 VALUES LESS THAN(2453000), PARTITION P4 VALUES LESS THAN(MAXVALUE) ) ENABLE ROW MOVEMENT; -- Run **ANALYZE** to update statistics. openGauss=# ANALYZE customer_info; openGauss=# ANALYZE customer_par; -- Run the **ANALYZE VERBOSE** statement to update statistics and display table information. openGauss=# ANALYZE VERBOSE customer_info; INFO: analyzing "cstore.pg_delta_3394584009"(cn_5002 pid=53078) INFO: analyzing "public.customer_info"(cn_5002 pid=53078) INFO: analyzing "public.customer_info" inheritance tree(cn_5002 pid=53078) ANALYZE -- Delete the table. openGauss=# DROP TABLE customer_info; openGauss=# DROP TABLE customer_par; ``` --- --- url: /zh/docs/latest-lite/sql_reference/analyze_analyse.md --- # ANALYZE | ANALYSE ## 功能描述 用于收集与数据库中普通表内容相关的统计信息,统计结果存储在系统表PG\_STATISTIC下。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。 如果没有指定参数,ANALYZE会分析当前数据库中的每个表和分区表。同时也可以通过指定table\_name、column和partition\_name参数把分析限定在特定的表、列或分区表中。 ANALYZE|ANALYSE VERIFY用于检测数据库中普通表(行存表、列存表)的数据文件是否损坏。 ## 注意事项 * ANALYZE非临时表不能在一个匿名块、事务块、函数或存储过程内被执行。支持存储过程中ANALYZE临时表,不支持统计信息回滚操作。 * ANALYZE VERIFY操作处理的大多为异常场景检测需要使用RELEASE版本。ANALYZE VERIFY 场景不触发远程读,因此远程读参数不生效。对于关键系统表出现错误被系统检测出页面损坏时,将直接报错不再继续检测。 * 如果没有指定参数,ANALYZE处理当前数据库里用户拥有相应权限的每个表。如果参数中指定了表,ANALYZE只处理指定的表。 * 要对一个表进行ANALYZE操作,通常用户必须是表的所有者或者被授予了指定表VACUUM权限的用户,默认系统管理员有该权限。数据库的所有者允许对数据库中除了共享目录以外的所有表进行ANALYZE操作(该限制意味着只有系统管理员才能真正对一个数据库进行ANALYZE操作)。ANALYZE命令会跳过那些用户没有权限的表。 ## 语法格式 * 收集表的统计信息。 ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ]; ``` * 收集分区表的统计信息。 ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ] PARTITION ( partition_name ) ; ``` * 收集子分区的统计信息 ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ] SUBPARTITION ( subpartition_name ) ; ``` * 收集多列统计信息。 ``` {ANALYZE | ANALYSE} [ VERBOSE ] table_name (( column_1_name, column_2_name [, ...] )); ``` > \[!NOTE]说明 > > * 收集多列统计信息时,请设置GUC参数[default\_statistics\_target](../database_reference/other_optimizer_options.md#zh-cn_topic_0283137690_zh-cn_topic_0237124719_zh-cn_topic_0059779049_se18c86fcdf5e4a22870f71187436d815)为负数,以使用百分比采样方式。 > * 如果关闭GUC参数enable\_functional\_dependency,每组多列统计信息最多支持32列;如果开启GUC参数enable\_functional\_dependency,每组多列统计信息最多支持4列。 > * 不支持收集多列统计信息的表:系统表。 * 检测当前库的数据文件。 ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE}; ``` > \[!NOTE]说明 > > * Fast模式校验时,需要对校验的表有并发的DML操作,会导致校验过程中有误报的问题,因为当前Fast模式是直接从磁盘上读取,并发有其他线程修改文件时,会导致获取的数据不准确,建议离线操作。 > * 支持对全库进行操作,由于涉及的表较多,建议以重定向保存结果**gsql -d database -p port -f "verify.sql"> verify\_warning.txt 2>&1**。 > * 对外提示NOTICE只核对外可见的表,内部表的检测会包含在它所依赖的外部表,不对外显示和呈现。 > * 此命令的处理可容错ERROR级别的处理。由于debug版本的Assert可能会导致core无法继续执行命令,建议在release模式下操作。 > * 对于全库操作时,当关键系统表出现损坏则直接报错,不再继续执行。 * 检测表和索引的数据文件 ``` {ANALYZE | ANALYSE} VERIFY { FAST | COMPLETE } { table_name | index_name } [CASCADE]; ``` > \[!NOTE]说明 > > * 支持对普通表的操作和索引表的操作,但不支持对索引表index使用CASCADE操作。原因是由于CASCADE模式用于处理主表的所有索引表,当单独对索引表进行检测时,无需使用CASCADE模式。 > * 对于主表的检测会同步检测主表的内部表,例如toast表、cudesc表等。 > * 当提示索引表损坏时,建议使用reindex命令进行重建索引操作。 * 检测表分区的数据文件 ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name PARTITION {(partition_name)}[CASCADE]; ``` > \[!NOTE]说明 > 支持对表的单独分区进行检测操作,但不支持对索引表index使用CASCADE操作。 ## 参数说明 * **VERBOSE** 启用显示进度信息。 > \[!NOTE]说明 > 如果指定了VERBOSE,ANALYZE发出进度信息,表明目前正在处理的表。各种有关表的统计信息也会打印出来。 * **table\_name** 需要分析的特定表的表名(可能会带模式名),如果省略,将对数据库中的所有表(非外部表)进行分析。 对于ANALYZE收集统计信息,目前仅支持行存表、列存表。 取值范围:已有的表名。 * **column\_name**,column\_1\_name,column\_2\_name 需要分析特定列的列名,默认为所有列。 取值范围:已有的列名。 * **partition\_name** 如果table为分区表,在关键字PARTITION后面指定分区名partition\_name表示分析该分区表的统计信息。 取值范围:表的某一个分区名。 * **subpartition\_name** 如果table为二级分区表,在关键字SUBPARTITION后面指定分区名subpartition\_name表示分析该子分区表的统计信息。 * **index\_name** 需要分析的特定索引表的表名(可能会带模式名)。 取值范围:已有的表名。 * **FAST|COMPLETE** 对于行存表,FAST模式下主要对于行存表的CRC和page header进行校验,如果校验失败则会告警; 而COMPLETE模式下,则主要对行存表的指针、tuple进行解析校验。 对于列存表,FAST模式下主要对于列存表的CRC和magic进行校验,如果校验失败则会告警; 而COMPLETE模式下,则主要对列存表的CU进行解析校验。 * **CASCADE** CASCADE模式下会对当前表的所有索引进行检测处理。 ## 示例 \--- 创建表。 ``` openGauss=# CREATE TABLE customer_info ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) ; ``` \--- 创建分区表。 ``` openGauss=# CREATE TABLE customer_par ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2452275), PARTITION P2 VALUES LESS THAN(2452640), PARTITION P3 VALUES LESS THAN(2453000), PARTITION P4 VALUES LESS THAN(MAXVALUE) ) ENABLE ROW MOVEMENT; ``` \--- 使用ANALYZE语句更新统计信息。 ``` openGauss=# ANALYZE customer_info; openGauss=# ANALYZE customer_par; ``` \--- 使用ANALYZE VERBOSE语句更新统计信息,并输出表的相关信息。 ``` openGauss=# ANALYZE VERBOSE customer_info; INFO: analyzing "cstore.pg_delta_3394584009"(cn_5002 pid=53078) INFO: analyzing "public.customer_info"(cn_5002 pid=53078) INFO: analyzing "public.customer_info" inheritance tree(cn_5002 pid=53078) ANALYZE ``` > \[!NOTE]说明 > 若环境若有故障,需查看数据库主节点的log。 \--- 删除表。 ``` openGauss=# DROP TABLE customer_info; openGauss=# DROP TABLE customer_par; ``` --- --- url: /zh/docs/latest/sql_reference/analyze_analyse.md --- # ANALYZE | ANALYSE ## 功能描述 用于收集与数据库中普通表内容相关的统计信息,统计结果存储在系统表PG\_STATISTIC下。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。 如果没有指定参数,ANALYZE会分析当前数据库中的每个表和分区表。同时也可以通过指定table\_name、column和partition\_name参数把分析限定在特定的表、列或分区表中。 ANALYZE|ANALYSE VERIFY用于检测数据库中普通表(行存表、列存表)的数据文件是否损坏。 ## 注意事项 * ANALYZE非临时表不能在一个匿名块、事务块、函数或存储过程内被执行。支持存储过程中ANALYZE临时表,不支持统计信息回滚操作。 * ANALYZE VERIFY操作处理的大多为异常场景检测需要使用RELEASE版本。ANALYZE VERIFY 场景不触发远程读,因此远程读参数不生效。对于关键系统表出现错误被系统检测出页面损坏时,将直接报错不再继续检测。 * 如果没有指定参数,ANALYZE处理当前数据库里用户拥有相应权限的每个表。如果参数中指定了表,ANALYZE只处理指定的表。 * 要对一个表进行ANALYZE操作,通常用户必须是表的所有者或者被授予了指定表VACUUM权限的用户,默认系统管理员有该权限。数据库的所有者允许对数据库中除了共享目录以外的所有表进行ANALYZE操作(该限制意味着只有系统管理员才能真正对一个数据库进行ANALYZE操作)。ANALYZE命令会跳过那些用户没有权限的表。 ## 语法格式 * 收集表的统计信息。 ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ]; ``` * 收集分区表的统计信息。 ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ] PARTITION ( partition_name ) ; ``` * 收集子分区的统计信息 ``` { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ] SUBPARTITION ( subpartition_name ) ; ``` * 收集多列统计信息。 ``` {ANALYZE | ANALYSE} [ VERBOSE ] table_name (( column_1_name, column_2_name [, ...] )); ``` > \[!NOTE]说明 > > * 收集多列统计信息时,请设置GUC参数[default\_statistics\_target](../database_reference/other_optimizer_options.md#zh-cn_topic_0283137690_zh-cn_topic_0237124719_zh-cn_topic_0059779049_se18c86fcdf5e4a22870f71187436d815)为负数,以使用百分比采样方式。 > > * 如果关闭GUC参数enable\_functional\_dependency,每组多列统计信息最多支持32列;如果开启GUC参数enable\_functional\_dependency,每组多列统计信息最多支持4列。 > > * 不支持收集多列统计信息的表:系统表。 * 检测当前库的数据文件。 ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE}; ``` > \[!NOTE]说明 > > * Fast模式校验时,需要对校验的表有并发的DML操作,会导致校验过程中有误报的问题,因为当前Fast模式是直接从磁盘上读取,并发有其他线程修改文件时,会导致获取的数据不准确,建议离线操作。 > > * 支持对全库进行操作,由于涉及的表较多,建议以重定向保存结果**gsql -d database -p port -f "verify.sql"> verify\_warning.txt 2>&1**。 > > * 对外提示NOTICE只核对外可见的表,内部表的检测会包含在它所依赖的外部表,不对外显示和呈现。 > > * 此命令的处理可容错ERROR级别的处理。由于debug版本的Assert可能会导致core无法继续执行命令,建议在release模式下操作。 > > * 对于全库操作时,当关键系统表出现损坏则直接报错,不再继续执行。 * 检测表和索引的数据文件 ``` {ANALYZE | ANALYSE} VERIFY { FAST | COMPLETE } { table_name | index_name } [CASCADE]; ``` > \[!NOTE]说明 > > * 支持对普通表的操作和索引表的操作,但不支持对索引表index使用CASCADE操作。原因是由于CASCADE模式用于处理主表的所有索引表,当单独对索引表进行检测时,无需使用CASCADE模式。 > > * 对于主表的检测会同步检测主表的内部表,例如toast表、cudesc表等。 > > * 当提示索引表损坏时,建议使用reindex命令进行重建索引操作。 * 检测表分区的数据文件 ``` {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name PARTITION {(partition_name)}[CASCADE]; ``` > \[!NOTE]说明 > 支持对表的单独分区进行检测操作,但不支持对索引表index使用CASCADE操作。 ## 参数说明 * **VERBOSE** 启用显示进度信息。 > \[!NOTE]说明 > 如果指定了VERBOSE,ANALYZE发出进度信息,表明目前正在处理的表。各种有关表的统计信息也会打印出来。 * **table\_name** 需要分析的特定表的表名(可能会带模式名),如果省略,将对数据库中的所有表(非外部表)进行分析。 对于ANALYZE收集统计信息,目前仅支持行存表、列存表。 取值范围:已有的表名。 * **column\_name**,column\_1\_name,column\_2\_name 需要分析特定列的列名,默认为所有列。 取值范围:已有的列名。 * **partition\_name** 如果table为分区表,在关键字PARTITION后面指定分区名partition\_name表示分析该分区表的统计信息。 取值范围:表的某一个分区名。 * **subpartition\_name** 如果table为二级分区表,在关键字SUBPARTITION后面指定分区名subpartition\_name表示分析该子分区表的统计信息。 * **index\_name** 需要分析的特定索引表的表名(可能会带模式名)。 取值范围:已有的表名。 * **FAST|COMPLETE** 对于行存表,FAST模式下主要对于行存表的CRC和page header进行校验,如果校验失败则会告警; 而COMPLETE模式下,则主要对行存表的指针、tuple进行解析校验。 对于列存表,FAST模式下主要对于列存表的CRC和magic进行校验,如果校验失败则会告警; 而COMPLETE模式下,则主要对列存表的CU进行解析校验。 * **CASCADE** CASCADE模式下会对当前表的所有索引进行检测处理。 ## 示例 \-- 创建表。 ``` openGauss=# CREATE TABLE customer_info ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) ; -- 创建分区表。 openGauss=# CREATE TABLE customer_par ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER ) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2452275), PARTITION P2 VALUES LESS THAN(2452640), PARTITION P3 VALUES LESS THAN(2453000), PARTITION P4 VALUES LESS THAN(MAXVALUE) ) ENABLE ROW MOVEMENT; -- 使用ANALYZE语句更新统计信息。 openGauss=# ANALYZE customer_info; openGauss=# ANALYZE customer_par; -- 使用ANALYZE VERBOSE语句更新统计信息,并输出表的相关信息。 openGauss=# ANALYZE VERBOSE customer_info; INFO: analyzing "cstore.pg_delta_3394584009"(cn_5002 pid=53078) INFO: analyzing "public.customer_info"(cn_5002 pid=53078) INFO: analyzing "public.customer_info" inheritance tree(cn_5002 pid=53078) ANALYZE -- 删除表。 openGauss=# DROP TABLE customer_info; openGauss=# DROP TABLE customer_par; ``` --- --- url: /en/docs/latest-lite/database_om_guide/analysis_table.md --- # ANALYZE Table The execution plan generator needs to use table statistics to generate the most effective query execution plan to improve query performance. After data is imported, you are advised to run the **ANALYZE** statement to update table statistics. The statistics are stored in the system catalog **PG\_STATISTIC**. ## ANALYZE Table **ANALYZE** supports row-store and column-store tables. **ANALYZE** can also collect statistics about specified columns of a local table. For details on **ANALYZE**, see [ANALYZE | ANALYSE](../sql_reference/analyze_analyse.md). 1. Update table statistics. Do **ANALYZE** to the **product\_info** table. ``` openGauss=# ANALYZE product_info; ``` ``` ANALYZE ``` ## autoanalyze openGauss provides the GUC parameter [autovacuum](../database_reference/automatic_vacuuming.md#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s995913ca9df54ae5bb488d1e810bd824) to specify whether to enable the autovacuum function of the database. If **autovacuum** is set to **on**, the system will start the autovacuum thread to automatically analyze tables when the data volume in the table reaches the threshold. This is the autoanalyze function. * For an empty table, when the number of rows inserted to it is greater than 50, **ANALYZE** is automatically triggered. * For a table containing data, the threshold is 50 + 10% x **reltuples**, where **reltuples** indicates the total number of rows in the table. The autovacuum function also depends on the following two GUC parameters in addition to **autovacuum**: * [track\_counts](../database_reference/query_and_index_statistics_collector.md#en-us_topic_0283136895_en-us_topic_0237124727_en-us_topic_0059779313_s3f4fb0b1004041f69e1454c701952411): This parameter must be set to **on** to enable statistics collection about the database. * [autovacuum\_max\_workers](../database_reference/automatic_vacuuming.md#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s76932f79410248ba8923017d19982673): This parameter must be set to a value greater than **0** to specify the maximum number of concurrent autovacuum threads. > \[!TIP]NOTICE > > * The autoanalyze function supports the default sampling mode but not percentage sampling. > * The autoanalyze function does not collect multi-column statistics, which only supports percentage sampling. > * The autoanalyze function supports row-store and column-store tables and does not support foreign tables, temporary tables, unlogged tables, and TOAST tables. --- --- url: /en/docs/latest/database_om_guide/analysis_table.md --- # ANALYZE Table The execution plan generator needs to use table statistics to generate the most effective query execution plan to improve query performance. After data is imported, you are advised to run the **ANALYZE** statement to update table statistics. The statistics are stored in the system catalog **PG\_STATISTIC**. ## ANALYZE Table **ANALYZE** supports row-store and column-store tables. **ANALYZE** can also collect statistics about specified columns of a local table. For details on **ANALYZE**, see [ANALYZE | ANALYSE](../sql_reference/analyze_analyse.md). Update table statistics. Do **ANALYZE** to the **product\_info** table. ``` ANALYZE product_info; ``` ``` ANALYZE ``` ## autoanalyze openGauss provides the GUC parameter [autovacuum](../database_reference/automatic_vacuuming.md#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s995913ca9df54ae5bb488d1e810bd824) to specify whether to enable the autovacuum function of the database. If **autovacuum** is set to **on**, the system will start the autovacuum thread to automatically analyze tables when the data volume in the table reaches the threshold. This is the autoanalyze function. * For an empty table, when the number of rows inserted to it is greater than 50, **ANALYZE** is automatically triggered. * For a table containing data, the threshold is 50 + 10% x **reltuples**, where **reltuples** indicates the total number of rows in the table. The autovacuum function also depends on the following two GUC parameters in addition to **autovacuum**: * [track\_counts](../database_reference/query_and_index_statistics_collector.md#en-us_topic_0283136895_en-us_topic_0237124727_en-us_topic_0059779313_s3f4fb0b1004041f69e1454c701952411): This parameter must be set to **on** to enable statistics collection about the database. * [autovacuum\_max\_workers](../database_reference/automatic_vacuuming.md#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s76932f79410248ba8923017d19982673): This parameter must be set to a value greater than **0** to specify the maximum number of concurrent autovacuum threads. > \[!TIP]NOTICE > > * The autoanalyze function supports the default sampling mode but not percentage sampling. > * The autoanalyze function does not collect multi-column statistics, which only supports percentage sampling. > * The autoanalyze function supports row-store and column-store tables and does not support foreign tables, temporary tables, unlogged tables, and TOAST tables. --- --- url: >- /en/docs/latest-lite/database_om_guide/analyzing_the_status_of_a_query_statement.md --- # Analyzing the Status of a Query Statement ## Symptom Some query statements are executed for an excessively long time in the system. You need to analyze the status of the query statements. ## Procedure 1. Log in to the host as the OS user **omm**. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 ``` **postgres** is the name of the database, and **8000** is the port number. 3. Set the parameter **track\_activities** to **on**. ``` SET track_activities = on; ``` The database collects the running information about active queries only if the parameter is set to **on**. 4. View the running query statements. The **pg\_stat\_activity** view is used as an example here. ``` SELECT datname, usename, state, query FROM pg_stat_activity; datname | usename | state | query ----------+---------+--------+------- postgres | omm | idle | postgres | omm | active | (2 rows) ``` If the **state** column is **idle**, the connection is idle and requires a user to enter a command. To identify only active query statements, run the following command: ``` SELECT datname, usename, state, query FROM pg_stat_activity WHERE state != 'idle'; ``` 5. Analyze whether a query statement is in the active or blocked state. Run the following command to view a query statement in the block state: ``` SELECT datname, usename, state, query FROM pg_stat_activity WHERE waiting = true; ``` The query statement is displayed. It is requesting a lock resource that may be held by another session, and is waiting for the lock resource to be released by the session. --- --- url: /en/docs/latest/resource_pooling/analyzing_the_status_of_a_query_statement.md --- # Analyzing the Status of a Query Statement ## Symptom Some query statements are executed for an excessively long time in the system. You need to analyze the status of the query statements. ## Procedure 1. Log in to the host as the OS user **omm**. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 ``` **postgres** is the name of the database, and **8000** is the port number. 3. Set the parameter **track\_activities** to **on**. ``` SET track_activities = on; ``` The database collects the running information about active queries only if the parameter is set to **on**. 4. View the running query statements. The **pg\_stat\_activity** view is used as an example here. ``` SELECT datname, usename, state, query FROM pg_stat_activity; datname | usename | state | query ----------+---------+--------+------- postgres | omm | idle | postgres | omm | active | (2 rows) ``` If the **state** column is **idle**, the connection is idle and requires a user to enter a command. To identify only active query statements, run the following command: ``` SELECT datname, usename, state, query FROM pg_stat_activity WHERE state != 'idle'; ``` 5. Analyze whether a query statement is in the active or blocked state. Run the following command to view a query statement in the block state: ``` SELECT datname, usename, state, query FROM pg_stat_activity WHERE waiting = true; ``` The query statement is displayed. It is requesting a lock resource that may be held by another session, and is waiting for the lock resource to be released by the session. --- --- url: >- /en/docs/latest-lite/database_om_guide/analyzing_whether_a_query_statement_is_blocked.md --- # Analyzing Whether a Query Statement Is Blocked ## Symptom During database running, query statements are blocked in some service scenarios. As a result, the query statements are executed for an excessively long time. ## Cause Analysis A query statement uses a lock to protect the data objects that it wants to access. If the data objects have been locked by another session, the query statement will be blocked and wait for the session to complete operation and release the lock resource. The data objects requiring locks include tables and tuples. ## Procedure 1. Log in to the host as the OS user **omm**. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 ``` **postgres** is the name of the database, and **8000** is the port number. 3. Find the thread ID of the faulty session from the current active session view. ``` SELECT w.query AS waiting_query, w.pid AS w_pid, w.usename AS w_user, l.query AS locking_query, l.pid AS l_pid, l.usename AS l_user, t.schemaname || '.' || t.relname AS tablename FROM pg_stat_activity w JOIN pg_locks l1 ON w.pid = l1.pid AND NOT l1.granted JOIN pg_locks l2 ON l1.relation = l2.relation AND l2.granted JOIN pg_stat_activity l ON l2.pid = l.pid JOIN pg_stat_user_tables t ON l1.relation = t.relid WHERE w.waiting = true; ``` 4. Terminate the session using its thread ID. ``` SELECT pg_terminate_backend(139834762094352); ``` If information similar to the following is displayed, the session is successfully terminated: ``` pg_terminate_backend --------------------- t (1 row) ``` If a command output similar to the following is displayed, a user is attempting to terminate the session, and the session will be reconnected rather than being terminated. ``` FATAL: terminating connection due to administrator command FATAL: terminating connection due to administrator command The connection to the server was lost. Attempting reset: Succeeded. ``` --- --- url: >- /en/docs/latest/resource_pooling/analyzing_whether_a_query_statement_is_blocked.md --- # Analyzing Whether a Query Statement Is Blocked ## Symptom During database running, query statements are blocked in some service scenarios. As a result, the query statements are executed for an excessively long time. ## Cause Analysis A query statement uses a lock to protect the data objects that it wants to access. If the data objects have been locked by another session, the query statement will be blocked and wait for the session to complete operation and release the lock resource. The data objects requiring locks include tables and tuples. ## Procedure 1. Log in to the host as the OS user **omm**. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 ``` **postgres** is the name of the database, and **8000** is the port number. 3. Find the thread ID of the faulty session from the current active session view. ``` SELECT w.query AS waiting_query, w.pid AS w_pid, w.usename AS w_user, l.query AS locking_query, l.pid AS l_pid, l.usename AS l_user, t.schemaname || '.' || t.relname AS tablename FROM pg_stat_activity w JOIN pg_locks l1 ON w.pid = l1.pid AND NOT l1.granted JOIN pg_locks l2 ON l1.relation = l2.relation AND l2.granted JOIN pg_stat_activity l ON l2.pid = l.pid JOIN pg_stat_user_tables t ON l1.relation = t.relid WHERE w.waiting = true; ``` 4. Terminate the session using its thread ID. ``` SELECT pg_terminate_backend(139834762094352); ``` If information similar to the following is displayed, the session is successfully terminated: ``` pg_terminate_backend --------------------- t (1 row) ``` If a command output similar to the following is displayed, a user is attempting to terminate the session, and the session will be reconnected rather than being terminated. ``` FATAL: terminating connection due to administrator command FATAL: terminating connection due to administrator command The connection to the server was lost. Attempting reset: Succeeded. ``` --- --- url: >- /zh/docs/latest/characteristic_description/aifeature_guide/anomaly_detection.md --- # Anomaly detection ## 概述 Anomaly detection异常检测模块的主要功能是基于统计方法来发现时序数据中可能存在的异常情况。该模块框架解耦,可以实现不同异常检测算法的灵活替换,而且该模块功能可以根据时序数据的不同特征来自动选择算法,支持异常值检测、阈值检测、箱型图检测、梯度检测、增长率检测、波动率检测和状态转换检测。 在异常检测的基础上,DBMind支持对关键指标异常的根因分析功能,其分析模型来源于大量现网场景总结,通过对指标发生异常时其他指标进行关联,输出可能的根因。 当前DBMind默认启动的检测器如[表1](#zh-cn_topic_0000001666869780_table179461740869)所示: **表 1** 检测器列表 > \[!TIP]须知 > > * 异常检测器的落盘存储依赖于元数据库,请勿在元数据库中对异常检测器相关的数据进行手动修改。 > * 当前版本仅在主备切换、扩容和节点剔除的场景下,支持对同一集群的检测器配置参数的继承和保留,其他场景均不支持。 > * 长事务检测器由长事务整体触发异常,但是计算异常个数的时候会实际计算长事务中超时之后执行的每个SQL。 > * 对于网络异常检测器,当延迟超过1000ms时,网络延迟相关指标的采集会开始出现数据丢失现象,无法保证网络数据的完整性,可能会对网络检测器的检测结果产生影响,此时应该通过集群诊断的断网检测功能上报异常。 > * 当前的异常检测器有部分检测项和智能巡检功能的某些检测项比较相似,如:CPU使用率、磁盘使用率、内存使用率、磁盘I/O使用率和线程池使用率检测等。由于智能巡检的设计目的和时间跨度与异常检测在设计上有所不同,检测阈值和条件也有所区别,所以某些相似检测项可能出现不一致的结果,这些属于正常现象。 > * 会话内存上下文指标pg\_session\_memory\_detail\_rate和共享内存上下文指标pg\_shared\_memory\_detail\_rate的超时时长为10秒,在查询内存视图耗时很长的情况下,指标所标注的时间会相应滞后。 > * 延迟和丢包率检测是通过并发多个ping命令检测起点到终点之间的连通性,通过多个ping命令返回的平均延迟和成功率来采集数据。 ## 使用指导 假设指标采集系统运行正常,并且用户已经初始化了配置文件目录confpath,则可以通过下述命令实现本特性的功能: ### 异常检测功能 仅启动异常检测功能: ``` gs_dbmind service start --conf confpath --only-run anomaly_detection ``` 对于某一指标,在全部节点上,从timestamps1到timestamps2时间段内的数据进行概览: ``` gs_dbmind component anomaly_detection --conf confpath --action overview --metric metric_name --start-time timestamps1 --end-time timestamps2 ``` 对于某一指标,在特定节点上,从timestamps1到timestamps2时间段内的数据进行概览: ``` gs_dbmind component anomaly_detection --conf confpath --action overview --metric metric_name --start-time timestamps1 --end-time timestamps2 --host ip_address ``` 对于某一指标,在全部节点上,从timestamps1到timestamps2时间段内的数据,以特定异常检测方式进行概览: ``` gs_dbmind component anomaly_detection --conf confpath --action overview --metric metric_name --start-time timestamps1 --end-time timestamps2 --anomaly anomaly_type ``` 对于某一指标,在特定节点,从timestamps1到timestamps2时间段内的数据,以特定异常检测方式进行概览: ``` gs_dbmind component anomaly_detection --conf confpath --action overview --metric metric_name --start-time timestamps1 --end-time timestamps2 --host ip_address --anomaly anomaly_type ``` 对于某一指标,在特定节点,从timestamps1到timestamps2时间段内的数据,以特定异常检测方式进行可视化展示: ``` gs_dbmind component anomaly_detection --conf confpath --action plot --metric metric_name --start-time timestamps1 --end-time timestamps2 --host ip_address --anomaly anomaly_type ``` 运行异常诊断后台任务: ``` 参考[Slow Query Diagnosis](zh-cn_topic_0000001667029332.md)中的方法,其对应定时任务为:anomaly_detection ``` ### 指标异常分析功能 指标异常根因分析接口调用: ``` curl -X 'GET' http://127.0.0.1:8080/v1/api/app/metric-diagnosis/?metric_name=os_cpu_user_usage&metric_filter={"from_instance":"127.0.0.1","from_job":"node_exporter","instance":"127.0.0.1:8181","job":"reprocessing_exporter"}&alarm_cause=["high_cpu_usage"]&start=1691482728000&end=1691482728000 -H 'accept: application/json' -H 'Content-Type: application/json' -H "Authorization: bearer xxx" ``` 如果使用HTTPS协议,则查询示例为: ``` curl -X 'GET' 'https://127.0.0.1:8080/v1/api/app/metric-diagnosis/?metric_name=os_cpu_user_usage&metric_filter={"from_instance":"127.0.0.1","from_job":"node_exporter","instance":"127.0.0.1:8181","job":"reprocessing_exporter"}&alarm_cause=["high_cpu_usage"]&start=1691482728000&end=1691482728000' -H 'accept: application/json' -H 'Content-Type: application/json' -H "Authorization: bearer xxx" --cacert xx.crt --key xx.key --cert xx.crt ``` 如果DBMind以微服务模式启动,则查询示例为: ``` curl -X 'POST' 'https://127.0.0.1:8080/v2/api/app/metric-diagnosis/?metric_name=os_cpu_user_usage&metric_filter={"from_instance":"127.0.0.1","from_job":"node_exporter","instance":"127.0.0.1:8181","job":"reprocessing_exporter"}&alarm_cause=["high_cpu_usage"]&start=1691482728000&end=1691482728000' -H 'accept: application/json' -H 'Content-Type: application/json' --cacert xx.crt --key xx.key --cert xx.crt ``` 返回结果格式参考: ``` {"data":{[{'reason1': 0.0, 'reason2': 1.0}, 'conclusion', 'advice']},"success":true} ``` 停止已启动的服务: ``` gs_dbmind service stop --conf confpath ``` 指标异常分析支持的场景详细情况如下: * **场景1:用户CPU使用率异常** 异常判断标准:用户CPU使用率10分钟内持续高于80%。 可能的异常根因: * 业务压力增大导致 现象:TPS、网络读写速率、CPU使用率和内存使用率均存在一定程度的上涨。 分析:通过与相关指标进行相关性比对。 建议:根据业务量评估CPU、内存等资源是否满足业务需求,是否需要扩容。 * iowait延时高导致 现象:数据库磁盘的读时延和写时延变长。 建议:增加I/O吞吐量,排查可以降低I/O的进程。 分析时提供的信息: * 提供pg\_stat\_activity每个unique\_sql\_id的总运行时间的快照信息。 * **场景2:线程池使用率异常** 异常判断标准:默认的异常检测规则是线程池使用率10分钟内持续高于80%。 可能的异常根因: * 业务压力增大导致 现象:TPS、网络读写速率、内存使用率和线程池使用率基本存在一定程度的关联。 分析:通过与相关指标进行相关性比对。 建议:根据业务量评估CPU、内存等资源是否满足业务需求,是否需要扩容。 * 磁盘读写时延过高导致 现象:数据库磁盘读写时延增高,导致线程池使用率超过配置的阈值。 分析:查看产生报警的节点的线程池使用率与数据盘I/O平均读写时长的相关性。 建议:若发现数据库磁盘读写时延频繁过高或者有明显劣化趋势,则继续定位是否磁盘硬件故障。 * 工作负载上升导致 现象:QPS、CPU使用率和系统内存持续上涨。 分析:根据算法对QPS、CPU使用率和系统内存持续上涨进行判断。 建议:数据库负载上升,考虑采用限流措施。 * **场景3:动态内存使用率异常** 异常判断标准:系统内存超过阈值(默认10分钟连续超过80%),再进行动态内存使用率异常分析。 可能的异常根因: * 会话数上涨导致 现象:在线会话数量指标随内存上涨的同时上涨。 分析:查看同一时间段内会话数量和内存上涨之间的关系,通过皮尔逊计算相关系数,绝对值超过阈值的指标会被认为是相关异常。 建议:停止变更。 * 动态内存泄露导致 现象:动态内存持续上涨。 分析:查看内存占用较大的上下文数量,如未发生很大变化则可能是内存泄露。 建议:通过pg\_terminate\_session终止会话或重启DN进程。 * 非数据库内存泄露导致 现象:非数据库内存持续上涨。 分析:查看非数据库内存占用。 建议:分析系统内存占用,终止节点上其他占用内存较高的进程。 分析时提供的信息: * 提供session\_memory\_detail的快照信息。 * **场景4:共享内存使用率异常** 异常判断标准:系统内存超过阈值(默认10分钟连续超过80%),再进行共享内存使用率异常分析。 可能的异常根因: * 未落盘脏页数过高导致 现象:INSERT或UPDATE操作比例突然增大。 分析:分析INSERT或UPDATE操作比例突然增大与共享内存的相关性,通过皮尔逊计算相关系数,绝对值超过阈值的指标会被认为是相关异常。 建议:考虑降低pagewriter\_sleep参数,加速脏页落盘的速度;考虑降低dirty\_page\_percent\_max参数,降低刷页阈值上限。 * 共享内存泄露导致 现象:共享内存持续上涨。 分析:查看系统内存占用,确认是否有除了openGauss进程外占用大量内存的进程。 建议:手动清理,执行“ipcrm -m shmid”(此命令操作危险,请谨慎操作)。 分析时提供的信息: * 提供shared\_memory\_detail的快照信息。 * **场景5:磁盘空间占用高异常** 异常判断标准:磁盘空间占用超过阈值(默认80%)。 可能的异常根因: * 数据库表空间膨胀导致 现象:数据库磁盘占用快速上升。 分析:分析INSERT或UPDATE操作比例和磁盘I/O读写情况来确定脏数据是否增加过快。 建议:临时情况,无需处理。 * Xlog堆积导致 现象:Xlog路径占用空间过大。 分析:分析Xlog数量是否超过wal\_keep\_segments + checkpoint\_segments \* 2+1。 建议:查看是否有未推进的逻辑复制槽阻塞Xlog回收。 分析时提供的信息: * 提供实时表空间信息。 * 提供临时文件信息,包括线程和会话信息。 * **场景6:磁盘I/O读取时延异常** 异常判断标准:数据库磁盘I/O使用率超过阈值(默认99%)。 可能的异常根因: * 数据磁盘读写I/O使用率超阈值导致 现象:数据库磁盘读写I/O使用率接近100%。 分析:分析数据库磁盘读写I/O使用率和时延之间的关系。 建议:降低I/O压力,提高磁盘的I/O限制。 * **场景7:扫描攻击** 异常判断标准:SQL执行错误率和用户越权率加权得分超过阈值(默认阈值:提示0.2,告警0.6,严重0.8)。 可能的异常根因: * SQL执行错误率和用户越权率增高导致 现象:SQL执行错误率和用户越权率增高。 分析:用户使用自动化工具扫描目标网络或系统的漏洞,利用这些漏洞获取未经授权的访问权限,窃取敏感数据或破坏系统目标。 建议:及时更新数据库软件和安全补丁,以修复已知漏洞,减少攻击面。 * **场景8:暴力登录** 异常判断标准:用户无效登录率和用户锁定率指标加权得分超过阈值(默认阈值:提示0.1,告警0.3,严重0.4)。 可能的异常根因: * 用户无效登录率和用户锁定率增高导致 现象:用户无效登录率和用户锁定率增高。 分析:攻击者猜测用户名和密码进行暴力登录,导致账户锁定及其他拒绝服务问题。 建议:根据告警信息,及时检查登录日志、采取相应措施。 * **场景9:违规操作** * 异常判断标准:用户越权率指标超过阈值(默认阈值:提示0.2,告警0.6,严重0.8)。 可能的异常根因: * 用户越权率增高导致 现象:用户越权率增高。 分析:攻击者使用用户凭证进行违规操作。 建议:对于敏感数据,限制访问权限。 > \[!NOTE]说明 > 其中,场景7~9的约束如下: > > * 用户需要有Monitor admin和Audit admin权限,如果没有Audit admin权限,会导致审计指标数据全为0,诊断结果不可用。 > * 需要开启audit\_enabled、audit\_login\_logout、audit\_user\_locked和audit\_user\_violation参数。 > * 审计总开关GUC参数audit\_enabled支持动态加载。在数据库运行期间修改该配置项的值会立即生效,无需重启数据库。默认值为on,表示开启审计功能。 > * 审计项audit\_login\_logout:默认值为7,表示开启用户登录、退出的审计功能。设置为0表示关闭用户登录、退出的审计功能。 > * 审计项audit\_user\_locked:默认值为1,表示开启审计用户锁定和解锁功能。 > * 审计项audit\_user\_violation:默认值为0,表示关闭用户越权操作审计功能。可通过命令 gs\_guc reload -Z datanode -N all -I all -c "audit\_user\_violation=1" 开启。 > * 如未开启审计相关参数,则只能处理扫描攻击场景。 ### 亚健康诊断功能 亚健康状态是系统介于健康状态和故障状态之间的一种状态,系统仍在运行且功能正常但处于降级模式的一种情况,它的存在会造成系统性能严重低于预期。 亚健康诊断支持的场景如下: * **场景1:潜在慢盘监测** DBMind默认初始化"slow\_disk\_detector"检测器,在每一次触发异常检测定时,任务时对潜在慢盘进行监测。 * 现象:“慢盘”现象普遍存在于存储架构之中,由于硬盘体质或者频繁读写的原因,部分硬盘会出现性能故障,I/O负载过高等情况进而导致延时变大,读写变慢的现象。 * 检测逻辑:在最近的过去7天~30天(收集的数据小于7天不进行检测),其磁盘I/O平均读写时间长期在30ms以上并呈现出上升趋势,则认为其发生潜在慢盘。 * **场景2:内存泄漏监测** DBMind默认初始化"mem\_leak\_detector"检测器,在每一次触发异常检测定时任务时对内存泄漏进行监测。 * 现象:程序中已动态分配的堆内存由于某种原因程序未释放或无法释放,造成系统内存的浪费,导致程序运行速度减慢甚至系统崩溃等严重后果。内存泄漏缺陷具有隐蔽性、积累性的特征,比其他内存非法访问错误更难检测。 * 检测逻辑:最近的过去7天~30天(收集的数据小于7天不进行检测),其内存占用呈现出上升趋势,则认为其发生内存泄漏。 可能的异常根因: * 动态内存泄露导致 现象:动态内存持续上涨。 分析:查看内存占用较大的上下文数量,如未发生很大变化则可能是内存泄露。 建议:通过pg\_terminate\_session终止会话或重启DN进程。 * 共享内存泄露导致 现象:共享内存持续上涨。 分析:查看系统内存占用,确认是否有除了openGauss进程外占用大量内存的进程。 建议:手动清理,ipcrm -m shmid(此命令操作危险,请谨慎操作)。 * 第三方软件内存增高导致 现象:other\_used\_memory持续上涨。 分析:第三方软件内存泄露。 建议:排查第三方软件的内存占用。 * 非数据库内存泄露导致 现象:非数据库内存持续上涨。 分析:查看非数据库内存占用。 建议:分析系统内存占用,终止节点上其他占用内存较高的进程。 * 用户无效登录过高导致 现象:用户无效登录数超阈值。 分析:用户无效登录日志过多,存在大量连接失败。 建议:请联系管理员。 分析时提供的信息: * 提供session\_memory\_detail的快照信息。 * 提供shared\_memory\_detail的快照信息。 * **场景3:锁冲突监测** DBMind默认初始化"deadlock\_detector"检测器,在每一次触发异常检测定时任务时对锁冲突进行监测。 * 现象:当发生锁冲突时,日志中会记录锁冲突的详细信息。 * 检测逻辑:当内核日志记录到死锁日志时,则认为其发生锁冲突,并对死锁信息进行收集。 * **场景4:Xlog堆积** 异常判断标准:Xlog数量超过wal\_keep\_segments + checkpoint\_segments \* 2。 可能的异常根因: * 逻辑复制槽阻塞Xlog回收 现象:存在未推进的逻辑复制槽。 分析:存在未推进的逻辑复制槽。 建议:可能存在阻塞Xlog回收的逻辑复制槽,请联系管理员。 * Xlog归档失败 现象:Xlog的最小lsn小于归档日志的lsn。 分析:Xlog的最小lsn小于归档日志的lsn,表示归档进程没有成功回收Xlog。 建议:Xlog归档失败问题请联系管理员。 * 备机build阻塞Xlog回收 现象:发现recycle\_build日志或者发现recycle\_full\_build日志或者发现recycle\_quorum\_required日志。 分析:发现recycle\_build日志或者发现recycle\_full\_build日志或者发现recycle\_quorum\_required日志。 建议:备机build阻塞Xlog回收问题请联系管理员。 * dcf阻塞Xlog回收 现象:发现recycle\_dcf日志。 分析:发现recycle\_dcf日志。 建议:dcf阻塞Xlog回收问题请联系管理员。 * dummy standby场景阻塞Xlog回收 现象:发现recycle\_dummy\_standby日志。 分析:发现recycle\_dummy\_standby日志。 建议:dummy standby场景阻塞Xlog回收问题请联系管理员。 * 增备阻塞Xlog回收 现象:发现recycle\_cbm日志。 分析:发现recycle\_cbm日志。 建议:增备阻塞Xlog回收问题请联系管理员。 * 备份槽阻塞Xlog回收 现象:发现recycle\_standby\_backup日志。 分析:发现recycle\_standby\_backup日志。 建议:备份槽阻塞Xlog回收问题请联系管理员。 * 极致rto阻塞Xlog回收 现象:发现recycle\_extro\_read日志。 分析:发现recycle\_extro\_read日志。 建议:极致rto阻塞Xlog回收问题请联系管理员。 * 参数设置不当 现象:磁盘空间小于(wal\_keep\_segments + checkpoint\_segments \* 2) \* wal\_segment\_size。 分析:磁盘空间小于(wal\_keep\_segments + checkpoint\_segments \* 2) \* wal\_segment\_size。 建议:磁盘空间过小,guc参数设置不当。 * Xlog回收进程失效 现象:回收日志长期不更新。 分析:回收日志长期不更新。 建议:Xlog回收进程失效问题请联系管理员。 * **场景5:长事务** 异常判断标准:存在处于active或者idle in transaction状态且运行时间超过1个小时的事务。 可能的异常根因: * 存在大量长事务 现象:长事务数量超过1个。 分析:存在未提交的长事务。 建议:如果P80、P95持续高,CPU使用率也一直保持很高,线程池使用率反复超过阈值,没有恢复迹象,则需要联系相关人员进行进一步定位分析。 分析时提供的信息: * 提供长事务发生时其session\_id对应的session\_memory\_detail的快照信息。 * 提供当前未结束的长事务的详细信息。 > \[!NOTE]说明 > > * 异常检测器的落盘存储依赖于元数据库,请勿在元数据库中对异常检测器进行手动修改。 > * 当前版本仅支持,在主备切换、扩容和剔除节点的场景下,同一集群的检测器配置参数会被继承与保留,其他场景均不支持。 > * 在输入anomaly detection的参数时,start-time设置时间至少要早于end-time设置时间30秒以上。 > * 异常检测功能依赖于异常检测器,可以通过异常检测器的查询接口/v1/api/app/anomaly-detection/detectors/{name}查看当前已添加的全部异常检测器。 > * 根因分析的某些功能依赖opengauss-exporter的指标采集,当数据库处于高负载状况下,由于opengauss-exporter设置了SQL的超时机制来保护业务,可能会导致某些复杂的查询语句超时,进而导致采集的数据为空,当发生采集失败时,可以查询opengauss-exporter的日志来进行进一步的定位。 > * 添加检测器或更改检测器参数会将检测器状态变为启用。 > * 对于初始化时默认的长期指标检测器(如slow\_disk\_detector和mem\_leak\_detector),其检测器的监测时间窗口长度是固定的,不支持修改,对于其duration参数的修改是无效的。 > * 对于长期指标检测器,当收集到的数据低于7天时,不会进行检测。当数据超过一小时以上没有更新时,不会进行检测。 > * 对Xlog堆积问题的根因分析依赖于Xlog日志的DFX功能,该功能仅在503.2版本及其后续版本中提供支持。 ## 获取帮助 异常检测模块命令行说明: ``` gs_dbmind component anomaly_detection --help ``` 显示如下帮助信息: ``` usage: [-h] --action {overview,plot} -c CONF -m METRIC -s START_TIME -e END_TIME [-H HOST] [-a {level_shift,spike,seasonal,volatility_shift}] Workload Anomaly detection: Anomaly detection of monitored metric. optional arguments: -h, --help show this help message and exit --action {overview,plot} choose a functionality to perform -c CONF, --conf CONF set the directory of configuration files -m METRIC, --metric METRIC set the metric name you want to retrieve -s START_TIME, --start-time START_TIME set the start time of for retrieving in ms, supporting UNIX-timestamp with microsecond or datetime format -e END_TIME, --end-time END_TIME set the end time of for retrieving in ms, supporting UNIX-timestamp with microsecond or datetime format -H HOST, --host HOST set a host of the metric, ip only or ip and port. -a {level_shift,spike,seasonal,volatility_shift}, --anomaly {level_shift,spike,seasonal,volatility_shift} set a anomaly detector of the metric from: "level_shift", "spike", "seasonal", "volatility_shift" ``` ## 命令参考 **表 1** 异常检测命令行参数说明 **表 2** 指标异常分析接口 ## 常见问题处理 * 概览场景失败: 1. 请检查配置文件路径是否正确。 2. 配置文件信息是否完整。 3. 检查指标名称是否准确。 4. 检查host地址是否正确。 5. 检查异常检测类型是否准确。 6. 检查起止时间内指标是否存在对应数据。 * 可视化场景失败: 1. 请检查配置文件路径是否正确。 2. 配置文件信息是否完整。 3. 检查指标名称是否准确。 4. 检查host地址是否正确。 5. 检查异常检测类型是否准确。 6. 检查起止时间内指标是否存在对应数据。 --- --- url: >- /en/docs/latest/characteristic_description/aifeature_guide/anomaly_detection.md --- # Anomaly Detection ## Overview The anomaly detection module implements time series data based on statistics methods to detect possible exceptions in the data. The framework of this module is decoupled to flexibly replace different anomaly detection algorithms. In addition, this module can automatically select algorithms based on different features of time series data. It supports anomaly value detection, threshold detection, box plot detection, gradient detection, growth rate detection, fluctuation rate detection, and status conversion detection. ## Usage Guide Assume the metric collection system is running properly and the configuration file directory **confpath** has been initialized. You can run the following commands to enable this feature: Enable only the anomaly detection function: ``` gs_dbmind service start --conf confpath --only-run anomaly_detection ``` View data for a metric on all nodes from timestamps1 to timestamps2: ``` gs_dbmind component anomaly_detection --conf confpath --action overview --metric metric_name --start-time timestamps1 --end-time timestamps2 ``` View data for a metric on a specific node from timestamps1 to timestamps2: ``` gs_dbmind component anomaly_detection --conf confpath --action overview --metric metric_name --start-time timestamps1 --end-time timestamps2 --host ip_address --anomaly anomaly_type ``` View data for a metric on all nodes from timestamps1 to timestamps2 using a specific anomaly detection mode: ``` gs_dbmind component anomaly_detection --conf confpath --action overview --metric metric_name --start-time timestamps1 --end-time timestamps2 --anomaly anomaly_type ``` View data for a metric on a specific node from timestamps1 to timestamps2 using a specific anomaly detection mode: ``` gs_dbmind component anomaly_detection --conf confpath --action overview --metric metric_name --start-time timestamps1 --end-time timestamps2 --host ip_address --anomaly anomaly_type ``` Visualize data for a metric on all nodes from timestamps1 to timestamps2 using a specific anomaly detection mode: ``` gs_dbmind component anomaly_detection --conf confpath --action plot --metric metric_name --start-time timestamps1 --end-time timestamps2 --host ip_address --anomaly anomaly_type ``` Stop the running service: ``` gs_dbmind service stop --conf confpath ``` > \[!NOTE]NOTE > When configuring anomaly detection parameters, ensure that the start-time is at least 30 seconds earlier than the end-time. ## Obtaining Help Information You can run the **--help** command to obtain the help information. For example: ``` gs_dbmind component anomaly_detection --help ``` The following information is displayed: ``` usage: anomaly_detection.py [-h] --action {overview,plot} -c CONF -m METRIC -s START_TIME -e END_TIME [-H HOST] [-a ANOMALY] Workload Anomaly detection: Anomaly detection of monitored metric. optional arguments: -h, --help show this help message and exit --action {overview,plot} choose a functionality to perform -c CONF, --conf CONF set the directory of configuration files -m METRIC, --metric METRIC set the metric name you want to retrieve -s START_TIME, --start-time START_TIME set the start time of for retrieving in ms -e END_TIME, --end-time END_TIME set the end time of for retrieving in ms -H HOST, --host HOST set a host of the metric, ip only or ip and port. -a ANOMALY, --anomaly ANOMALY set a anomaly detector of the metric(increase_rate, level_shift, spike, threshold) Process finished with exit code 0 ``` ## Command Reference **Table 1** Command Line Parameters ## Troubleshooting * Overview scenario failure: Ensure the configuration file path is correct and the configuration information is complete. Verify the metric name, host IP address, and anomaly detection type are accurate, and check if the metric data exists within the specified start and end times. * Visualization scenario failure: Ensure the configuration file path is correct and the configuration information is complete. Verify the metric name, host IP address, and anomaly detection type are accurate, and check if the metric data exists within the specified start and end times. --- --- url: >- /en/docs/latest/characteristic_description/anomaly_detection_database_indicator_collection_forecasting_and_exception_monitoring.md --- # Anomaly-detection: Database Indicator Collection, Forecasting, and Exception Monitoring ## Availability This feature is available since openGauss 1.1.0. ## Introduction Anomaly\_detection is an AI tool integrated into openGauss and can be used to collect and predict database indicators, as well as monitor and diagnose exceptions. It is a component in the dbmind suite. The following information can be collected: IO\_Read, IO\_Write, CPU\_Usage, Memory\_Usage, and disk space occupied by the database. Anomaly\_detection can monitor multiple indicators at the same time and predict the change trend of each indicator. When detecting that an indicator exceeds the manually set threshold in a certain period or at a certain moment in the future, the tool generates an alarm through logs. ## Benefits * This greatly simplifies the work of O\&M personnel, releases a large number of labor resources, and reduces costs for the company. * This feature helps users detect exceptions in advance and prevent database exceptions from causing greater loss. ## Description Anomaly\_detection consists of agent and detector. The agent and openGauss database are deployed on the same server. The agent module provides the following functions: Periodically collect database indicator data and store the collected data in the buffer queue. Periodically send the data in the buffer queue to the detector. The detector module communicates with the agent module based on HTTP or HTTPS. Therefore, the detector module can be deployed on any server that can communicate with the agent module. The detector module has the following functions: Receive the data sent by the agent and cache the collected data locally. Predict the future change trend of the indicator and report alarms based on the collected database indicator data. ## Enhancements None ## Constraints * The database is normal, and the data directory has been written into environment variables and named **PGDATA**. * If you log in to the database host as a Linux user, add *$GAUSSHOME*\*\*/bin\*\* to the \*PATH \_environment variable so that you can directly run database O\&M tools, such as gsql, gs\*guc, and gs\_ctl. * The recommended Python version is Python 3.6 or later. The required dependency has been installed in the operating environment, and the optimization program can be started properly. * This tool consists of the agent and detector. Data is transmitted between the agent and detector in HTTP or HTTPS mode. Therefore, ensure that the agent server can communicate with the detector server properly. * Detector module runs the server and monitor services, which need to be started separately. * If HTTPS is used for communication, you need to prepare the CA certificate, and certificates and keys of the agent and detector, and save them to **ca**, **agent**, and **server** in the **root** directory of the project, respectively. In addition, you need to save the key encryption password to **pwf** of the certificate, and set the permission to **600** to prevent other users from performing read and write operations. You can also use the script in the **share** directory to generate certificates and keys. ## Dependencies None --- --- url: >- /en/docs/latest/characteristic_description/aifeature_guide/anomaly_analysis_multi_metric_correlation_analysis.md --- # Anomaly\_analysis: Multi\_Metric Correlation Analysis ## Overview The Anomaly Analysis multi-metric correlation module is primarily used to analyze the Pearson correlation coefficient of time series data to identify metrics that are most strongly correlated with known anomalies. This module features a decoupled framework and supports time series databases such as Prometheus and InfluxDB. ## Usage Guide Assume the metric collection system is running properly and the configuration file directory **confpath** has been initialized. You can run the following command to use this feature: To analyze the correlation between a specific metric and other metrics within the time range from timestamps1 to timestamps2 on a specific node: ``` gs_dbmind component anomaly_analysis --conf confpath --metric metric_name --start-time timestamps1 --end-time timestamps2 --host ip_address ``` To analyze the correlation between a specific metric and other metrics from timestamps1 to timestamps2 on a specific node and save the analysis result as a CSV file: ``` gs_dbmind component anomaly_analysis --conf confpath --metric metric_name --start-time timestamps1 --end-time timestamps2 --host ip_address --csv-dump-path csv_path ``` > \[!NOTE]NOTE > Ensure that start-time is at least 30 seconds earlier than end-time when configuring anomaly\_analysis parameters. ## Obtaining Help Information You can run the **--help** command to obtain help information. For example: ``` gs_dbmind component anomaly_detection --help ``` The following information will be displayed: ``` usage: anomaly_analysis.py [-h] -c CONF -m METRIC -s START_TIME -e END_TIME -H HOST [--csv-dump-path CSV_DUMP_PATH] Workload Anomaly analysis: Anomaly analysis of monitored metric. optional arguments: -h, --help show this help message and exit -c CONF, --conf CONF set the directory of configuration files -m METRIC, --metric METRIC set the metric name you want to retrieve -s START_TIME, --start-time START_TIME set the start time of for retrieving in ms, supporting UNIX-timestamp with microsecond or datetime format -e END_TIME, --end-time END_TIME set the end time of for retrieving in ms, supporting UNIX-timestamp with microsecond or datetime format -H HOST, --host HOST set a host of the metric, ip only or ip and port. --csv-dump-path CSV_DUMP_PATH dump the result csv file to the dump path if it is specified. ``` \*\* ## Command Reference **Table 1** Command Line Parameters ## Troubleshooting * If the analysis scenario fails, check that the configuration file path is correct and the configuration information is complete. Also, verify that the metric name and host address are accurate, and ensure that the metric data is available for the specified start and end times. --- --- url: >- /en/docs/latest-lite/sql_reference/anonymous_block_supporting_autonomous_transaction.md --- # Anonymous Block Supporting Autonomous Transaction An autonomous transaction can be defined in an anonymous block. The identifier of an autonomous transaction is **PRAGMA AUTONOMOUS\_TRANSACTION**. The syntax of an autonomous transaction is the same as that of creating an anonymous block. The following is an example. ``` create table t1(a int ,b text); START TRANSACTION; DECLARE PRAGMA AUTONOMOUS_TRANSACTION; BEGIN insert into t1 values(1,'you are so cute,will commit!'); END; / insert into t1 values(1,'you will rollback!'); rollback; select * from t1; ``` In the preceding example, an anonymous block containing an autonomous transaction is finally executed before a transaction block to be rolled back, which directly illustrates a characteristic of the autonomous transaction, that is, rollback of the primary transaction does not affect content that has been committed by the autonomous transaction. --- --- url: >- /en/docs/latest/sql_reference/anonymous_block_supporting_autonomous_transaction.md --- # Anonymous Block Supporting Autonomous Transaction An autonomous transaction can be defined in an anonymous block. The identifier of an autonomous transaction is **PRAGMA AUTONOMOUS\_TRANSACTION**. The syntax of an autonomous transaction is the same as that of creating an anonymous block. The following is an example. ``` create table t1(a int ,b text); START TRANSACTION; DECLARE PRAGMA AUTONOMOUS_TRANSACTION; BEGIN insert into t1 values(1,'you are so cute,will commit!'); END; / insert into t1 values(1,'you will rollback!'); rollback; select * from t1; ``` In the preceding example, an anonymous block containing an autonomous transaction is finally executed before a transaction block to be rolled back, which directly illustrates a characteristic of the autonomous transaction, that is, rollback of the primary transaction does not affect content that has been committed by the autonomous transaction. --- --- url: /en/docs/latest-lite/brief_tutorial/anonymous_blocks.md --- # Anonymous Blocks An anonymous block is one of the character blocks of a stored procedure and has no name. It is generally used for scripts or activities that are not executed frequently. ## Syntax [Figure 1](#en-us_topic_0283137481_en-us_topic_0237122218_en-us_topic_0059779171_f19ed9f384e0646f29744951d7eec8c3b) shows the syntax diagram for an anonymous block. **Figure 1** anonymous\_block::=\ ![](figures/anonymous_block.png) Details about the syntax diagram are as follows: * The execution section of an anonymous block starts with a BEGIN statement, has a break with an END statement, and ends with a semicolon (;). Type a slash (/) and press **Enter** to execute the statement. > \[!TIP]NOTICE > The terminator "/" must be written in an independent row. * The declaration section includes the variable definition, type, and cursor definition. * A simplest anonymous block does not execute any commands. At least one statement, even a NULL statement, must be presented in any implementation blocks. ## Parameter Description * **DECLARE** Specifies an optional keyword used to begin a DECLARE statement. This keyword can be used to declare a data type, variable, or cursor. The use of this keyword depends on the context in which the block is located. * **declaration\_statements** Specifies the declaration of a data type, variable, cursor, exception, or procedure whose scope is limited to the block. Each declaration must be terminated with a semicolon (;). * **BEGIN** Specifies the mandatory keyword for introducing an executable section. The section can contain one or more SQL or PL/SQL statements. A BEGIN-END block can contain nested BEGIN-END blocks. * **execution\_statements** Specifies PL/SQL or SQL statements. Each statement must be terminated with a semicolon (;). * **END** Specifies the required keyword for ending a block. ## Examples ``` -- Create a null statement block. openGauss=# BEGIN NULL; END; / -- Create a demonstration table. openGauss=# CREATE TABLE table1(id1 INT, id2 INT, id3 INT); CREATE TABLE -- Use an anonymous block to insert data. openGauss=# BEGIN insert into table1 values(1,2,3); END; / ANONYMOUS BLOCK EXECUTE -- Query the inserted data. openGauss=# select * from table1; id1 | id2 | id3 -----+-----+----- 1 | 2 | 3 (1 rows) ``` --- --- url: /en/docs/latest-lite/sql_reference/anonymous_blocks.md --- # Anonymous Blocks An anonymous block applies to a script infrequently executed or a one-off activity. An anonymous block is executed in a session and is not stored. ## Syntax [Figure 1](#en-us_topic_0283137481_en-us_topic_0237122218_en-us_topic_0059779171_f19ed9f384e0646f29744951d7eec8c3b) shows the syntax diagrams for an anonymous block. **Figure 1** anonymous\_block::=\ ![](figures/anonymous_block.png "anonymous_block") Details about the syntax diagram are as follows: * The execute part of an anonymous block starts with a **BEGIN** statement, has a break with an **END** statement, and ends with a semicolon (;). Type a slash (/) and press **Enter** to execute the statement. > \[!TIP]NOTICE > The terminator "/" must be written in an independent row. * The declaration section includes the variable definition, type, and cursor definition. * A simplest anonymous block does not execute any commands. At least one statement, even a **NULL** statement, must be presented in any implementation blocks. --- --- url: /en/docs/latest-lite/sql_reference/anonymous_blocks_1.md --- # Anonymous Blocks An anonymous block is one of the character blocks of a stored procedure and has no name. It is generally used for scripts or activities that are not executed frequently. ## Syntax [Figure 1](#en-us_topic_0283137481_en-us_topic_0237122218_en-us_topic_0059779171_f19ed9f384e0646f29744951d7eec8c3b) shows the syntax diagram for an anonymous block. **Figure 1** anonymous\_block::=\ ![](figures/anonymous_block.png "anonymous_block") Details about the syntax diagram are as follows: * The execution section of an anonymous block starts with a BEGIN statement, has a break with an END statement, and ends with a semicolon (;). Type a slash (/) and press **Enter** to execute the statement. > \[!TIP]NOTICE > The terminator "/" must be written in an independent row. * The declaration section includes the variable definition, type, and cursor definition. * A simplest anonymous block does not execute any commands. At least one statement, even a NULL statement, must be presented in any implementation blocks. ## Parameter Description * **DECLARE** Specifies an optional keyword used to begin a DECLARE statement. This keyword can be used to declare a data type, variable, or cursor. The use of this keyword depends on the context in which the block is located. * **declaration\_statements** Specifies the declaration of a data type, variable, cursor, exception, or procedure whose scope is limited to the block. Each declaration must be terminated with a semicolon (;). * **BEGIN** Specifies the mandatory keyword for introducing an executable section. The section can contain one or more SQL or PL/SQL statements. A BEGIN-END block can contain nested BEGIN-END blocks. * **execution\_statements** Specifies PL/SQL or SQL statements. Each statement must be terminated with a semicolon (;). * **END** Specifies the required keyword for ending a block. ## Examples ``` -- Create a null statement block. openGauss=# BEGIN NULL; END; / -- Create a demonstration table. openGauss=# CREATE TABLE table1(id1 INT, id2 INT, id3 INT); CREATE TABLE -- Use an anonymous block to insert data. openGauss=# BEGIN insert into table1 values(1,2,3); END; / ANONYMOUS BLOCK EXECUTE -- Query the inserted data. openGauss=# select * from table1; id1 | id2 | id3 -----+-----+----- 1 | 2 | 3 (1 rows) ``` --- --- url: /en/docs/latest/sql_reference/anonymous_block_stored_procedure.md --- # Anonymous Blocks An anonymous block applies to a script infrequently executed or a one-off activity. An anonymous block is executed in a session and is not stored. ## Syntax [Figure 1](#en-us_topic_0237122218_en-us_topic_0059779171_f19ed9f384e0646f29744951d7eec8c3b) shows the syntax diagrams for an anonymous block. **Figure 1** anonymous\_block::=\ ![](figures/anonymous_block.png "anonymous_block") Details about the syntax diagram are as follows: * The execute part of an anonymous block starts with a **BEGIN** statement, has a break with an **END** statement, and ends with a semicolon (;). Type a slash (/) and press **Enter** to execute the statement. > \[!TIP]NOTICE\ > The terminator "/" must be written in an independent row. * The declaration section includes the variable definition, type, and cursor definition. * A simplest anonymous block does not execute any commands. At least one statement, even a **NULL** statement, must be presented in any implementation blocks. --- --- url: /en/docs/latest/sql_reference/brief_tutorial/anonymous_blocks.md --- # Anonymous Blocks An anonymous block is one of the character blocks of a stored procedure and has no name. It is generally used for scripts or activities that are not executed frequently. ## Syntax [Figure 1](#en-us_topic_0283137481_en-us_topic_0237122218_en-us_topic_0059779171_f19ed9f384e0646f29744951d7eec8c3b) shows the syntax diagram for an anonymous block. **Figure 1** anonymous\_block::=\ ![](figures/anonymous_block.png "anonymous_block") Details about the syntax diagram are as follows: * The execution section of an anonymous block starts with a BEGIN statement, has a break with an END statement, and ends with a semicolon (;). Type a slash (/) and press **Enter** to execute the statement. > \[!TIP]NOTICE > The terminator "/" must be written in an independent row. * The declaration section includes the variable definition, type, and cursor definition. * A simplest anonymous block does not execute any commands. At least one statement, even a NULL statement, must be presented in any implementation blocks. ## Parameter Description * **DECLARE** Specifies an optional keyword used to begin a DECLARE statement. This keyword can be used to declare a data type, variable, or cursor. The use of this keyword depends on the context in which the block is located. * **declaration\_statements** Specifies the declaration of a data type, variable, cursor, exception, or procedure whose scope is limited to the block. Each declaration must be terminated with a semicolon (;). * **BEGIN** Specifies the mandatory keyword for introducing an executable section. The section can contain one or more SQL or PL/SQL statements. A BEGIN-END block can contain nested BEGIN-END blocks. * **execution\_statements** Specifies PL/SQL or SQL statements. Each statement must be terminated with a semicolon (;). * **END** Specifies the required keyword for ending a block. ## Examples ``` -- Create a null statement block. openGauss=# BEGIN NULL; END; / -- Create a demonstration table. openGauss=# CREATE TABLE table1(id1 INT, id2 INT, id3 INT); CREATE TABLE -- Use an anonymous block to insert data. openGauss=# BEGIN insert into table1 values(1,2,3); END; / ANONYMOUS BLOCK EXECUTE -- Query the inserted data. openGauss=# select * from table1; id1 | id2 | id3 -----+-----+----- 1 | 2 | 3 (1 rows) ``` --- --- url: /zh/docs/latest-lite/sql_reference/anydata_type.md --- # ANYDATA类型 ANYTYPE、ANYDATA 和 ANYDATASET 是用于处理不确定数据类型的一组类型,包含类型的实际数据,以及对该类型的描述,可以用于动态地处理各种数据类型。 ## 规格描述 1. ANYTYPE、ANYDATA 和 ANYDATASET 类型可处理的普通数据类型范围限定在binary\_double、blob、char、date、nchar、number、nvarchar2、raw、timestamp、timestamptz、varchar、varchar2,共12种类型内。 2. 对于以上12种对应类型的CONVERT方法构建的ANYDATA、ANYDATASET,类型描述部分即ANYTYPE属性为NULL,详见下述GETTYPE存储过程。 3. 三种类型均创建于public shcema下,类型所包含的存储过程需通过类型名.存储过程名进行调用,包含self参数的存储过程也可通过对象名.存储过程名的方式调用,仅有self参数的存储过程使用时不可省略括号。使用方式与面向对象语法类似,详见下述对应类型的SQL语句示例。 ## ANYTYPE ANYTYPE类型可存储其他类型的类型描述,如类型名、数值类型的精度、字符串类型的长度等。 ### 存储过程 #### BEGINCREATE ```sql STATIC PROCEDURE BEGINCREATE( typecode IN INTEGER, atype OUT ANYTYPE); ``` 创建一个新的 ANYTYPE 实例,用于创建类型描述。 |参数|类型|说明| |--|--|--| |typecode|int|入参,整数代表对应类型| |atype|anytype|出参,初始化的anytype| 这里给出以上12种类型对应的typecode |typecode|类型| |--|--| |101|binary\_double| |113|blob| |96|char| |12|date| |286|nchar| |2|number| |287|nvarchar2| |95|raw| |187|timestamp| |188|timestamptz| |1|varchar| |9|varchar2| #### SETINFO ```sql MEMBER PROCEDURE SETINFO( self IN OUT NOCOPY ANYTYPE, prec IN INTEGER, scale IN INTEGER, len IN INTEGER, csid IN INTEGER, csfrm IN INTEGER, atype IN ANYTYPE DEFAULT NULL, elem_tc IN INTEGER DEFAULT NULL, elem_count IN INTEGER DEFAULT 0); ``` 设置ANTYPE的各属性。 |参数|类型|说明| |--|--|--| |self|ANYTYPE|self| |prec|int|数字类型精度| |scale|int|数字类型刻度,与精度一起使用| |len|int|字符串类型长度| |csid|int|字符集id| |csfrm|int|字符格式| |atype|ANYTYPE|object类型入参,未使用| |elem\_tc|int|collection类型的typecode,未使用| |elem\_count|int|table或数组类型的长度,未使用| #### ENDCREATE ```sql MEMBER PROCEDURE ENDCREATE( self IN OUT NOCOPY ANYTYPE); ``` 结束创建一个ANYTYPE。在此调用后,其他SET函数不能被调用。 |参数|类型|说明| |--|--|--| |self|ANYTYPE|self| #### GETINFO ```sql MEMBER FUNCTION GETINFO ( self IN ANYTYPE, prec OUT INTEGER, scale OUT INTEGER, len OUT INTEGER, csid OUT INTEGER, csfrm OUT INTEGER, schema_name OUT VARCHAR2, type_name OUT VARCHAR2, version OUT varchar2, numelems OUT INTEGER) RETURN INTEGER; ``` 获取ANYTYPE类型中的属性值,需要在ENDCREATE后调用。 |参数|类型|说明| |--|--|--| |self|ANYTYPE|self| |prec|int|数字类型精度| |scale|int|数字类型刻度,与精度一起使用| |len|int|字符串类型长度| |csid|int|字符集id| |csfrm|int|字符格式| |schema\_name|varchar|类型所在schema| |type\_name|varchar|类型名| |version|varchar|类型的版本| |numelems|int|数组类型的元素数量,object类型的属性数量| 返回值:type\_name对应的typecode ### 示例 ```sql declare v_anytype anytype; prec int; scale int; len int; csid int; csfrm int; schema_name VARCHAR2(20); type_name VARCHAR2(20); version varchar2(20); numelems int; result int; begin anytype.BeginCreate(101, v_anytype); v_anytype.setinfo(255, 127, 2147483647, 65535, 33); anytype.endcreate(v_anytype); result := v_anytype.getinfo(prec,scale,len,csid,csfrm,schema_name,type_name,version,numelems); RAISE NOTICE 'Output values are: %, %, %, %, %, %', prec, scale, len, csid, csfrm, schema_name; RAISE NOTICE 'More output values are: %, %, %, %', type_name, version, numelems, result; end; / NOTICE: Output values are: , , , , , NOTICE: More output values are: , , , 101 ANONYMOUS BLOCK EXECUTE ``` ## ANYDATA ANYDATA用于处理不确定类型数据,包含类型的实际数据,以及对该类型的描述。其类型描述部分可以看作一个ANYTYPE。 ### 存储过程 #### CONVERT ```sql STATIC FUNCTION ConvertBDouble(dbl IN BINARY_DOUBLE) return ANYDATA; STATIC FUNCTION ConvertBlob(b IN BLOB) RETURN ANYDATA; STATIC FUNCTION ConvertChar(c IN CHAR) RETURN ANYDATA; STATIC FUNCTION ConvertDate(dat IN DATE) RETURN ANYDATA; STATIC FUNCTION ConvertNchar(nc IN NCHAR) return ANYDATA; STATIC FUNCTION ConvertNVarchar2(nc IN NVARCHAR2) return ANYDATA; STATIC FUNCTION ConvertNumber(num IN NUMBER) RETURN ANYDATA; STATIC FUNCTION ConvertRaw(r IN RAW) RETURN ANYDATA; STATIC FUNCTION ConvertTimestamp(ts IN TIMESTAMP) return ANYDATA; STATIC FUNCTION ConvertTimestampTZ(ts IN TIMESTAMP WITH TIMEZONE) return ANYDATA; STATIC FUNCTION ConvertVarchar(c IN VARCHAR) RETURN ANYDATA; STATIC FUNCTION ConvertVarchar2(c IN VARCHAR2) RETURN ANYDATA; ``` 创建一个新的ANYDATA实例。对于以上12种CONVERT方法构建的ANYDATA,类型描述部分即ANYTYPE属性为NULL。 |参数|类型|说明| |--|--|--| |-|-|12种类型对应的入参| 返回值:ANYDATA #### ACCESS ```sql MEMBER FUNCTION AccessBDouble(self IN ANYDATA) return BINARY_DOUBLE; MEMBER FUNCTION AccessBlob(self IN ANYDATA) return BLOB; MEMBER FUNCTION AccessChar(self IN ANYDATA) return CHAR; MEMBER FUNCTION AccessDate(self IN ANYDATA) return DATE; MEMBER FUNCTION AccessNchar(self IN ANYDATA) return NCHAR; MEMBER FUNCTION AccessNumber(self IN ANYDATA) return NUMBER; MEMBER FUNCTION AccessNVarchar2(self IN ANYDATA) return NVARCHAR2; MEMBER FUNCTION AccessRaw(self IN ANYDATA) return RAW; MEMBER FUNCTION AccessTimestamp(self IN ANYDATA) return TIMESTAMP; MEMBER FUNCTION AccessTimestampTZ(self IN ANYDATA) return TIMESTAMP WITH TIMEZONE; MEMBER FUNCTION AccessVarchar(self IN ANYDATA) return VARCHAR; MEMBER FUNCTION AccessVarchar2(self IN ANYDATA) return VARCHAR2; ``` 返回ANYDATA中的数据。首先需要与ANYDATA中存储的数据类型匹配,若不匹配,返回NULL。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| 返回值:12种对应类型 #### GETTYPE ```sql MEMBER FUNCTION GETTYPE( self IN ANYDATA, typ OUT NOCOPY AnyType) RETURN INTEGER; ``` 将ANYDATA的类型描述,即ANYTYPE部分赋给出参typ,并返回对应的类型的typecode。在限定的12种类型下,获取的typ均为NULL,typcode为实际类型。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| |typ|AnyType|类型信息| 返回值:类型对应的typecode #### GETTYPENAME ```sql MEMBER FUNCTION GETTYPENAME( self IN ANYDATA) RETURN VARCHAR2; ``` 返回ANYDATA中存储的数据类型名称。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| 返回值:类型名 ### 示例 ```sql declare v_anydata anydata; typecode int; v_char nchar(10); type_name VARCHAR2(20); begin v_anydata := anydata.convertnchar('abc123,?'); v_char := v_anydata.accessnchar(); typecode = v_anydata.gettype(); type_name = v_anydata.gettypename(); raise notice '%, %, %', v_char, type_name, typecode; end; / NOTICE: abc123,? , NChar, 286 ANONYMOUS BLOCK EXECUTE ``` ## ANYDATASET ANYDATASET用于处理一组不确定类型数据,可看作ANYDATA的集合,单个集合中的类型需要相同。 ### 存储过程 #### BEGINCREATE ```sql STATIC PROCEDURE BeginCreate( typecode IN INTEGER, rtype IN OUT NOCOPY AnyType, aset OUT NOCOPY ANYDATASET); ``` 函数接收typecode确定集合中元素的类型,创建一个新的ANYDATASET实例。此处的typecode对应关系与ANYTYPE相同。 |参数|类型|说明| |--|--|--| |typecode|int|集合类型的typecode| |rtype|AnyType|集合类型的类型属性| |aset|ANYDATASET|出参,初始化函数的返回值| |typecode|类型| |--|--| |101|binary\_double| |113|blob| |96|char| |12|date| |286|nchar| |2|number| |287|nvarchar2| |95|raw| |187|timestamp| |188|timestamptz| |1|varchar| |9|varchar2| #### ADDINSTANCE ```sql MEMBER PROCEDURE AddInstance( self IN OUT NOCOPY ANYDATASET); ``` 在ANYDATASET中创建一个新的数据元素,每次新增元素时均需要调用该存储过程。 |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| #### SET ```sql MEMBER PROCEDURE SETBDOUBLE( self IN OUT NOCOPY ANYDATASET, dbl IN BINARY_DOUBLE, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETBLOB( self IN OUT NOCOPY ANYDATASET, b IN BLOB, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETCHAR( self IN OUT NOCOPY ANYDATASET, c IN CHAR, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETDATE( self IN OUT NOCOPY ANYDATASET, dat IN DATE, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETNCHAR( self IN OUT NOCOPY ANYDATASET, nc IN NCHAR, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETNUMBER( self IN OUT NOCOPY ANYDATASET, num IN NUMBER, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETNVARCHAR2( self IN OUT NOCOPY ANYDATASET, nc IN NVarchar2, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETRAW( self IN OUT NOCOPY ANYDATASET, r IN RAW, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETTIMESTAMP( self IN OUT NOCOPY ANYDATASET, ts IN TIMESTAMP, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETTIMESTAMPTZ( self IN OUT NOCOPY ANYDATASET, ts IN TIMESTAMP WITH TIME ZONE, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETVARCHAR( self IN OUT NOCOPY ANYDATASET, c IN VARCHAR, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETVARCHAR2( self IN OUT NOCOPY ANYDATASET, c IN VARCHAR2, last_elem BOOLEAN DEFAULT FALSE); ``` 为ANYDATASET中的单个数据元素实例设定值,在ADDINSTANSE后调用,需要和ANYDATASET创建时指定的类型一致。其他调用顺序将有以下表现: * 进行过ADDINSTANSE但未设定值,正常调用SET赋值 * BEGINCREATE后未进行ADDINSTANSE,调用SET报错。 * 前向数据实例均已设定值,此时调用SET,覆盖最后一个数据实例。 |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| |-|-|12种对应类型参数| |last\_elem|BOOLEAN|是否是集合类型的最后一个元素,未使用| #### ENDCREATE ```sql MEMBER PROCEDURE ENDCREATE( self IN OUT NOCOPY ANYDATASET); ``` 结束ANYDATASET构建。ANYDATASET允许BEGINCREATE之后直接ENDCREATE,也就是空集。若有未设定值的元素,即ADDINSTANSE后未调用对应的SET,将报错。 |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| #### GET ```sql MEMBER FUNCTION GETBDOUBLE( self IN ANYDATASET, index IN int, dbl OUT NOCOPY BINARY_DOUBLE) RETURN INTEGER; MEMBER FUNCTION GETBLOB( self IN ANYDATASET, index IN int, b OUT NOCOPY BLOB) RETURN INTEGER; MEMBER FUNCTION GETCHAR( self IN ANYDATASET, index IN int, c OUT NOCOPY CHAR) RETURN INTEGER; MEMBER FUNCTION GETDATE( self IN ANYDATASET, index IN int, dat OUT NOCOPY DATE) RETURN INTEGER; MEMBER FUNCTION GETNCHAR( self IN ANYDATASET, index IN int, nc OUT NOCOPY NCHAR) RETURN INTEGER; MEMBER FUNCTION GETNUMBER( self IN ANYDATASET, index IN int, num OUT NOCOPY NUMBER) RETURN INTEGER; MEMBER FUNCTION GETNVARCHAR2( self IN ANYDATASET, index IN int, nc OUT NOCOPY NVARCHAR2) RETURN INTEGER; MEMBER FUNCTION GETRAW( self IN ANYDATASET, index IN int, r OUT NOCOPY RAW) RETURN INTEGER; MEMBER FUNCTION GETTIMESTAMP( self IN ANYDATASET, index IN int, ts OUT NOCOPY TIMESTAMP) RETURN INTEGER; MEMBER FUNCTION GETTIMESTAMPTZ( self IN ANYDATASET, index IN int, ts OUT NOCOPY TIMESTAMP WITH TIME ZONE) RETURN INTEGER, MEMBER FUNCTION GETVARCHAR( self IN ANYDATASET, index IN int, c OUT NOCOPY VARCHAR) RETURN INTEGER; MEMBER FUNCTION GETVARCHAR2( self IN ANYDATASET, index IN int, c OUT NOCOPY VARCHAR2) RETURN INTEGER; ``` 根据index返回ANYDATASET中的元素 |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| |index|int|需要取的元素下标| |--|--|12种对应类型出参| 返回值:SUCCESS(0) #### GETCOUNT ```sql MEMBER FUNCTION GetCount( self IN ANYDATASET) RETURN INTEGER; ``` |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| 返回值:ANYDATASET中元素的个数 #### GETTYPE ```sql MEMBER FUNCTION GETTYPE( self IN ANYDATASET, typ OUT NOCOPY AnyType) RETURN INTEGER; ``` 将ANYDATASET的类型描述,即ANYTYPE部分赋给出参typ,并返回对应的类型的typecode。在限定的12种类型下,获取的typ均为NULL,typcode为实际类型。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| |typ|AnyType|类型信息| 返回值:类型对应的typecode #### GETTYPENAME ```sql MEMBER FUNCTION GETTYPENAME( self IN ANYDATASET) RETURN VARCHAR2; ``` 返回ANYDATA中存储的数据类型名称。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| 返回值:类型名 ### 示例 ```sql declare v_anytype anytype; v_anydataset anydataset; v_string float8; v_type int; v_typname varchar2; v_count int; v_typecode int; begin anydataset.BeginCreate(1, v_anytype, v_anydataset); RAISE notice '%, %', array_length(v_anydataset.data, 1), v_anydataset.count; v_anydataset.addInstance(); v_anydataset.SETvarchar('100.80'); v_anydataset.addInstance(); v_anydataset.SETvarchar('0.90'); anydataset.EndCreate(v_anydataset); RAISE notice '%, %', array_length(v_anydataset.data, 1), v_anydataset.count; v_typname = v_anydataset.GetTypename(); v_count = v_anydataset.GetCount(); v_typecode = v_anydataset.GetType(); RAISE notice 'name %, count %, type %', v_typname, v_count, v_typecode; v_type := v_anydataset.getvarchar(v_string,1); raise notice '%, %', v_string, v_type; v_type := v_anydataset.getvarchar(v_string,2); raise notice '%, %', v_string, v_type; v_type := v_anydataset.getvarchar(v_string,3); raise notice '%, %', v_string, v_type; end; / NOTICE: 0, 0 NOTICE: 2, 2 NOTICE: name Varchar, count 2, type 1 NOTICE: , 0 NOTICE: , 0 NOTICE: , 0 ANONYMOUS BLOCK EXECUTE ``` --- --- url: /zh/docs/latest/sql_reference/anydata_type.md --- # ANYDATA类型 ANYTYPE、ANYDATA 和 ANYDATASET 是用于处理不确定数据类型的一组类型,包含类型的实际数据,以及对该类型的描述,可以用于动态地处理各种数据类型。 ## 规格描述 1. ANYTYPE、ANYDATA 和 ANYDATASET 类型可处理的普通数据类型范围限定在binary\_double、blob、char、date、nchar、number、nvarchar2、raw、timestamp、timestamptz、varchar、varchar2,共12种类型内。 2. 对于以上12种对应类型的CONVERT方法构建的ANYDATA、ANYDATASET,类型描述部分即ANYTYPE属性为NULL,详见下述GETTYPE存储过程。 3. 三种类型均创建于public shcema下,类型所包含的存储过程需通过类型名.存储过程名进行调用,包含self参数的存储过程也可通过对象名.存储过程名的方式调用,仅有self参数的存储过程使用时不可省略括号。使用方式与面向对象语法类似,详见下述对应类型的SQL语句示例。 ## ANYTYPE ANYTYPE类型可存储其他类型的类型描述,如类型名、数值类型的精度、字符串类型的长度等。 ### 存储过程 #### BEGINCREATE ```sql STATIC PROCEDURE BEGINCREATE( typecode IN INTEGER, atype OUT ANYTYPE); ``` 创建一个新的 ANYTYPE 实例,用于创建类型描述。 |参数|类型|说明| |--|--|--| |typecode|int|入参,整数代表对应类型| |atype|anytype|出参,初始化的anytype| 这里给出以上12种类型对应的typecode |typecode|类型| |--|--| |101|binary\_double| |113|blob| |96|char| |12|date| |286|nchar| |2|number| |287|nvarchar2| |95|raw| |187|timestamp| |188|timestamptz| |1|varchar| |9|varchar2| #### SETINFO ```sql MEMBER PROCEDURE SETINFO( self IN OUT NOCOPY ANYTYPE, prec IN INTEGER, scale IN INTEGER, len IN INTEGER, csid IN INTEGER, csfrm IN INTEGER, atype IN ANYTYPE DEFAULT NULL, elem_tc IN INTEGER DEFAULT NULL, elem_count IN INTEGER DEFAULT 0); ``` 设置ANTYPE的各属性。 |参数|类型|说明| |--|--|--| |self|ANYTYPE|self| |prec|int|数字类型精度| |scale|int|数字类型刻度,与精度一起使用| |len|int|字符串类型长度| |csid|int|字符集id| |csfrm|int|字符格式| |atype|ANYTYPE|object类型入参,未使用| |elem\_tc|int|collection类型的typecode,未使用| |elem\_count|int|table或数组类型的长度,未使用| #### ENDCREATE ```sql MEMBER PROCEDURE ENDCREATE( self IN OUT NOCOPY ANYTYPE); ``` 结束创建一个ANYTYPE。在此调用后,其他SET函数不能被调用。 |参数|类型|说明| |--|--|--| |self|ANYTYPE|self| #### GETINFO ```sql MEMBER FUNCTION GETINFO ( self IN ANYTYPE, prec OUT INTEGER, scale OUT INTEGER, len OUT INTEGER, csid OUT INTEGER, csfrm OUT INTEGER, schema_name OUT VARCHAR2, type_name OUT VARCHAR2, version OUT varchar2, numelems OUT INTEGER) RETURN INTEGER; ``` 获取ANYTYPE类型中的属性值,需要在ENDCREATE后调用。 |参数|类型|说明| |--|--|--| |self|ANYTYPE|self| |prec|int|数字类型精度| |scale|int|数字类型刻度,与精度一起使用| |len|int|字符串类型长度| |csid|int|字符集id| |csfrm|int|字符格式| |schema\_name|varchar|类型所在schema| |type\_name|varchar|类型名| |version|varchar|类型的版本| |numelems|int|数组类型的元素数量,object类型的属性数量| 返回值:type\_name对应的typecode ### 示例 ```sql declare v_anytype anytype; prec int; scale int; len int; csid int; csfrm int; schema_name VARCHAR2(20); type_name VARCHAR2(20); version varchar2(20); numelems int; result int; begin anytype.BeginCreate(101, v_anytype); v_anytype.setinfo(255, 127, 2147483647, 65535, 33); anytype.endcreate(v_anytype); result := v_anytype.getinfo(prec,scale,len,csid,csfrm,schema_name,type_name,version,numelems); RAISE NOTICE 'Output values are: %, %, %, %, %, %', prec, scale, len, csid, csfrm, schema_name; RAISE NOTICE 'More output values are: %, %, %, %', type_name, version, numelems, result; end; / NOTICE: Output values are: , , , , , NOTICE: More output values are: , , , 101 ANONYMOUS BLOCK EXECUTE ``` ## ANYDATA ANYDATA用于处理不确定类型数据,包含类型的实际数据,以及对该类型的描述。其类型描述部分可以看作一个ANYTYPE。 ### 存储过程 #### CONVERT ```sql STATIC FUNCTION ConvertBDouble(dbl IN BINARY_DOUBLE) return ANYDATA; STATIC FUNCTION ConvertBlob(b IN BLOB) RETURN ANYDATA; STATIC FUNCTION ConvertChar(c IN CHAR) RETURN ANYDATA; STATIC FUNCTION ConvertDate(dat IN DATE) RETURN ANYDATA; STATIC FUNCTION ConvertNchar(nc IN NCHAR) return ANYDATA; STATIC FUNCTION ConvertNVarchar2(nc IN NVARCHAR2) return ANYDATA; STATIC FUNCTION ConvertNumber(num IN NUMBER) RETURN ANYDATA; STATIC FUNCTION ConvertRaw(r IN RAW) RETURN ANYDATA; STATIC FUNCTION ConvertTimestamp(ts IN TIMESTAMP) return ANYDATA; STATIC FUNCTION ConvertTimestampTZ(ts IN TIMESTAMP WITH TIMEZONE) return ANYDATA; STATIC FUNCTION ConvertVarchar(c IN VARCHAR) RETURN ANYDATA; STATIC FUNCTION ConvertVarchar2(c IN VARCHAR2) RETURN ANYDATA; ``` 创建一个新的ANYDATA实例。对于以上12种CONVERT方法构建的ANYDATA,类型描述部分即ANYTYPE属性为NULL。 |参数|类型|说明| |--|--|--| |-|-|12种类型对应的入参| 返回值:ANYDATA #### ACCESS ```sql MEMBER FUNCTION AccessBDouble(self IN ANYDATA) return BINARY_DOUBLE; MEMBER FUNCTION AccessBlob(self IN ANYDATA) return BLOB; MEMBER FUNCTION AccessChar(self IN ANYDATA) return CHAR; MEMBER FUNCTION AccessDate(self IN ANYDATA) return DATE; MEMBER FUNCTION AccessNchar(self IN ANYDATA) return NCHAR; MEMBER FUNCTION AccessNumber(self IN ANYDATA) return NUMBER; MEMBER FUNCTION AccessNVarchar2(self IN ANYDATA) return NVARCHAR2; MEMBER FUNCTION AccessRaw(self IN ANYDATA) return RAW; MEMBER FUNCTION AccessTimestamp(self IN ANYDATA) return TIMESTAMP; MEMBER FUNCTION AccessTimestampTZ(self IN ANYDATA) return TIMESTAMP WITH TIMEZONE; MEMBER FUNCTION AccessVarchar(self IN ANYDATA) return VARCHAR; MEMBER FUNCTION AccessVarchar2(self IN ANYDATA) return VARCHAR2; ``` 返回ANYDATA中的数据。首先需要与ANYDATA中存储的数据类型匹配,若不匹配,返回NULL。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| 返回值:12种对应类型 #### GETTYPE ```sql MEMBER FUNCTION GETTYPE( self IN ANYDATA, typ OUT NOCOPY AnyType) RETURN INTEGER; ``` 将ANYDATA的类型描述,即ANYTYPE部分赋给出参typ,并返回对应的类型的typecode。在限定的12种类型下,获取的typ均为NULL,typcode为实际类型。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| |typ|AnyType|类型信息| 返回值:类型对应的typecode #### GETTYPENAME ```sql MEMBER FUNCTION GETTYPENAME( self IN ANYDATA) RETURN VARCHAR2; ``` 返回ANYDATA中存储的数据类型名称。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| 返回值:类型名 ### 示例 ```sql declare v_anydata anydata; typecode int; v_char nchar(10); type_name VARCHAR2(20); begin v_anydata := anydata.convertnchar('abc123,?'); v_char := v_anydata.accessnchar(); typecode = v_anydata.gettype(); type_name = v_anydata.gettypename(); raise notice '%, %, %', v_char, type_name, typecode; end; / NOTICE: abc123,? , NChar, 286 ANONYMOUS BLOCK EXECUTE ``` ## ANYDATASET ANYDATASET用于处理一组不确定类型数据,可看作ANYDATA的集合,单个集合中的类型需要相同。 ### 存储过程 #### BEGINCREATE ```sql STATIC PROCEDURE BeginCreate( typecode IN INTEGER, rtype IN OUT NOCOPY AnyType, aset OUT NOCOPY ANYDATASET); ``` 函数接收typecode确定集合中元素的类型,创建一个新的ANYDATASET实例。此处的typecode对应关系与ANYTYPE相同。 |参数|类型|说明| |--|--|--| |typecode|int|集合类型的typecode| |rtype|AnyType|集合类型的类型属性| |aset|ANYDATASET|出参,初始化函数的返回值| |typecode|类型| |--|--| |101|binary\_double| |113|blob| |96|char| |12|date| |286|nchar| |2|number| |287|nvarchar2| |95|raw| |187|timestamp| |188|timestamptz| |1|varchar| |9|varchar2| #### ADDINSTANCE ```sql MEMBER PROCEDURE AddInstance( self IN OUT NOCOPY ANYDATASET); ``` 在ANYDATASET中创建一个新的数据元素,每次新增元素时均需要调用该存储过程。 |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| #### SET ```sql MEMBER PROCEDURE SETBDOUBLE( self IN OUT NOCOPY ANYDATASET, dbl IN BINARY_DOUBLE, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETBLOB( self IN OUT NOCOPY ANYDATASET, b IN BLOB, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETCHAR( self IN OUT NOCOPY ANYDATASET, c IN CHAR, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETDATE( self IN OUT NOCOPY ANYDATASET, dat IN DATE, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETNCHAR( self IN OUT NOCOPY ANYDATASET, nc IN NCHAR, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETNUMBER( self IN OUT NOCOPY ANYDATASET, num IN NUMBER, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETNVARCHAR2( self IN OUT NOCOPY ANYDATASET, nc IN NVarchar2, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETRAW( self IN OUT NOCOPY ANYDATASET, r IN RAW, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETTIMESTAMP( self IN OUT NOCOPY ANYDATASET, ts IN TIMESTAMP, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETTIMESTAMPTZ( self IN OUT NOCOPY ANYDATASET, ts IN TIMESTAMP WITH TIME ZONE, last_elem IN BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETVARCHAR( self IN OUT NOCOPY ANYDATASET, c IN VARCHAR, last_elem BOOLEAN DEFAULT FALSE); MEMBER PROCEDURE SETVARCHAR2( self IN OUT NOCOPY ANYDATASET, c IN VARCHAR2, last_elem BOOLEAN DEFAULT FALSE); ``` 为ANYDATASET中的单个数据元素实例设定值,在ADDINSTANSE后调用,需要和ANYDATASET创建时指定的类型一致。其他调用顺序将有以下表现: * 进行过ADDINSTANSE但未设定值,正常调用SET赋值 * BEGINCREATE后未进行ADDINSTANSE,调用SET报错。 * 前向数据实例均已设定值,此时调用SET,覆盖最后一个数据实例。 |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| |-|-|12种对应类型参数| |last\_elem|BOOLEAN|是否是集合类型的最后一个元素,未使用| #### ENDCREATE ```sql MEMBER PROCEDURE ENDCREATE( self IN OUT NOCOPY ANYDATASET); ``` 结束ANYDATASET构建。ANYDATASET允许BEGINCREATE之后直接ENDCREATE,也就是空集。若有未设定值的元素,即ADDINSTANSE后未调用对应的SET,将报错。 |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| #### GET ```sql MEMBER FUNCTION GETBDOUBLE( self IN ANYDATASET, index IN int, dbl OUT NOCOPY BINARY_DOUBLE) RETURN INTEGER; MEMBER FUNCTION GETBLOB( self IN ANYDATASET, index IN int, b OUT NOCOPY BLOB) RETURN INTEGER; MEMBER FUNCTION GETCHAR( self IN ANYDATASET, index IN int, c OUT NOCOPY CHAR) RETURN INTEGER; MEMBER FUNCTION GETDATE( self IN ANYDATASET, index IN int, dat OUT NOCOPY DATE) RETURN INTEGER; MEMBER FUNCTION GETNCHAR( self IN ANYDATASET, index IN int, nc OUT NOCOPY NCHAR) RETURN INTEGER; MEMBER FUNCTION GETNUMBER( self IN ANYDATASET, index IN int, num OUT NOCOPY NUMBER) RETURN INTEGER; MEMBER FUNCTION GETNVARCHAR2( self IN ANYDATASET, index IN int, nc OUT NOCOPY NVARCHAR2) RETURN INTEGER; MEMBER FUNCTION GETRAW( self IN ANYDATASET, index IN int, r OUT NOCOPY RAW) RETURN INTEGER; MEMBER FUNCTION GETTIMESTAMP( self IN ANYDATASET, index IN int, ts OUT NOCOPY TIMESTAMP) RETURN INTEGER; MEMBER FUNCTION GETTIMESTAMPTZ( self IN ANYDATASET, index IN int, ts OUT NOCOPY TIMESTAMP WITH TIME ZONE) RETURN INTEGER, MEMBER FUNCTION GETVARCHAR( self IN ANYDATASET, index IN int, c OUT NOCOPY VARCHAR) RETURN INTEGER; MEMBER FUNCTION GETVARCHAR2( self IN ANYDATASET, index IN int, c OUT NOCOPY VARCHAR2) RETURN INTEGER; ``` 根据index返回ANYDATASET中的元素 |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| |index|int|需要取的元素下标| |--|--|12种对应类型出参| 返回值:SUCCESS(0) #### GETCOUNT ```sql MEMBER FUNCTION GetCount( self IN ANYDATASET) RETURN INTEGER; ``` |参数|类型|说明| |--|--|--| |self|ANYDATASET|self| 返回值:ANYDATASET中元素的个数 #### GETTYPE ```sql MEMBER FUNCTION GETTYPE( self IN ANYDATASET, typ OUT NOCOPY AnyType) RETURN INTEGER; ``` 将ANYDATASET的类型描述,即ANYTYPE部分赋给出参typ,并返回对应的类型的typecode。在限定的12种类型下,获取的typ均为NULL,typcode为实际类型。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| |typ|AnyType|类型信息| 返回值:类型对应的typecode #### GETTYPENAME ```sql MEMBER FUNCTION GETTYPENAME( self IN ANYDATASET) RETURN VARCHAR2; ``` 返回ANYDATA中存储的数据类型名称。 |参数|类型|说明| |--|--|--| |self|ANYDATA|self| 返回值:类型名 ### 示例 ```sql declare v_anytype anytype; v_anydataset anydataset; v_string float8; v_type int; v_typname varchar2; v_count int; v_typecode int; begin anydataset.BeginCreate(1, v_anytype, v_anydataset); RAISE notice '%, %', array_length(v_anydataset.data, 1), v_anydataset.count; v_anydataset.addInstance(); v_anydataset.SETvarchar('100.80'); v_anydataset.addInstance(); v_anydataset.SETvarchar('0.90'); anydataset.EndCreate(v_anydataset); RAISE notice '%, %', array_length(v_anydataset.data, 1), v_anydataset.count; v_typname = v_anydataset.GetTypename(); v_count = v_anydataset.GetCount(); v_typecode = v_anydataset.GetType(); RAISE notice 'name %, count %, type %', v_typname, v_count, v_typecode; v_type := v_anydataset.getvarchar(v_string,1); raise notice '%, %', v_string, v_type; v_type := v_anydataset.getvarchar(v_string,2); raise notice '%, %', v_string, v_type; v_type := v_anydataset.getvarchar(v_string,3); raise notice '%, %', v_string, v_type; end; / NOTICE: 0, 0 NOTICE: 2, 2 NOTICE: name Varchar, count 2, type 1 NOTICE: , 0 NOTICE: , 0 NOTICE: , 0 ANONYMOUS BLOCK EXECUTE ``` --- --- url: /zh/docs/latest-lite/datavec/gallery_engine_age.md --- # Apache AGE (incubating) for openGauss ## 介绍 图数据库由于能够处理数据之前的复杂关系,近年来得到了广泛的应用。与传统关系型数据库不同,图数据库将数据表示为节点、边和属性。节点表示实体,边表示实体之间的关系,属性表示两者的属性。 Apache AGE是基于PostgreSQL开发的图数据库引擎,AGE的所有组件都运行在PostgreSQL事务缓存层和存储层之上,AGE实现了一个存储引擎同时处理关系型和图数据模型,用户可使用标准的ANSI SQL和图查询语言openCypher对数据进行查询。 Apache AGE在数据库内核的查询解析,查询重写,查询计划,查询执行,数据存储均有涉及,数据存储方面定义了图数据库的存储模型。openGauss在其他方面使用数据库内核的hook点,对Cypher语言进行了支持,实现了同时处理关系型和图数据的能力。 openGauss数据库使用插件的方式支持图数据库引擎,在openGauss数据库中可直接采用创建插件的方式使用Apache AGE的能力。 ## 安装 > 轻量版的openGauss镜像,已安装AGE,部署好openGauss数据库后,通过加载插件方式可直接使用图数据库能力 ### 编译安装 age源码地址: #### 方式一(同openGauss一起安装) 将age源码放到openGauss-server源码的contrib目录下,直接编译安装openGauss-server,age会自动编译安装 > 此方式适用于openGauss-server同时编译安装 #### 方式二(使用openGauss源码安装) 1. 将age源码 放到openGauss-server的源码 contrib 目录下 2. 进入 contrib/age 目录,在age的目录下执行 make install > 此方式适用于openGauss-servery已经使用源码编译安装, 并且源码及编译环境依旧保存,可以使用此方式安装age #### 安装方式三(使用PGXS安装) 1. 安装必要依赖 ``` yum install gcc glibc glib-common readline readline-devel zlib zlib-devel flex bison perl ``` > gcc 版本需要>=7.3.0 2. 需要将openGauss安装目录的bin目录配置到环境变量中 执行命令 ``` which pg_config ``` 确认pg\_config 是 openGauss 安装目录下的 pg\_config 3\. 进入age根目录 执行 ``` make install USE_PGXS=true ``` > 此方式适用于直接使用安装包安装openGauss的方式。这里不建议使用PGXS安装方式, 随着openGauss的升级,必要的头文件不会全部安装到安装目录,因此会存在编译时缺少头文件的问题,可以按照错误提示从openGauss的 头文件拷贝到openGauss安装目录include/postgresql/server/ 文件夹下 ##### 安装必要的依赖 > 前提条件:openGauss正常编译安装,并且配置到了环境变量中 在age的源码目录执行命令 ``` make install USE_PGXS=true ``` ## 快速开始 ### 连接openGauss ``` gsql -r ``` ### 创建插件 * 执行命令 ``` create extension age; ``` * 示例 ``` openGauss=# create extension age; CREATE EXTENSION ``` * 约束 openGauss安装dolphin插件后,B模式下需要使用如下方式安装AGE插件: ``` set dolphin.b_compatibility_mode=off; create extension age; set dolphin.b_compatibility_mode=on; ``` ### 设置查询空间 * 说明 AGE安装之后,会默认创建ag\_catalog的schema,AGE内置的数据类型、函数均存储在ag\_catalog下。 * 执行命令 ``` SET search_path TO ag_catalog; ``` * 示例 ``` openGauss=# SET search_path TO ag_catalog; SET ``` ### 加载插件 * 执行命令 ``` load 'age'; ``` * 示例 ``` openGauss=# load 'age'; LOAD ``` ### 创建图空间 * 执行命令 ``` SELECT create_graph('test'); ``` * 示例 ``` openGauss=# SELECT create_graph('test'); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "_ag_label_vertex_pkey" for table "_ag_label_vertex" CONTEXT: referenced column: create_graph NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "_ag_label_edge_pkey" for table "_ag_label_edge" CONTEXT: referenced column: create_graph NOTICE: graph "test" has been created CONTEXT: referenced column: create_graph create_graph -------------- (1 row) ``` ### 执行cypher语句 * 语法 ``` SELECT * FROM cypher(参数1 要查询的图空间, 参数2 cypher语句) AS (a agtype ,[返回元组的个数]); ``` * 示例 ``` openGauss=# SELECT * FROM cypher('test', $$CREATE (:v {i: 0})$$) AS (a agtype); a --- (0 rows) openGauss=# SELECT * FROM cypher('test', $$MATCH (n:v) RETURN n$$) AS (n agtype); n ----------------------------------------------------------------------- {"id": 844424930131969, "label": "v", "properties": {"i": 0}}::vertex (1 row) ``` ## 适配情况 AGE在openGauss上实现了适配,适配详情参考 [Apache AGE适配openGauss详情说明](apache_age_adaptation.md) * 更多资料 > 更详细的使用方式可以参考AGE的官方文档: ## Apache AGE回归测试语句运行 ### 执行步骤 > 前提条件:openGauss使用源码编译的方式安装 1. 将age源码放在openGauss源码的contrib目录下 2. 进入age源码目录,执行命令 ``` make installcheck ``` --- --- url: /zh/docs/latest/datavec/gallery_engine_age.md --- # Apache AGE (incubating) for openGauss ## 介绍 图数据库由于能够处理数据之前的复杂关系,近年来得到了广泛的应用。与传统关系型数据库不同,图数据库将数据表示为节点、边和属性。节点表示实体,边表示实体之间的关系,属性表示两者的属性。 Apache AGE是基于PostgreSQL开发的图数据库引擎,AGE的所有组件都运行在PostgreSQL事务缓存层和存储层之上,AGE实现了一个存储引擎同时处理关系型和图数据模型,用户可使用标准的ANSI SQL和图查询语言openCypher对数据进行查询。 Apache AGE在数据库内核的查询解析,查询重写,查询计划,查询执行,数据存储均有涉及,数据存储方面定义了图数据库的存储模型。openGauss在其他方面使用数据库内核的hook点,对Cypher语言进行了支持,实现了同时处理关系型和图数据的能力。 openGauss数据库使用插件的方式支持图数据库引擎,在openGauss数据库中可直接采用创建插件的方式使用Apache AGE的能力。 ## 安装 > 企业版的openGauss安装包,已安装AGE,部署好openGauss数据库后,通过加载插件方式可直接使用图数据库能力 ### 编译安装 age源码地址: #### 方式一(同openGauss一起安装) 将age源码放到openGauss-server源码的contrib目录下,直接编译安装openGauss-server,age会自动编译安装 > 此方式适用于openGauss-server同时编译安装 #### 方式二(使用openGauss源码安装) 1. 将age源码 放到openGauss-server的源码 contrib 目录下 2. 进入 contrib/age 目录,在age的目录下执行 make install > 此方式适用于openGauss-servery已经使用源码编译安装, 并且源码及编译环境依旧保存,可以使用此方式安装age #### 安装方式三(使用PGXS安装) 1. 安装必要依赖 ``` yum install gcc glibc glib-common readline readline-devel zlib zlib-devel flex bison perl ``` > gcc 版本需要>=7.3.0 2. 需要将openGauss安装目录的bin目录配置到环境变量中 执行命令 ``` which pg_config ``` 确认pg\_config 是 openGauss 安装目录下的 pg\_config 3. 进入age根目录 执行 ``` make install USE_PGXS=true ``` > 此方式适用于直接使用安装包安装openGauss的方式。这里不建议使用PGXS安装方式, 随着openGauss的升级,必要的头文件不会全部安装到安装目录,因此会存在编译时缺少头文件的问题,可以按照错误提示从openGauss的 头文件拷贝到openGauss安装目录include/postgresql/server/ 文件夹下。 ##### 安装必要的依赖 > 前提条件:openGauss正常编译安装,并且配置到了环境变量中 在age的源码目录执行命令。 ``` make install USE_PGXS=true ``` ## 快速开始 ### 连接openGauss ``` gsql -r ``` ### 创建插件 * 执行命令 ``` create extension age; ``` * 示例 ``` openGauss=# create extension age; CREATE EXTENSION ``` * 约束 openGauss安装dolphin插件后,B模式下需要使用如下方式安装AGE插件: ``` set dolphin.b_compatibility_mode=off; create extension age; set dolphin.b_compatibility_mode=on; ``` ### 设置查询空间 * 说明 AGE安装之后,会默认创建ag\_catalog的schema,AGE内置的数据类型、函数均存储在ag\_catalog下。 * 执行命令 ``` SET search_path TO ag_catalog; ``` * 示例 ``` openGauss=# SET search_path TO ag_catalog; SET ``` ### 加载插件 * 执行命令 ``` load 'age'; ``` * 示例 ``` openGauss=# load 'age'; LOAD ``` ### 创建图空间 * 执行命令 ``` SELECT create_graph('test'); ``` * 示例 ``` openGauss=# SELECT create_graph('test'); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "_ag_label_vertex_pkey" for table "_ag_label_vertex" CONTEXT: referenced column: create_graph NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "_ag_label_edge_pkey" for table "_ag_label_edge" CONTEXT: referenced column: create_graph NOTICE: graph "test" has been created CONTEXT: referenced column: create_graph create_graph -------------- (1 row) ``` ### 执行cypher语句 * 语法 ``` SELECT * FROM cypher(参数1 要查询的图空间, 参数2 cypher语句) AS (a agtype ,[返回元组的个数]); ``` * 示例 ``` openGauss=# SELECT * FROM cypher('test', $$CREATE (:v {i: 0})$$) AS (a agtype); a --- (0 rows) openGauss=# SELECT * FROM cypher('test', $$MATCH (n:v) RETURN n$$) AS (n agtype); n ----------------------------------------------------------------------- {"id": 844424930131969, "label": "v", "properties": {"i": 0}}::vertex (1 row) ``` ## 适配情况 AGE在openGauss上实现了适配,适配详情参考 [Apache AGE适配openGauss详情说明](apache_age_adaptation.md) * 更多资料 > 更详细的使用方式可以参考AGE的官方文档: ## Apache AGE回归测试语句运行 ### 执行步骤 > 前提条件:openGauss使用源码编译的方式安装 1. 将age源码放在openGauss源码的contrib目录下 2. 进入age源码目录,执行命令 ``` make installcheck ``` --- --- url: /zh/docs/latest-lite/datavec/apache_age_adaptation.md --- # Apache AGE (incubating) for openGauss 适配详情 ## 说明 Apache AGE通过创建插件的形式使用。 ``` create extension age; ``` AGE安装之后,会默认创建ag\_catalog的schema,AGE内置的数据类型、函数均存储在ag\_catalog下。因此在使用AGE的时候,特别是执行cypher语句时,需要先执行命令: ``` SET search_path TO ag_catalog; ``` 同时需要执行 load 'age' 命令确保age插件的全部hook被加载,保证图数据的完整性。 ``` load 'age'; ``` > \[!NOTE]说明 > 创建使用age插件前需要关闭线程池,设置enable\_thread\_pool = off ## 1. 图的操作 图由一组顶点和边组成,其中每个单独的节点和边都具有属性映射。顶点是图的基本对象,它可以独立于图中的其他任何东西而存在。边在两个顶点之间创建有向连接。 ### 1.1 创建图 创建图使用函数:create\_graph(graph\_name); ``` SELECT * FROM ag_catalog.create_graph('graph_name'); ``` ### 1.2 删除图 删除图使用函数:drop\_graph(graph\_name, cascade); > 1. 第一个参数graph\_name为要删除的图,第二个参数cascade为布尔值,表示是否删除依赖于图表的标签和数据 > 2. 建议将 cascade 选项设置为 true,否则必须使用 SQL DDL 命令手动删除图中的所有内容 ``` SELECT * FROM ag_catalog.drop_graph('graph_name', true); ``` ### 1.3 创建图中的点类型 创建图中的点类型使用函数:create\_vlabel(graph\_name, label\_name); ``` SELECT * FROM ag_catalog.create_vlabel('graph_name','label_name'); ``` 每当使用create\_vlabel()函数创建顶点标签时,会在new\_graph的命名空间new\_graph中生成一个新表"\"。用于创建边类型的create\_elabel()函数也是如此。这两个函数不是必须使用的,用Cypher语句创建顶点和边时,如果类型表不存在,会自动创建。 ### 1.4 创建图中的边类型 创建图使用函数:create\_elabel(graph\_name, label\_name); ``` SELECT * FROM ag_catalog.create_elabel('graph_name','label_name'); ``` ## 2. 图的存储 ### 2.1 图 图创建之后,内核会创建一个与图名称相同的schema。同时在ag\_catalog.ag\_graph的表中会插入一条数据,标记新创建的schema用来存储图数据。 ``` SELECT create_graph('new_graph'); NOTICE: graph "new_graph" has been created create_graph -------------- (1 row) SELECT * FROM ag_catalog.ag_graph; name | namespace -----------+----------- new_graph | new_graph (1 row) ``` ### 图中的点和边 ``` -- 创建图之后,会在该图对应的schema中创建_ag_label_vertex和_ag_label_edge两张表作为默认的点表和边表,同时会在ag_catalog.ag_label中插入两条数据将点表和边表与schema关联起来。 SELECT * FROM ag_catalog.ag_label; name | graph | id | kind | relation ------------------+-------+----+------+---------------------------- _ag_label_vertex | 68484 | 1 | v | new_graph._ag_label_vertex _ag_label_edge | 68484 | 2 | e | new_graph._ag_label_edge (2 rows) -- 创建点表 SELECT create_vlabel('new_graph', 'Person'); NOTICE: VLabel "Person" has been created create_vlabel --------------- (1 row) -- 创建点表之后,会在ag_catalog.ag_label表中插入一条数据将点表与图关联起来。kind为v代表点表kind为e代表边表 SELECT * FROM ag_catalog.ag_label; name | graph | id | kind | relation ------------------+-------+----+------+---------------------------- _ag_label_vertex | 68484 | 1 | v | new_graph._ag_label_vertex _ag_label_edge | 68484 | 2 | e | new_graph._ag_label_edge Person | 68484 | 3 | v | new_graph."Person" (3 rows) ``` ## 3. Cypher查询 Cypher语句无法在数据库中直接执行。需要通过cypher()函数构造,将Cypher语句作为cypher()函数的参数执行,cypher()函数返回一个SETOF records。 ### 3.1 cypher()函数介绍 cypher(graph\_name, query\_string, parameters) > 第一个参数graph\_name为要查询的图,第二个参数query\_string为Cypher语句,第三个参数parameters为可选参数只能与Prepared Statements一起使用。否则将抛出错误。 ``` SELECT * FROM cypher('graph_name', $$ /* Cypher Query Here */ $$) AS (result1 agtype, result2 agtype); ``` **注意事项** > 1. AS 后的 (result1 agtype, result2 agtype) 即SETOF records 需要和Cypher语句中的返回值个数相同 > 2. SELECT \* FROM cypher 不能写成 SELECT cypher > 3. 执行语句前需要执行 load 'age' 和 set search\_path = ag\_catalog ## 数据类型及函数说明 以下对AGE中包含的数据类型、Cypher语法、函数进行简要说明。 ### 1 数据类型 AGE的会创建两种数据类型: graphid 和 agtype。其中graphid代表点和边的唯一id标识符。agtype为AGE的核心数据类型,具体介绍可参考 #### 1.1 Simple DataTypes 简单数据类型包括:Null、Integer、Float、Numeric、Bool、String。 #### 1.2 Composite DataTypes 复合数据类型包括:List、Map。 * List支持以下操作 | 序号 | 功能支持 | 说明 | |:--------|:---------|--------:| | 1 |List in general | 普通list | | 2 |NULL in a List | 带null的list | | 3 |Access Individual Elements | 获取list的某个元素 | | 4 |MapElements in Lists | list元素包含map结构 | | 5 |Accessing Map Elements in Lists | 获取list元素中map的值 | | 6 |Negative Index Access | 负值索引 | | 7 |Index Ranges | 区间索引 | | 8 |Negative Index Ranges | 负值区间区间索引 | | 9 |Positive Slices | 正切片操作 | | 10 |Negative Slices | 负切片操作 | * Map支持以下操作 | 序号 | 功能支持 | 说明 | |:--------|:---------|--------:| |1 | Literal Maps with SimpleDataTypes | 普通map类型 | |2 | Literal Maps with composite Data Types | map中包含复合数据类型 | |3 | Property Access of a map | map的属性值获取操作 | |4 | Accessing List Elements in Maps | map中获取list元素操作 | #### 1.3 Simple Entities 简单实体类型包括 GraphId、Labels、Properties。又简单实体类型组成Vertex、Edge、Composite Entities。 #### 1.4 Vertex Vertex 是图的基本组成元素,代表节点。 #### 1.5 Edge Edge 是图的基本组成元素,代表边。 #### 1.6 Composite Entities 由Vertex 和 Edge组成的Path类型。 ### 2 Cypher语法 AGE对Cypher语法的支持具体介绍可参考: #### 2.1 Match | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 | get all vertices | 获取全部节点| |2 | get all vertices with a label | 获取某label类型的全部节点| |3 | related vertices | 通过边获取相关节点(邻居节点)| |4 | match with labels | 通过label过滤相关节点| |5 | Outgoing Edges |有向边支持| |6 | Directed Edges and variable | 有向边变量支持| |7 | Match on edge type |通过label type过滤边| |8 | Match on edge type and use a variable | 通过label type过滤边同时设置变量| |9 | Multiple Edges | 多条边匹配| |10 | Variable Length Edges | 变长路径匹配| #### 2.2 With | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Filter on aggregate function results |通过聚合函数过滤结果| |2 |Sort results before using collect on them |collect前排序操作| |3 |Limit branching of a path search |匹配路径、限制为一定数量,然后使用这些路径作为基础再次匹配| #### 2.3 SKIP | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |skip first three rows |跳过最开始的行| |2 |Return middle tow rows |配合limit返回中间的行| |3 |Using an expression with SKIP to return a subset of the rows |使用SKIP带有表达式返回行的子集| #### 2.4 LIMIT | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Return a subset of the rows |返回查询结果的子集| |2 |Using an expression with LIMIT to return a subset of the rows |limit带有表达式返回行的子集| #### 2.5 Return | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 | Return nodes |返回查询的节点| |2 | Return edges |返回查询的边| |3 | Return property |返回节点或者边的属性| |4 | Return all elements |返回全部元素| |5 | Variable with uncommon characters |支持不通用的字符变量| |6 | Aliasing a field |返回值起别名| |7 | unique results |distinct 返回值| #### 2.6 ORDER BY | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 | Order nodes by proerty |通过单个属性排序| |2 | Order nodes by multiple properties |通过多个属性排序| |3 | Order nodes in descending order |降序排序| |4 | Ordering null |null的排序规则升序在最后| #### 2.7 CREATE | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| | 1 | Create single vertex |创建单个节点| | 2 | Create multiple vertices |创建多个节点| | 3 | Create a vertex with a label |创建带标签的节点| | 4 | Create vertex and add labels and properties |创建带标签和加属性的节点| | 5 | Return create node |创建并返回节点| | 6 | Create an edge between two nodes |创建边| | 7 | Create an edge and set properties |创建边并赋属性值| | 8 | Create a full path |创建一条路经| #### 2.8 SET | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Set a property |修改单个属性| |2 |Return created vertex |返回修改后的节点| |3 |Remove a property |移除属性| |4 |Set multiple properties using one SET clause |修改多个属性| #### 2.9 REMOVE | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Remove a property |移除属性| #### 2.10 DELETE | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Delete single vertex |删除单个节点| |2 |Delete all vertices and edges |删除全部节点和边| |3 |Delete edges only |删除边| |4 |Return a deleted vertex |返回删除的节点| ### 3 函数支持 函数主要是对agtype的操作和表达式的生成,具体内容可参考: #### 3.1 Predicate Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Exists(Property) |检测属性是否存在| |2 |Exists(Path) | 检测查询路径是否存在| #### 3.2 Scalar Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |id |返回顶点或边的 id| |2 |start\_id |返回边的起始顶点的 id| |3 |end\_id |返回边的终止顶点的 id| |4 |type |返回边类型的字符串表示形式| |5 |properties |返回包含顶点或边的所有属性的 agtype map。如果参数已经是map,则原封不动地返回| |6 |head |返回 agtype 列表中的第一个元素| |7 |last |返回 agtype 列表中的最后一个元素| |8 |length |返回路径的长度| |9 |size |返回列表的长度| |10 |startNode |返回边的起始节点| |11 |endNode |返回边的终点节点| |12 |timestamp |返回当前时间与 UTC 1970 年 1 月 1 日午夜之间的差值(以毫秒为单位)| |13 |toBoolean |将字符串值转换为布尔值| |14 |toFloat |将整数或字符串值转换为浮点数| |15 |toInteger |将浮点数或字符串值转换为整数值| |15 |coalesce |返回给定表达式列表中的第一个非空值| #### 3.3 List Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |keys |返回一个列表,其中包含顶点、边或map的所有属性名称的字符串表示形式| |2 |range |返回一个列表,该列表包含起始值start和结束值end所限定范围内的所有整数值| |3 |labels |返回一个包含节点所有标签的字符串表示形式的列表| |4 |relationships |返回包含路径中所有关系的列表| |5 |nodes |返回包含路径中所有顶点的列表| #### 3.4 Numeric Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |rand |返回一个随机浮点数,范围从 0(含)到 1(不含);即 \[0,1]| |2 |abs |返回给定数字的绝对值| |3 |ceil |返回大于或等于给定数字且等于数学整数的最小浮点数| |4 |floor |返回小于或等于给定数字且等于数学整数的最大浮点数| |5 |round |返回四舍五入为最接近的整数的给定数字的值| |6 |sign |返回给定数字的符号| #### 3.5 Logarithmic Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |e |返回自然对数的底数,e| |2 |sqrt |返回数字的平方根| |3 |exp |返回 e^n,其中 e 是自然对数的底数,n 是参数表达式的值| |4 |log |返回数字的自然对数| |5 |log10 |返回一个数字的常用对数(底数为 10)| #### 3.6 Trigonometric Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |degrees |将弧度转换为度| |2 |radians |将度数转换为弧度| |3 |pi |返回数学常数 pi| |4 |sin |返回数字的正弦| |5 |cos |返回数字的余弦| |6 |tan |返回数字的正切| |7 |cot |返回数字的余切| |8 |asin |返回数字的反正弦| |9 |acos |返回数字的反余弦| |10| atan |返回数字的反正切| |11| atan2 |以弧度返回一组坐标的反正切值| #### 3.7 String Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |replace |返回一个字符串,其中原始字符串中出现的所有指定字符串都已被另一个(指定的)字符串替换 |2 |split |返回根据给定分隔符的匹配项对原始字符串进行拆分后得到的字符串列表| |3 |left |返回包含原始字符串最左边指定数量字符的字符串。| |4 |right |返回包含原始字符串最右边指定数量字符的字符串。| |5 |substring |返回原始字符串的子字符串,以从 0 开始的索引开始和长度。| |6 |rTrim |返回删除尾随空格后的原始字符串| |7 |lTrim |返回删除前导空格后的原始字符串。| |8 |trim |返回删除前导和尾随空格的原始字符串| |9 |toLower |以小写形式返回原始字符串| |10 |toUpper |以大写形式返回原始字符串| |11 |reverse |返回原始字符串中所有字符的顺序均已反转的字符串。| #### 3.8 Aggregation Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |min |返回一组值中的最小值| |2 |max |返回一组值中的最大值| |3 |stDev |返回给定值在一组中的标准偏差| |4 |stDevP |返回给定值在一组中的标准偏差| |5 |percentileCont |返回给定值在组中的百分位数| |6 |percentileDisc |返回给定值在组中的百分位数| |7 |count |返回值或记录的数量| |8 |avg |返回一组数值的平均值| |9 |sum |返回一组数值的总和| --- --- url: /zh/docs/latest/datavec/apache_age_adaptation.md --- # Apache AGE (incubating) for openGauss 适配详情 ## 说明 Apache AGE通过创建插件的形式使用。 ``` create extension age; ``` AGE安装之后,会默认创建ag\_catalog的schema,AGE内置的数据类型、函数均存储在ag\_catalog下。因此在使用AGE的时候,特别是执行cypher语句时,需要先执行命令: ``` SET search_path TO ag_catalog; ``` 同时需要执行 load 'age' 命令确保age插件的全部hook被加载,保证图数据的完整性。 ``` load 'age'; ``` > \[!NOTE]说明 > > 创建使用age插件前需要关闭线程池,设置enable\_thread\_pool = off ## 1. 图的操作 图由一组顶点和边组成,其中每个单独的节点和边都具有属性映射。顶点是图的基本对象,它可以独立于图中的其他任何东西而存在。边在两个顶点之间创建有向连接。 ### 1.1 创建图 创建图使用函数:create\_graph(graph\_name); ``` SELECT * FROM ag_catalog.create_graph('graph_name'); ``` ### 1.2 删除图 删除图使用函数:drop\_graph(graph\_name, cascade); > 1. 第一个参数graph\_name为要删除的图,第二个参数cascade为布尔值,表示是否删除依赖于图表的标签和数据 > 2. 建议将 cascade 选项设置为 true,否则必须使用 SQL DDL 命令手动删除图中的所有内容 ``` SELECT * FROM ag_catalog.drop_graph('graph_name', true); ``` ### 1.3 创建图中的点类型 创建图中的点类型使用函数:create\_vlabel(graph\_name, label\_name); ``` SELECT * FROM ag_catalog.create_vlabel('graph_name','label_name'); ``` 每当使用create\_vlabel()函数创建顶点标签时,会在new\_graph的命名空间new\_graph中生成一个新表"\"。用于创建边类型的create\_elabel()函数也是如此。这两个函数不是必须使用的,用Cypher语句创建顶点和边时,如果类型表不存在,会自动创建。 ### 1.4 创建图中的边类型 创建图使用函数:create\_elabel(graph\_name, label\_name); ``` SELECT * FROM ag_catalog.create_elabel('graph_name','label_name'); ``` ## 2. 图的存储 ### 2.1 图 图创建之后,内核会创建一个与图名称相同的schema。同时在ag\_catalog.ag\_graph的表中会插入一条数据,标记新创建的schema用来存储图数据。 ``` SELECT create_graph('new_graph'); NOTICE: graph "new_graph" has been created create_graph -------------- (1 row) SELECT * FROM ag_catalog.ag_graph; name | namespace -----------+----------- new_graph | new_graph (1 row) ``` ### 图中的点和边 ``` -- 创建图之后,会在该图对应的schema中创建_ag_label_vertex和_ag_label_edge两张表作为默认的点表和边表,同时会在ag_catalog.ag_label中插入两条数据将点表和边表与schema关联起来。 SELECT * FROM ag_catalog.ag_label; name | graph | id | kind | relation ------------------+-------+----+------+---------------------------- _ag_label_vertex | 68484 | 1 | v | new_graph._ag_label_vertex _ag_label_edge | 68484 | 2 | e | new_graph._ag_label_edge (2 rows) -- 创建点表 SELECT create_vlabel('new_graph', 'Person'); NOTICE: VLabel "Person" has been created create_vlabel --------------- (1 row) -- 创建点表之后,会在ag_catalog.ag_label表中插入一条数据将点表与图关联起来。kind为v代表点表kind为e代表边表 SELECT * FROM ag_catalog.ag_label; name | graph | id | kind | relation ------------------+-------+----+------+---------------------------- _ag_label_vertex | 68484 | 1 | v | new_graph._ag_label_vertex _ag_label_edge | 68484 | 2 | e | new_graph._ag_label_edge Person | 68484 | 3 | v | new_graph."Person" (3 rows) ``` ## 3. Cypher查询 Cypher语句无法在数据库中直接执行。需要通过cypher()函数构造,将Cypher语句作为cypher()函数的参数执行,cypher()函数返回一个SETOF records。 ### 3.1 cypher()函数介绍 cypher(graph\_name, query\_string, parameters) > 第一个参数graph\_name为要查询的图,第二个参数query\_string为Cypher语句,第三个参数parameters为可选参数只能与Prepared Statements一起使用。否则将抛出错误。 ``` SELECT * FROM cypher('graph_name', $$ /* Cypher Query Here */ $$) AS (result1 agtype, result2 agtype); ``` **注意事项** > 1. AS 后的 (result1 agtype, result2 agtype) 即SETOF records 需要和Cypher语句中的返回值个数相同 > 2. SELECT \* FROM cypher 不能写成 SELECT cypher > 3. 执行语句前需要执行 load 'age' 和 set search\_path = ag\_catalog ## 数据类型及函数说明 以下对AGE中包含的数据类型、Cypher语法、函数进行简要说明。 ### 1 数据类型 AGE的会创建两种数据类型: graphid 和 agtype。其中graphid代表点和边的唯一id标识符。agtype为AGE的核心数据类型,具体介绍可参考 #### 1.1 Simple DataTypes 简单数据类型包括:Null、Integer、Float、Numeric、Bool、String。 #### 1.2 Composite DataTypes 复合数据类型包括:List、Map。 * List支持以下操作 | 序号 | 功能支持 | 说明 | |:--------|:---------|--------:| | 1 |List in general | 普通list | | 2 |NULL in a List | 带null的list | | 3 |Access Individual Elements | 获取list的某个元素 | | 4 |MapElements in Lists | list元素包含map结构 | | 5 |Accessing Map Elements in Lists | 获取list元素中map的值 | | 6 |Negative Index Access | 负值索引 | | 7 |Index Ranges | 区间索引 | | 8 |Negative Index Ranges | 负值区间区间索引 | | 9 |Positive Slices | 正切片操作 | | 10 |Negative Slices | 负切片操作 | * Map支持以下操作 | 序号 | 功能支持 | 说明 | |:--------|:---------|--------:| |1 | Literal Maps with SimpleDataTypes | 普通map类型 | |2 | Literal Maps with composite Data Types | map中包含复合数据类型 | |3 | Property Access of a map | map的属性值获取操作 | |4 | Accessing List Elements in Maps | map中获取list元素操作 | #### 1.3 Simple Entities 简单实体类型包括 GraphId、Labels、Properties。又简单实体类型组成Vertex、Edge、Composite Entities。 #### 1.4 Vertex Vertex 是图的基本组成元素,代表节点。 #### 1.5 Edge Edge 是图的基本组成元素,代表边。 #### 1.6 Composite Entities 由Vertex 和 Edge组成的Path类型。 ### 2 Cypher语法 AGE对Cypher语法的支持具体介绍可参考: #### 2.1 Match | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 | get all vertices | 获取全部节点| |2 | get all vertices with a label | 获取某label类型的全部节点| |3 | related vertices | 通过边获取相关节点(邻居节点)| |4 | match with labels | 通过label过滤相关节点| |5 | Outgoing Edges |有向边支持| |6 | Directed Edges and variable | 有向边变量支持| |7 | Match on edge type |通过label type过滤边| |8 | Match on edge type and use a variable | 通过label type过滤边同时设置变量| |9 | Multiple Edges | 多条边匹配| |10 | Variable Length Edges | 变长路径匹配| #### 2.2 With | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Filter on aggregate function results |通过聚合函数过滤结果| |2 |Sort results before using collect on them |collect前排序操作| |3 |Limit branching of a path search |匹配路径、限制为一定数量,然后使用这些路径作为基础再次匹配| #### 2.3 SKIP | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |skip first three rows |跳过最开始的行| |2 |Return middle tow rows |配合limit返回中间的行| |3 |Using an expression with SKIP to return a subset of the rows |使用SKIP带有表达式返回行的子集| #### 2.4 LIMIT | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Return a subset of the rows |返回查询结果的子集| |2 |Using an expression with LIMIT to return a subset of the rows |limit带有表达式返回行的子集| #### 2.5 Return | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 | Return nodes |返回查询的节点| |2 | Return edges |返回查询的边| |3 | Return property |返回节点或者边的属性| |4 | Return all elements |返回全部元素| |5 | Variable with uncommon characters |支持不通用的字符变量| |6 | Aliasing a field |返回值起别名| |7 | unique results |distinct 返回值| #### 2.6 ORDER BY | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 | Order nodes by proerty |通过单个属性排序| |2 | Order nodes by multiple properties |通过多个属性排序| |3 | Order nodes in descending order |降序排序| |4 | Ordering null |null的排序规则升序在最后| #### 2.7 CREATE | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| | 1 | Create single vertex |创建单个节点| | 2 | Create multiple vertices |创建多个节点| | 3 | Create a vertex with a label |创建带标签的节点| | 4 | Create vertex and add labels and properties |创建带标签和加属性的节点| | 5 | Return create node |创建并返回节点| | 6 | Create an edge between two nodes |创建边| | 7 | Create an edge and set properties |创建边并赋属性值| | 8 | Create a full path |创建一条路经| #### 2.8 SET | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Set a property |修改单个属性| |2 |Return created vertex |返回修改后的节点| |3 |Remove a property |移除属性| |4 |Set multiple properties using one SET clause |修改多个属性| #### 2.9 REMOVE | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Remove a property |移除属性| #### 2.10 DELETE | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Delete single vertex |删除单个节点| |2 |Delete all vertices and edges |删除全部节点和边| |3 |Delete edges only |删除边| |4 |Return a deleted vertex |返回删除的节点| ### 3 函数支持 函数主要是对agtype的操作和表达式的生成,具体内容可参考: #### 3.1 Predicate Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |Exists(Property) |检测属性是否存在| |2 |Exists(Path) | 检测查询路径是否存在| #### 3.2 Scalar Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |id |返回顶点或边的 id| |2 |start\_id |返回边的起始顶点的 id| |3 |end\_id |返回边的终止顶点的 id| |4 |type |返回边类型的字符串表示形式| |5 |properties |返回包含顶点或边的所有属性的 agtype map。如果参数已经是map,则原封不动地返回| |6 |head |返回 agtype 列表中的第一个元素| |7 |last |返回 agtype 列表中的最后一个元素| |8 |length |返回路径的长度| |9 |size |返回列表的长度| |10 |startNode |返回边的起始节点| |11 |endNode |返回边的终点节点| |12 |timestamp |返回当前时间与 UTC 1970 年 1 月 1 日午夜之间的差值(以毫秒为单位)| |13 |toBoolean |将字符串值转换为布尔值| |14 |toFloat |将整数或字符串值转换为浮点数| |15 |toInteger |将浮点数或字符串值转换为整数值| |15 |coalesce |返回给定表达式列表中的第一个非空值| #### 3.3 List Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |keys |返回一个列表,其中包含顶点、边或map的所有属性名称的字符串表示形式| |2 |range |返回一个列表,该列表包含起始值start和结束值end所限定范围内的所有整数值| |3 |labels |返回一个包含节点所有标签的字符串表示形式的列表| |4 |relationships |返回包含路径中所有关系的列表| |5 |nodes |返回包含路径中所有顶点的列表| #### 3.4 Numeric Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |rand |返回一个随机浮点数,范围从 0(含)到 1(不含);即 \[0,1]| |2 |abs |返回给定数字的绝对值| |3 |ceil |返回大于或等于给定数字且等于数学整数的最小浮点数| |4 |floor |返回小于或等于给定数字且等于数学整数的最大浮点数| |5 |round |返回四舍五入为最接近的整数的给定数字的值| |6 |sign |返回给定数字的符号| #### 3.5 Logarithmic Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |e |返回自然对数的底数,e| |2 |sqrt |返回数字的平方根| |3 |exp |返回 e^n,其中 e 是自然对数的底数,n 是参数表达式的值| |4 |log |返回数字的自然对数| |5 |log10 |返回一个数字的常用对数(底数为 10)| #### 3.6 Trigonometric Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |degrees |将弧度转换为度| |2 |radians |将度数转换为弧度| |3 |pi |返回数学常数 pi| |4 |sin |返回数字的正弦| |5 |cos |返回数字的余弦| |6 |tan |返回数字的正切| |7 |cot |返回数字的余切| |8 |asin |返回数字的反正弦| |9 |acos |返回数字的反余弦| |10| atan |返回数字的反正切| |11| atan2 |以弧度返回一组坐标的反正切值| #### 3.7 String Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |replace |返回一个字符串,其中原始字符串中出现的所有指定字符串都已被另一个(指定的)字符串替换 |2 |split |返回根据给定分隔符的匹配项对原始字符串进行拆分后得到的字符串列表| |3 |left |返回包含原始字符串最左边指定数量字符的字符串。| |4 |right |返回包含原始字符串最右边指定数量字符的字符串。| |5 |substring |返回原始字符串的子字符串,以从 0 开始的索引开始和长度。| |6 |rTrim |返回删除尾随空格后的原始字符串| |7 |lTrim |返回删除前导空格后的原始字符串。| |8 |trim |返回删除前导和尾随空格的原始字符串| |9 |toLower |以小写形式返回原始字符串| |10 |toUpper |以大写形式返回原始字符串| |11 |reverse |返回原始字符串中所有字符的顺序均已反转的字符串。| #### 3.8 Aggregation Functions | 序号 | 功能支持 | 说明 | |:--------|:---------|:--------| |1 |min |返回一组值中的最小值| |2 |max |返回一组值中的最大值| |3 |stDev |返回给定值在一组中的标准偏差| |4 |stDevP |返回给定值在一组中的标准偏差| |5 |percentileCont |返回给定值在组中的百分位数| |6 |percentileDisc |返回给定值在组中的百分位数| |7 |count |返回值或记录的数量| |8 |avg |返回一组数值的平均值| |9 |sum |返回一组数值的总和| --- --- url: /en/docs/latest-lite/brief_tutorial/appendix_sql_syntax.md --- # Appendix: SQL Syntax ## ABORT Exits the current transaction. ``` ABORT [ WORK | TRANSACTION ] ; ``` ## ALTER AUDIT POLICY Modifies the unified audit policy. ``` ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ADD | REMOVE } { [ privilege_audit_clause ] [ access_audit_clause ] }; ALTER AUDIT POLICY [ IF EXISTS ] policy_name MODIFY ( filter_group_clause ); ALTER AUDIT POLICY [ IF EXISTS ] policy_name DROP FILTER; ALTER AUDIT POLICY [ IF EXISTS ] policy_name COMMENTS policy_comments; ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ENABLE | DISABLE }; where privilege_audit_clause can be: PRIVILEGES { DDL | ALL } where access_audit_clause can be: ACCESS { DML | ALL } where filter_group_clause can be: FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } where DDL can be: { ( ALTER | ANALYZE | COMMENT | CREATE | DROP | GRANT | REVOKE | SET | SHOW | LOGIN_ACCESS | LOGIN_FAILURE | LOGOUT | LOGIN ) } where DML can be: { ( COPY | DEALLOCATE | DELETE_P | EXECUTE | REINDEX | INSERT | REPARE | SELECT | TRUNCATE | UPDATE ) } ``` ## ALTER DATA SOURCE Modifies the attributes and content of the data source. ``` ALTER DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS ( { [ADD | SET | DROP] optname ['optvalue'] } [, ...] )]; ALTER DATA SOURCE src_name RENAME TO src_new_name; ALTER DATA SOURCE src_name OWNER TO new_owner; Valid optname are: DSN, USERNAME, PASSWORD, ENCODING ``` ## ALTER DATABASE Modifies a database, including its name, owner, connection limitation, and object isolation. ``` ALTER DATABASE database_name [ [ WITH ] CONNECTION LIMIT connlimit ]; ALTER DATABASE database_name RENAME TO new_name; ALTER DATABASE database_name OWNER TO new_owner; ALTER DATABASE database_name SET TABLESPACE new_tablespace; ALTER DATABASE database_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ALTER DATABASE database_name RESET { configuration_parameter | ALL }; ALTER DATABASE database_name [ WITH ] { ENABLE | DISABLE } PRIVATE OBJECT; ``` ## ALTER DEFAULT PRIVILEGES Sets the permissions that will be applied to objects created in the future. (It does not affect permissions granted to existing objects.) ``` ALTER DEFAULT PRIVILEGES [ FOR { ROLE | USER } target_role [, ...] ] [ IN SCHEMA schema_name [, ...] ] abbreviated_grant_or_revoke; where abbreviated_grant_or_revoke can be: grant_on_tables_clause | grant_on_sequences_clause | grant_on_functions_clause | grant_on_types_clause | grant_on_client_master_keys_clause | grant_on_column_encryption_keys_clause | revoke_on_tables_clause | revoke_on_sequences_clause | revoke_on_functions_clause | revoke_on_types_clause | revoke_on_client_master_keys_clause | revoke_on_column_encryption_keys_clause where grant_on_tables_clause can be: GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_sequences_clause can be: GRANT { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_functions_clause can be: GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_types_clause can be: GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_client_master_keys_clause can be: GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_column_encryption_keys_clause can be: GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where revoke_on_tables_clause can be: REVOKE [ GRANT OPTION FOR ] { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_sequences_clause can be: REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_functions_clause can be: REVOKE [ GRANT OPTION FOR ] { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_types_clause can be: REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_client_master_keys_clause can be: REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_column_encryption_keys_clause can be: REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` ## ALTER DIRECTORY Modifies a directory. ``` CREATE [OR REPLACE] DIRECTORY directory_name AS 'path_name'; ``` ## ALTER EXTENSION Modifies an extension. ``` ALTER EXTENSION name UPDATE [ TO new_version ]; ALTER EXTENSION name SET SCHEMA new_schema; ALTER EXTENSION name ADD member_object; ALTER EXTENSION name DROP member_object; where member_object is: FOREIGN TABLE object_name | FUNCTION function_name ( [ [ argmode ] [ argname ] argtype [, ...] ] ) | [ PROCEDURAL ] LANGUAGE object_name | SCHEMA object_name | SERVER object_name | TABLE object_name | TEXT SEARCH CONFIGURATION object_name | TYPE object_name | VIEW object_name ``` ## ALTER FOREIGN TABLE Modifies a foreign table. ``` 1. GDS: ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] tablename OWNER TO new_owner; 2. HDFS: ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] tablename OWNER TO new_owner; ALTER FOREIGN TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ALTER FOREIGN TABLE [ IF EXISTS ] tablename ADD [CONSTRAINT constraint_name] {PRIMARY KEY | UNIQUE} (column_name) [NOT ENFORCED [ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION] | ENFORCED]; ALTER FOREIGN TABLE [ IF EXISTS ] tablename DROP CONSTRAINT constraint_name ; ALTER FOREIGN TABLE [ IF EXISTS ] tablename action [, ... ]; where action can be: ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS integer | ALTER [ COLUMN ] column_name OPTIONS ( {[ ADD | SET | DROP ] option ['value'] } [, ... ]) | MODIFY column_name data_type | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL 3. OBS: ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] tablename OWNER TO new_owner; ALTER FOREIGN TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ALTER FOREIGN TABLE [ IF EXISTS ] tablename ADD [CONSTRAINT constraint_name] {PRIMARY KEY | UNIQUE} (column_name) [NOT ENFORCED [ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION] | ENFORCED]; ALTER FOREIGN TABLE [ IF EXISTS ] tablename DROP CONSTRAINT constraint_name ; ALTER FOREIGN TABLE [ IF EXISTS ] tablename action [, ... ]; where action can be: ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS integer | ALTER [ COLUMN ] column_name OPTIONS ( {[ ADD | SET | DROP ] option ['value'] } [, ... ]) | MODIFY column_name data_type | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL 4. GC: ALTER FOREIGN TABLE [ IF EXISTS ] tablename OPTIONS ( {[ SET ] option ['value']} [, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] tablename OWNER TO new_owner; ALTER FOREIGN TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type [, ...] ); ALTER FOREIGN TABLE [ IF EXISTS ] tablename action [, ... ]; where action can be: ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type | MODIFY column_name data_type ``` ## ALTER FUNCTION Modifies the attributes of a user-defined function. ``` ALTER FUNCTION function_name ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ALTER FUNCTION funname ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) RENAME TO new_name; ALTER FUNCTION funname ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) OWNER TO new_owner; ALTER FUNCTION funname ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) SET SCHEMA new_schema; where action can be: {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER} | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter {{ TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter| ALL} ``` ## ALTER GROUP Modifies the attributes of a user group. ``` ALTER GROUP group_name ADD USER user_name [, ... ]; ALTER GROUP group_name DROP USER user_name [, ... ]; ALTER GROUP group_name RENAME TO new_name; ``` ## ALTER INDEX Modifies the definition of an existing index. ``` ALTER INDEX [ IF EXISTS ] index_name RENAME TO new_name; ALTER INDEX [ IF EXISTS ] index_name SET TABLESPACE tablespace_name; ALTER INDEX [ IF EXISTS ] index_name SET ( {storage_parameter = value} [, ... ] ); ALTER INDEX [ IF EXISTS ] index_name RESET ( storage_parameter [, ... ] ) ; ALTER INDEX [ IF EXISTS ] index_name [ MODIFY PARTITION partition_name ] UNUSABLE; ALTER INDEX index_name REBUILD [ PARTITION partition_name ]; ALTER INDEX [ IF EXISTS ] index_name RENAME PARTITION partition_name TO new_partition_name; ALTER INDEX [ IF EXISTS ] index_name MOVE PARTITION index_partition_name TABLESPACE new_tablespace; ``` ## ALTER LARGE OBJECT Modifies the definition of a large object. It is used to assign a new owner. ``` ALTER LARGE OBJECT large_object_oid OWNER TO new_owner; ``` ## ALTER MASKING POLICY Modifies a masking policy. ``` ALTER MASKING POLICY policy_name { ADD | REMOVE | MODIFY } masking_actions [, ... ]; ALTER MASKING POLICY policy_name MODIFY ( filter_group_clause ); ALTER MASKING POLICY policy_name DROP FILTER; ALTER MASKING POLICY policy_name { ENABLE | DISABLE }; where masking_actions can be: masking_function ON LABEL(label_name [, ... ]) where masking_function can be: { maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking } where filter_group_clause can be: FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## ALTER MATERIALIZED VIEW Modifies multiple auxiliary attributes of an existing materialized view. ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name OWNER TO new_owner; ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME [COLUMN] column_name to new_column_name; ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME TO new_name; ``` ## ALTER OPERATOR Modifies the definition of an operator. ``` ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) OWNER TO new_owner ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) SET SCHEMA new_schema ``` ## ALTER RESOURCE LABEL Modifies a resource label. ``` ALTER RESOURCE LABEL label_name { ADD | REMOVE } label_item_list [, ... ]; where label_item_list can be: resource_type(resource_path[, ... ]) where resource_type can be: { TABLE | COLUMN | SCHEMA | VIEW | FUNCTION } ``` ## ALTER RESOURCE POOL Modifies the Cgroup of a resource pool. ``` ALTER RESOURCE POOL pool_name WITH ({MEM_PERCENT=pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='priority' | nodegroup='nodegroup_name' }[, ... ]); ``` ## ALTER ROLE Modifies role attributes. ``` ALTER ROLE role_name [ [ WITH ] option [ ... ] ]; ALTER ROLE role_name RENAME TO new_name; ALTER ROLE role_name [ IN DATABASE database_name ] SET configuration_parameter {{ TO | = } { value | DEFAULT }|FROM CURRENT}; ALTER ROLE role_name [ IN DATABASE database_name ] RESET {configuration_parameter|ALL}; where option can be: {CREATEDB | NOCREATEDB} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {AUDITADMIN | NOAUDITADMIN} | {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {USEFT | NOUSEFT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' [ EXPIRED ] | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' | EXPIRED ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | ACCOUNT { LOCK | UNLOCK } | PGUSER ``` ## ALTER ROW LEVEL SECURITY POLICY Modifies an existing row-level access control policy, including the policy name and the users and expressions affected by the policy. ``` ALTER [ ROW LEVEL SECURITY ] POLICY [ IF EXISTS ] policy_name ON table_name RENAME TO new_policy_name ALTER [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ TO { role_name | PUBLIC } [, ...] ] [ USING ( using_expression ) ] ``` ## ALTER SCHEMA Modifies schema attributes. ``` ALTER SCHEMA schema_name RENAME TO new_name; ALTER SCHEMA schema_name OWNER TO new_owner; ALTER SCHEMA schema_name {WITH | WITHOUT} BLOCKCHAIN; ``` ## ALTER SEQUENCE Modifies the parameters of an existing sequence. ``` ALTER SEQUENCE [ IF EXISTS ] name [ MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE ] [ OWNED BY { table_name.column_name | NONE } ]; ALTER SEQUENCE [ IF EXISTS ] name OWNER TO new_owner; ``` ## ALTER SERVER Adds, modifies, or deletes the parameters of an existing server. You can query existing servers from the **pg\_foreign\_server** system catalog. ``` ALTER SERVER server_name [ VERSION 'new_version' ] [ OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ] ) ]; ALTER SERVER server_name OWNER TO new_owner; ALTER SERVER server_name RENAME TO new_name; ``` ## ALTER SESSION Defines or modifies the conditions or parameters that affect the current session. Modified session parameters are kept until the current session is disconnected. ``` ALTER SESSION SET {{config_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }} | CURRENT_SCHEMA [ TO | = ] { schema | DEFAULT } | TIME ZONE time_zone | SCHEMA schema | NAMES encoding_name | ROLE role_name PASSWORD 'password' | SESSION AUTHORIZATION { role_name PASSWORD 'password' | DEFAULT } | XML OPTION { DOCUMENT | CONTENT } } ; ALTER SESSION SET [ SESSION CHARACTERISTICS AS ] TRANSACTION { ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED } | { READ ONLY | READ WRITE } } [, ...] ; ``` ## ALTER SYNONYM Modifies the attributes of the **SYNONYM** object. ``` ALTER SYNONYM synonym_name OWNER TO new_owner; ``` ## ALTER SYSTEM KILL SESSION Ends a session. ``` ALTER SYSTEM KILL SESSION 'session_sid, serial' [ IMMEDIATE ]; ``` ## ALTER SYSTEM SET Sets GUC parameters at the POSTMASTER, SIGHUP, and BACKEND levels. This command writes parameters into the configuration file. The time to take effect varies according to the level. ``` ALTER SYSTEM SET { GUC_name } TO { GUC_value }; ``` ## ALTER TABLE Modifies tables, including modifying table definitions, renaming tables, renaming specified columns in tables, renaming table constraints, setting table schemas, enabling or disabling row-level security policies, and adding or updating multiple columns. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ALTER TABLE [ IF EXISTS ] table_name ADD ( { column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ]} [, ...] ); ALTER TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ALTER TABLE [ IF EXISTS ] table_name RENAME TO new_table_name; ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME [ COLUMN ] column_name TO new_column_name; ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME CONSTRAINT constraint_name TO new_constraint_name; ALTER TABLE [ IF EXISTS ] table_name SET SCHEMA new_schema; where action can be: column_clause | ADD table_constraint [ NOT VALID ] | ADD table_constraint_using_index | VALIDATE CONSTRAINT constraint_name | DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ] | CLUSTER ON index_name | SET WITHOUT CLUSTER | SET ( {storage_parameter = value} [, ... ] ) | RESET ( storage_parameter [, ... ] ) | OWNER TO new_owner | SET TABLESPACE new_tablespace | SET {COMPRESS|NOCOMPRESS} | TO { GROUP groupname | NODE ( nodename [, ... ] ) } | ADD NODE ( nodename [, ... ] ) | DELETE NODE ( nodename [, ... ] ) | UPDATE SLICE LIKE table_name | DISABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE REPLICA TRIGGER trigger_name | ENABLE ALWAYS TRIGGER trigger_name | ENABLE ROW LEVEL SECURITY | DISABLE ROW LEVEL SECURITY | FORCE ROW LEVEL SECURITY | NO FORCE ROW LEVEL SECURITY | ENCRYPTION KEY ROTATION where column_clause can be: ADD [ COLUMN ] column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | MODIFY column_name data_type | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL | DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ] | ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ] | ALTER [ COLUMN ] column_name { SET DEFAULT expression | DROP DEFAULT } | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS [PERCENT] integer | ADD STATISTICS (( column_1_name, column_2_name [, ...] )) | DELETE STATISTICS (( column_1_name, column_2_name [, ...] )) | ALTER [ COLUMN ] column_name SET ( {attribute_option = value} [, ... ] ) | ALTER [ COLUMN ] column_name RESET ( attribute_option [, ... ] ) | ALTER [ COLUMN ] column_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN } where column_constraint can be: [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED ALWAYS AS ( generation_expr ) STORED | UNIQUE index_parameters | PRIMARY KEY index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where compress_mode can be: { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } where table_constraint can be: [ CONSTRAINT constraint_name ] { CHECK ( expression ) | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where index_parameters can be: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] where table_constraint_using_index can be: [ CONSTRAINT constraint_name ] { UNIQUE | PRIMARY KEY } USING INDEX index_name [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` ## ALTER TABLE INHERIT ``` ALTER TABLE table_name { inherit | no inherit } parent_name; ``` ## ALTER TABLE PARTITION ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME PARTITION { partion_name | FOR ( partition_value [, ...] ) } TO partition_new_name; where action can be: move_clause | exchange_clause | row_clause | merge_clause | modify_clause | split_clause | add_clause | drop_clause where move_clause can be: MOVE PARTITION { partion_name | FOR ( partition_value [, ...] ) } TABLESPACE tablespacename where exchange_clause can be: EXCHANGE PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } WITH TABLE {[ ONLY ] ordinary_table_name | ordinary_table_name * | ONLY ( ordinary_table_name )} [ { WITH | WITHOUT } VALIDATION ] [ VERBOSE ] where row_clause can be: { ENABLE | DISABLE } ROW MOVEMENT where merge_clause can be: MERGE PARTITIONS { partition_name } [, ...] INTO PARTITION partition_name [ TABLESPACE tablespacename ] where modify_clause can be: MODIFY PARTITION partition_name { UNUSABLE LOCAL INDEXES | REBUILD UNUSABLE LOCAL INDEXES } where split_clause can be: SPLIT PARTITION { partition_name | FOR ( partition_value [, ...] ) } { split_point_clause | no_split_point_clause } where split_point_clause can be: AT ( partition_value ) INTO ( PARTITION partition_name [ TABLESPACE tablespacename ] , PARTITION partition_name [ TABLESPACE tablespacename ] ) where no_split_point_clause can be: INTO {(partition_less_than_item [, ...] ) | (partition_start_end_item [, ...] )} where add_clause can be: ADD {partition_less_than_item | partition_start_end_item} where partition_less_than_item can be: PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } [, ...] ) [ TABLESPACE tablespacename ] where partition_start_end_item can be: PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] where drop_clause can be: DROP PARTITION { partition_name | FOR ( partition_value [, ...] ) } ``` ## ALTER TABLESPACE Modifies the attributes of a tablespace. ``` ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name; ALTER TABLESPACE tablespace_name OWNER TO new_owner; ALTER TABLESPACE tablespace_name SET ( {tablespace_option = value} [, ... ] ); ALTER TABLESPACE tablespace_name RESET ( tablespace_option [, ... ] ); ALTER TABLESPACE tablespace_name RESIZE MAXSIZE { UNLIMITED | 'space_size' }; ``` ## ALTER TEXT SEARCH CONFIGURATION Modifies the definition of a text search configuration. You can modify its mappings from strings to dictionaries, change the configuration's name or owner, or modify the parameters. ``` ALTER TEXT SEARCH CONFIGURATION name ADD MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ] ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ] ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING REPLACE old_dictionary WITH new_dictionary ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] REPLACE old_dictionary WITH new_dictionary ALTER TEXT SEARCH CONFIGURATION name DROP MAPPING [ IF EXISTS ] FOR token_type [, ... ] ALTER TEXT SEARCH CONFIGURATION name RENAME TO new_name ALTER TEXT SEARCH CONFIGURATION name OWNER TO new_owner ALTER TEXT SEARCH CONFIGURATION name SET SCHEMA new_schema ALTER TEXT SEARCH CONFIGURATION name SET ( {configuration_option = value} [, ...] ) ALTER TEXT SEARCH CONFIGURATION name RESET ( {configuration_option} [, ...] ) ``` ## ALTER TEXT SEARCH DICTIONARY Modifies the definition of a full-text search dictionary, including its parameters, name, owner, and schema. ``` ALTER TEXT SEARCH DICTIONARY name ( option = value | option [, ...] ); ALTER TEXT SEARCH DICTIONARY name RENAME TO new_name; ALTER TEXT SEARCH DICTIONARY name OWNER TO new_owner; ALTER TEXT SEARCH DICTIONARY name SET SCHEMA new_schema ``` ## ALTER TRIGGER Renames a trigger. ``` ALTER TRIGGER name ON table_name RENAME TO new_name ``` ## ALTER TYPE Modifies the definition of a type. ``` ALTER TYPE name action [, ... ] ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ALTER TYPE name RENAME TO new_name ALTER TYPE name SET SCHEMA new_schema ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value where action is one of: ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` ## ALTER USER Modifies the attributes of a database user. ``` ALTER USER user_name [ [ WITH ] option [ ... ] ]; ALTER USER user_name RENAME TO new_name; ALTER USER user_name [ IN DATABASE database_name ] SET configuration_parameter {{ TO | = } { value | DEFAULT }|FROM CURRENT}; ALTER USER user_name [ IN DATABASE database_name ] RESET {configuration_parameter|ALL}; where option can be: {CREATEDB | NOCREATEDB} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {AUDITADMIN | NOAUDITADMIN} | {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {USEFT | NOUSEFT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' [ EXPIRED ] | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' | EXPIRED ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | ACCOUNT { LOCK | UNLOCK } | PGUSER ``` ## ALTER VIEW Modifies the auxiliary attributes of a view. ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name SET DEFAULT expression; ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name DROP DEFAULT; ALTER VIEW [ IF EXISTS ] view_name OWNER TO new_owner; ALTER VIEW [ IF EXISTS ] view_name RENAME TO new_name; ALTER VIEW [ IF EXISTS ] view_name SET SCHEMA new_schema; ALTER VIEW [ IF EXISTS ] view_name SET ( {view_option_name [= view_option_value]} [, ... ] ); ALTER VIEW [ IF EXISTS ] view_name RESET ( view_option_name [, ... ] ); ``` ## ANALYSE|ANALYZE Collects statistics about ordinary tables in a database, and stores the results in the **PG\_STATISTIC** system catalog. The execution plan generator uses these statistics to determine which one is the most effective execution plan. ``` {ANALYZE | ANALYSE} [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ]; {ANALYZE | ANALYSE} [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ] PARTITION partition_name; {ANALYZE | ANALYSE} [ VERBOSE ] { foreign_table_name | FOREIGN TABLES }; {ANALYZE | ANALYSE} [ VERBOSE ] table_name (( column_1_name, column_2_name [, ...] )); {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE}; {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name|index_name [CASCADE]; {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name PARTITION (partition_name) [CASCADE]; ``` ## ANONYMOUS BLOCK Applies to a script that is infrequently executed or a one-off activity. It is executed in a session and is not stored. ``` [DECLARE [declare_statements]] BEGIN execution_staements END; / ``` ## BEGIN Initiates an anonymous block or a single transaction. ``` start an anonymous block: [DECLARE [declare_statements]] BEGIN execution_statements END; / start a transaction: BEGIN [ WORK | TRANSACTION ] [ { ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED | SERIALIZABLE | REPEATABLE READ } | { READ WRITE | READ ONLY } } [, ...] ]; ``` ## CALL Calls defined functions and stored procedures. ``` CALL [schema.] func_name ( param_expr ); ``` ## CHECKPOINT A checkpoint is a point in the transaction log sequence at which all data files have been updated to reflect the information in the log. All data files will be flushed to a disk. ``` CHECKPOINT ``` ## CLEAN CONNECTION Clears database connections. You may use this statement to delete a specific user's connections to a specified database. ``` CLEAN CONNECTION TO { COORDINATOR ( nodename [, ... ] ) | NODE ( nodename [, ... ] ) | ALL [ CHECK ] [ FORCE ] } [ FOR DATABASE dbname ] [ TO USER username ]; ``` ## CLOSE Frees the resources associated with an open cursor. ``` CLOSE { cursor_name | ALL }; ``` ## CLUSTER Clusters a table based on an index. ``` CLUSTER [ VERBOSE ] table_name [ USING index_name ]; CLUSTER [ VERBOSE ] table_name PARTITION ( partition_name ) [ USING index_name ]; CLUSTER [ VERBOSE ]; ``` ## COMMENT Defines or changes the comment of an object. ``` COMMENT ON { AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | COLUMN { table_name.column_name | view_name.column_name } | CONSTRAINT constraint_name ON table_name | CONVERSION object_name | DATABASE object_name | DOMAIN object_name | EXTENSION object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) | INDEX object_name | LARGE OBJECT large_object_oid | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | ROLE object_name | RULE rule_name ON table_name | SCHEMA object_name | SERVER object_name | TABLE object_name | TABLESPACE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name } IS 'text'; ``` ## COMMIT Commits all operations of a transaction. ``` { COMMIT | END } [ WORK | TRANSACTION ]; ``` ## COMMIT PREPARED Commits a prepared two-phase transaction. ``` COMMIT PREPARED transaction_id; ``` ## COPY Copies data between tables and files. ``` COPY table_name [ ( column_name [, ...] ) ] FROM { 'filename' | STDIN } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ LOG ERRORS ] [ LOG ERRORS DATA ] [ REJECT LIMIT 'limit' ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ] | [ TRANSFORM ( { column_name [ data_type ] [ AS transform_expr ] } [, ...] ) ]; COPY table_name [ ( column_name [, ...] ) ] TO { 'filename' | STDOUT } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; COPY query TO { 'filename' | STDOUT } [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; where option can be: FORMAT 'format_name' | OIDS [ boolean ] | DELIMITER 'delimiter_character' | NULL 'null_string' | HEADER [ boolean ] | FILEHEADER 'header_file_string' | FREEZE [ boolean ] | QUOTE 'quote_character' | ESCAPE 'escape_character' | EOL 'newline_character' | NOESCAPING [ boolean ] | FORCE_QUOTE { ( column_name [, ...] ) | * } | FORCE_NOT_NULL ( column_name [, ...] ) | FORCE_NULL ( column_name [, ...] ) | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA [ boolean ] | FILL_MISSING_FIELDS [ boolean ] | COMPATIBLE_ILLEGAL_CHARS [ boolean ] | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' and copy_option can be: OIDS | NULL 'null_string' | HEADER | FILEHEADER 'header_file_string' | FREEZE | FORCE NOT NULL column_name [, ...] | FORCE NULL column_name [, ...] | FORCE QUOTE { column_name [, ...] | * } | BINARY | CSV | QUOTE [ AS ] 'quote_character' | ESCAPE [ AS ] 'escape_character' | EOL 'newline_character' | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA | FILL_MISSING_FIELDS | COMPATIBLE_ILLEGAL_CHARS | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` ## CREATE AUDIT POLICY Creates a unified audit policy. ``` CREATE AUDIT POLICY [ IF NOT EXISTS ] policy_name { { privilege_audit_clause | access_audit_clause } [ filter_group_clause ] [ ENABLED | DISABLED ] }; where privilege_audit_clause can be: PRIVILEGES { DDL | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] where access_audit_clause can be: ACCESS { DML | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] where filter_group_clause can be: FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } where DDL can be: { ( ALTER | ANALYZE | COMMENT | CREATE | DROP | GRANT | REVOKE | SET | SHOW | LOGIN_ACCESS | LOGIN_FAILURE | LOGOUT | LOGIN ) } where DML can be: { ( COPY | DEALLOCATE | DELETE_P | EXECUTE | REINDEX | INSERT | REPARE | SELECT | TRUNCATE | UPDATE ) } where FILTER_TYPE can be: { APP | ROLES | IP } ``` ## CREATE CLIENT MASTER KEY Creates a CMK object that can be used to encrypt a CEK object. ``` CREATE CLIENT MASTER KEY client_master_key_name [WITH] ( ['KEY_STORE' , 'KEY_PATH' , 'ALGORITHM'] ); ``` ## CREATE COLUMN ENCRYPTION KEY Creates a CEK that can be used to encrypt a specified column in a table. ``` CREATE COLUMN ENCRYPTION KEY column_encryption_key_name [WITH] [VALUES] ( ['CLIENT_MASTER_KEY' , 'ALGORITHM'] ); ``` ## CREATE DATA SOURCE Creates an external data source, which defines the information about the database that openGauss will connect to. ``` CREATE DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS (optname 'optvalue' [, ...])]; Valid optname are: DSN, USERNAME, PASSWORD, ENCODING ``` ## CREATE DATABASE Creates a database. By default, the new database will be created only by cloning the standard system database **template0**. ``` CREATE DATABASE database_name [ [ WITH ] {[ OWNER [=] user_name ]| [ TEMPLATE [=] template ]| [ ENCODING [=] encoding ]| [ LC_COLLATE [=] lc_collate ]| [ LC_CTYPE [=] lc_ctype ]| [ DBCOMPATIBILITY [=] compatibility_type ]| [ TABLESPACE [=] tablespace_name ]| [ CONNECTION LIMIT [=] connlimit ]}[...] ]; ``` ## CREATE DIRECTORY Creates a directory. The directory defines an alias for a path in the server file system and is used to store data files used by users. ``` CREATE [OR REPLACE] DIRECTORY directory_name AS 'path_name'; ``` ## CREATE EXTENSION Installs an extension. ``` CREATE EXTENSION [ IF NOT EXISTS ] extension_name [ WITH ] [ SCHEMA schema_name ] [ VERSION version ] [ FROM old_version ]; ``` ## CREATE FOREIGN TABLE Creates a foreign table. ``` CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( { column_name type_name POSITION(offset,length) [column_constraint ] | LIKE source_table | table_constraint } [, ...] ) SEVER gsmpp_server OPTIONS ( { option_name ' value ' } [, ...] ) [ { WRITE ONLY | READ ONLY }] [ WITH error_table_name | LOG INTO error_table_name] [REMOTE LOG 'name'] [PER NODE REJECT LIMIT 'value'] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ]; CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( { column_name type_name [ { [CONSTRAINT constraint_name] NULL | [CONSTRAINT constraint_name] NOT NULL | column_constraint [...]} ] | table_constraint} [, ...] ) SERVER server_name OPTIONS ( { option_name ' value ' } [, ...] ) DISTRIBUTE BY {ROUNDROBIN | REPLICATION} [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] [ PARTITION BY ( column_name ) [AUTOMAPPED]] ; CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( [ { column_name type_name | LIKE source_table } [, ...] ] ) SERVER server_name OPTIONS ( { option_name ' value ' } [, ...] ) [ READ ONLY ] [ DISTRIBUTE BY {ROUNDROBIN} ] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ]; where column_constraint can be: [CONSTRAINT constraint_name] {PRIMARY KEY | UNIQUE} [NOT ENFORCED [ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION] | ENFORCED] where table_constraint can be: [CONSTRAINT constraint_name] {PRIMARY KEY | UNIQUE} (column_name) [NOT ENFORCED [ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION] | ENFORCED] ``` ## CREATE FUNCTION Creates a function. ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ]} [, ...] ] ) [ RETURNS rettype [ DETERMINISTIC ] | RETURNS TABLE ( { column_name column_type } [, ...] )] LANGUAGE lang_name [ {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | [ NOT ] LEAKPROOF | WINDOW | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | {FENCED | NOT FENCED} | {PACKAGE} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } ] [...] { AS 'definition' | AS 'obj_file', 'link_symbol' } CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ DETERMINISTIC ] [ {IMMUTABLE | STABLE | VOLATILE } | {SHIPPABLE | NOT SHIPPABLE} | {PACKAGE} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } ][...] { IS | AS } plsql_body / ``` ## CREATE GROUP Creates a user group. ``` CREATE GROUP group_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; where option can be: {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_group_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN role_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## CREATE INDEX Create an index on a specified table. ``` CREATE [ UNIQUE ] INDEX [ [schema_name.] index_name ] ON table_name [ USING method ] ({ { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ WHERE predicate ]; CREATE [ UNIQUE ] INDEX [ [schema_name.] index_name ] ON table_name [ USING method ] ( {{ column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ WITH ( { storage_parameter = value } [, ...] ) ] [ TABLESPACE tablespace_name ]; ``` ## CREATE LANGUAGE Defines a new procedural language. A standalone or centralized system does not support creating procedural languages. ``` CREATE [ UNIQUE ] INDEX [ [schema_name.] index_name ] ON table_name [ USING method ] ({ { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ WHERE predicate ]; CREATE [ UNIQUE ] INDEX [ [schema_name.] index_name ] ON table_name [ USING method ] ( {{ column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ WITH ( { storage_parameter = value } [, ...] ) ] [ TABLESPACE tablespace_name ]; openGauss=# \h CREATE LANGUAGE Command: CREATE LANGUAGE Description: define a new procedural language Syntax: CREATE [ OR REPLACE ] [ PROCEDURAL ] LANGUAGE name; CREATE [ OR REPLACE ] [ TRUSTED ] [ PROCEDURAL ] LANGUAGE name HANDLER call_handler [ INLINE inline_handler ] [ VALIDATOR valfunction ]; ``` ## CREATE MASKING POLICY Creates a masking policy. ``` CREATE MASKING POLICY policy_name masking_clause [, ... ] [ policy_filter_clause ] [ ENABLE | DISABLE ]; where masking_clause can be: masking_function ON LABEL(label_name [, ... ]) where masking_function can be: { maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking } where policy_filter_clause can be: FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } where FILTER_TYPE can be: { APP | ROLES | IP } ``` ## CREATE MATERIALIZED VIEW Creates a complete-refresh materialized view that can be refreshed by using **REFRESH MATERIALIZED VIEW** to refresh the data in the materialized view. ``` CREATE [ INCREMENTAL ] MATERIALIZED VIEW table_name [ (column_name [, ...] ) ] [ TABLESPACE tablespace_name ] AS query ``` ## CREATE MODEL Trains a machine learning model and saves the model. ``` CREATE MODEL model_name USING algorithm_name [FEATURES { {expression [ [ AS ] output_name ]} [, ...] }] [TARGET { {expression [ [ AS ] output_name ]} [, ...] }] FROM { table_name | select_query } WITH hyperparameter_name = { hyperparameter_value | DEFAULT } [, ...] } ``` ## CREATE OPERATOR Defines a new operator. ``` CREATE OPERATOR name ( PROCEDURE = function_name [, LEFTARG = left_type ] [, RIGHTARG = right_type ] [, COMMUTATOR = com_op ] [, NEGATOR = neg_op ] [, RESTRICT = res_proc ] [, JOIN = join_proc ] [, HASHES ] [, MERGES ] ) ``` ## CREATE PACKAGE Creates a package. ``` CREATE [ OR REPLACE ] PACKAGE [ schema ] package_name [ invoker_rights_clause ] { IS | AS } item_list_1 END package_name; ``` ## CREATE PROCEDURE Creates a stored procedure. ``` CREATE [ OR REPLACE ] PACKAGE [ schema ] package_name [ invoker_rights_clause ] { IS | AS } item_list_1 END package_name; openGauss=# \h CREATE PROCEDURE Command: CREATE PROCEDURE Description: create a procedure Syntax: CREATE [ OR REPLACE ] PROCEDURE procedure_name [ ( {[ argmode ] [ argname ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] { IS | AS } plsql_body / ``` ## CREATE RESOURCE LABEL Creates a resource label. ``` CREATE RESOURCE LABEL [ IF NOT EXISTS ] label_name ADD label_item_list[ , ... ]; where label_item_list can be: resource_type(resource_path[, ... ]) where resource_type can be: { TABLE | COLUMN | SCHEMA | VIEW | FUNCTION } ``` ## CREATE RESOURCE POOL Creates a resource pool and specifies the Cgroup of the resource pool. ``` CREATE RESOURCE POOL pool_name [WITH ({MEM_PERCENT=pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='priority' | nodegroup='nodegroup_name' | is_foreign = boolean }[, ... ])]; ``` ## CREATE ROLE Creates a role. ``` CREATE ROLE role_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; where option can be: {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN role_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## CREATE ROW LEVEL SECURITY POLICY Creates a row-level access control policy for a table. ``` CREATE [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ AS { PERMISSIVE | RESTRICTIVE } ] [ FOR { ALL | SELECT | UPDATE | DELETE } ] [ TO { role_name | PUBLIC } [, ...] ] USING ( using_expression ) ``` ## CREATE SCHEMA Creates a schema. ``` CREATE SCHEMA schema_name [ AUTHORIZATION user_name ] [WITH BLOCKCHAIN] [ schema_element [ ... ] ]; ``` ## CREATE SEQUENCE Aadds a sequence to the current database. The owner of the sequence is the user who creates it. ``` CREATE SEQUENCE name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE] [ MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE] [ GLOBAL | SESSION ] [ OWNED BY { table_name.column_name | NONE } ]; ``` ## CREATE SERVER Defines a new foreign server. ``` CREATE SERVER server_name FOREIGN DATA WRAPPER fdw_name OPTIONS ( { option_name ' value ' } [, ...] ) ; ``` ## CREATE SYNONYM Creates a synonym object. A synonym is an alias of a database object and is used to record the mapping between database object names. You can use synonyms to access associated database objects. ``` CREATE [ OR REPLACE ] [ PUBLIC ] SYNONYM synonym_name FOR object_name; ``` ## CREATE TABLE Creates an empty table in the current database. The table will be owned by the creator. ``` CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] [encrypted with ('column_encryption_key', 'encryption_type')] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ]) [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ]; where column_constraint can be: [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED ALWAYS AS ( generation_expr ) STORED | UNIQUE index_parameters | PRIMARY KEY index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where table_constraint can be: [ CONSTRAINT constraint_name ] { CHECK ( expression ) | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where compress_mode can be: { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } where like_option can be: { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | PARTITION | RELOPTIONS | DISTRIBUTION | ALL } where index_parameters can be: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## CREATE TABLE AS Creates a table from the results of a query. ``` CREATE [ UNLOGGED ] TABLE table_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ DISTRIBUTE BY { REPLICATION | { [HASH ] ( column_name ) } } ] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] AS query [ WITH [ NO ] DATA ]; ``` ## CREATE TABLE PARTITION Creates a partitioned table. Partitioning refers to splitting what is logically one large table into smaller physical pieces based on specific schemes. The table based on the logic is called a partitioned table, and each physical piece is called a partition. A partitioned table is a logical table and does not store data. Data is stored in physical partitions. ``` CREATE TABLE [ IF NOT EXISTS ] partition_table_name ( [ { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ] ] ) [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ DISTRIBUTE BY { REPLICATION | { [ HASH ] ( column_name ) } } ] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] PARTITION BY { {VALUES (partition_key)} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN ( tablespace_name [, ... ] ) ] ] ( partition_less_than_item [, ... ] )} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN ( tablespace_name [, ... ] ) ] ] ( partition_start_end_item [, ... ] )} | {LIST | HASH (partition_key) (PARTITION partition_name [VALUES (list_values_clause)] opt_table_space )} NOTICE: LIST/HASH partition is only available in CENTRALIZED mode! } [ { ENABLE | DISABLE } ROW MOVEMENT ]; where column_constraint can be: [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED ALWAYS AS ( generation_expr ) STORED | UNIQUE index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where table_constraint can be: [ CONSTRAINT constraint_name ] { CHECK ( expression ) | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters | FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where index_parameters can be: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] where like_option can be: { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS | DISTRIBUTION | ALL } where partition_less_than_item can be: PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } ) [TABLESPACE tablespace_name] where partition_start_end_item can be: PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` ## CREATE TABLE INHERITS Creates a tablespace in a database. ``` CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] TABLE inherit_table_name( [ {LIKE fathername} [INCLUDING ALL]} ] ) [ INHERITS ( parent_table [, ... ] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ]; ``` ## CREATE TABLESPACE Creates a tablespace in a database. ``` CREATE TABLESPACE tablespace_name [ OWNER user_name ] [ RELATIVE ] LOCATION 'directory' [ MAXSIZE 'space_size' ] [with_option_clause]; where option_clause can be: WITH ( filesystem= { 'systemtype '| " systemtype " | systemtype } [ { , address = { ' ip:port [ , ... ] ' | " ip:port [ , ... ] "} } ] , cfgpath = { 'path '| " path " } ,storepath = { 'rootpath '| " rootpath "} [{, random_page_cost = { 'value '| " value " | value }}] [{,seq_page_cost = { 'value '| " value " | value }}]) ``` ## CREATE TEXT SEARCH CONFIGURATION Creates a text search configuration. A text search configuration specifies a text search parser that can divide a string into tokens, plus dictionaries that can be used to determine which tokens are of interest for searching. ``` CREATE TEXT SEARCH CONFIGURATION name ( PARSER = parser_name | COPY = source_config ) [ WITH ( {configuration_option = value} [, ...] )]; ``` ## CREATE TEXT SEARCH DICTIONARY Deletes a full-text retrieval dictionary. ``` CREATE TEXT SEARCH DICTIONARY name ( TEMPLATE = template_name | COPY = source_config [, option = value [, ...] ] ); ``` ## CREATE TRIGGER Creates a trigger. The trigger will be associated with the specified table or view, and will execute the specified functions under certain conditions. ``` CREATE [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] } ON table_name [ FROM referenced_table_name ] { NOT DEFERRABLE | [ DEFERRABLE ] { INITIALLY IMMEDIATE | INITIALLY DEFERRED } } [ FOR [ EACH ] { ROW | STATEMENT } ] [ WHEN ( condition ) ] EXECUTE PROCEDURE function_name ( arguments ) where event can be one of: INSERT UPDATE [ OF column_name [, ... ] ] DELETE TRUNCATE ``` ## CREATE TYPE Defines a new data type for use in the current database. The user who defines a type becomes its owner. Types are designed only for row-store tables. ``` CREATE TYPE name AS ( [ attribute_name data_type [ COLLATE collation ] [, ... ] ] ) CREATE TYPE name AS ENUM ( [ 'label' [, ... ] ] ) CREATE TYPE name ( INPUT = input_function, OUTPUT = output_function [ , RECEIVE = receive_function ] [ , SEND = send_function ] [ , TYPMOD_IN = type_modifier_input_function ] [ , TYPMOD_OUT = type_modifier_output_function ] [ , ANALYZE = analyze_function ] [ , INTERNALLENGTH = { internallength | VARIABLE } ] [ , PASSEDBYVALUE ] [ , ALIGNMENT = alignment ] [ , STORAGE = storage ] [ , LIKE = like_type ] [ , CATEGORY = category ] [ , PREFERRED = preferred ] [ , DEFAULT = default ] [ , ELEMENT = element ] [ , DELIMITER = delimiter ] [ , COLLATABLE = collatable ] ) CREATE TYPE name ``` ## CREATE USER Creates a user. ``` CREATE USER user_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; where option can be: {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN role_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## CREATE VIEW Creates a view. ``` CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW view_name [ ( column_name [, ...] ) ] [ WITH ( {view_option_name [= view_option_value]} [, ... ] ) ] AS query; ``` ## CREATE WEAK PASSWORD DICTIONARY Inserts one or more weak passwords into the **gs\_global\_config** table. ``` CREATE WEAK PASSWORD DICTIONARY [WITH VALUES] ( {'weak_password'} [, ...] ); ``` ## CURSOR Defines a cursor to retrieve a small number of rows out of a large query. ``` CURSOR cursor_name [ BINARY ] [ INSENSITIVE ] [ [ NO ] SCROLL ] FOR query ; ``` ## DEALLOCATE Deallocates a previously prepared statement. If you do not explicitly deallocate a prepared statement, it is deallocated when the session ends. ``` DEALLOCATE [ PREPARE ] { name | ALL }; ``` ## DECLARE Deallocates a previously prepared statement. If you do not explicitly deallocate a prepared statement, it is deallocated when the session ends. ``` 1. declare a cursor: DECLARE cursor_name [ BINARY ] [ NO SCROLL ] CURSOR [ { WITH | WITHOUT } HOLD ] FOR query ; 2. start an anonymous block: [DECLARE [declare_statements]] BEGIN execution_statements END; / ``` ## DELETE Deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, it will delete all rows in the table. The result is a valid, but an empty table. ``` [ WITH [ RECURSIVE ] with_query [, ...] ] DELETE [/*+ plan_hint */] FROM [ ONLY ] table_name [ * ] [ [ AS ] alias ] [ USING using_list ] [ WHERE condition | WHERE CURRENT OF cursor_name ] [ LIMIT row_count ] [ RETURNING { * | { output_expr [ [ AS ] output_name ] } [, ...] } ]; ``` ## DO Executes an anonymous code block. ``` DO [ LANGUAGE lang_name ] code; ``` ## DROP AUDIT POLICY Deletes an audit policy. ``` DROP AUDIT POLICY [IF EXISTS] policy_name; ``` ## DROP CLIENT MASTER KEY Deletes a CMK. ``` DROP CLIENT MASTER KEY [ IF EXISTS ] client_master_key_name [, ...]; ``` ## DROP COLUMN ENCRYPTION KEY Deletes a CEK. ``` DROP COLUMN ENCRYPTION KEY [ IF EXISTS ] client_column_key_name [, ...]; ``` ## DROP DATA SOURCE Deletes a data source. ``` DROP DATA SOURCE [IF EXISTS] src_name [CASCADE | RESTRICT]; ``` ## DROP DATABASE Deletes a database. ``` DROP DATABASE [ IF EXISTS ] database_name; ``` ## DROP DIRECTORY Deletes a directory. ``` DROP DIRECTORY [ IF EXISTS ] directory_name; ``` ## DROP EXTENSION Deletes an extension. ``` DROP EXTENSION [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP FOREIGN TABLE Deletes a foreign table. ``` DROP FOREIGN TABLE [ IF EXISTS ] table_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP FUNCTION Deletes a function. ``` DROP FUNCTION [ IF EXISTS ] function_name [ ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) [ CASCADE | RESTRICT ] ]; ``` ## DROP GROUP Deletes a user group. ``` DROP GROUP [ IF EXISTS ] group_name [, ...]; ``` ## DROP INDEX Deletes an index. ``` DROP INDEX [ IF EXISTS ] index_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP MASKING POLICY Deletes a masking policy. ``` DROP MASKING POLICY [IF EXISTS] policy_name; ``` ## DROP MATERIALIZED VIEW Forcibly deletes an existing materialized view from the database. ``` DROP MATERIALIZED VIEW [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ] ``` ## DROP MODEL Deletes a model that has been trained and saved. ``` DROP MODEL model_name; ``` ## DROP OPERATOR Not supported in openGauss currently. ``` DROP OPERATOR [ IF EXISTS ] name ( { left_type | NONE } , { right_type | NONE } ) [ CASCADE | RESTRICT ] ``` ## DROP OWNED Deletes the database objects owned by a database role. ``` DROP OWNED BY name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP PACKAGE Deletes a package or package body. ``` DROP PACKAGE [ IF EXISTS ] package_name; ``` ## DROP PROCEDURE Deletes a stored procedure. ``` DROP PROCEDURE [ IF EXISTS ] procedure_name; ``` ## DROP RESOURCE LABEL Deletes a resource label. ``` DROP RESOURCE LABEL [ IF EXISTS ] policy_name[, ... ]; ``` ## DROP RESOURCE POOL Deletes a resource pool. ``` DROP RESOURCE POOL [ IF EXISTS ] pool_name; ``` ## DROP ROLE Deletes a role. ``` DROP ROLE [ IF EXISTS ] role_name [, ...]; ``` ## DROP ROW LEVEL SECURITY POLICY Deletes a row-level access control policy from a table. ``` DROP [ ROW LEVEL SECURITY ] POLICY [ IF EXISTS ] policy_name ON table_name [ CASCADE | RESTRICT ] ``` ## DROP SCHEMA Deletes a schema from the current database. ``` DROP SCHEMA [ IF EXISTS ] schema_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP SEQUENCE Deletes a sequence from the current database. ``` DROP SEQUENCE [ IF EXISTS ] {[schema.]sequence_name} [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP SERVER Deletes a data server. ``` DROP SERVER [ IF EXISTS ] server_name [ { CASCADE | RESTRICT } ] ; ``` ## DROP SYNONYM Deletes a synonym. ``` DROP [ PUBLIC ] SYNONYM [ IF EXISTS ] synonym_name [ CASCADE | RESTRICT ]; ``` ## DROP TABLE Deletes a table. ``` DROP TABLE [ IF EXISTS ] {[schema.]table_name} [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP TABLESPACE Deletes a tablespace. ``` DROP TABLESPACE [ IF EXISTS ] tablespace_name; ``` ## DROP TEXT SEARCH CONFIGURATION Deletes a text search configuration. ``` DROP TEXT SEARCH CONFIGURATION [ IF EXISTS ] name [ CASCADE | RESTRICT ] ``` ## DROP TEXT SEARCH DICTIONARY Deletes a full-text retrieval dictionary. ``` DROP TEXT SEARCH DICTIONARY [ IF EXISTS ] name [ CASCADE | RESTRICT ]; ``` ## DROP TRIGGER Deletes a trigger. ``` DROP TRIGGER [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ] ``` ## DROP TYPE Deletes a user-defined data type. ``` DROP TYPE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ] ``` ## DROP USER Deletes a user and the schema with the same name as the user. ``` DROP USER [ IF EXISTS ] user_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP VIEW Forcibly deletes a view from the database. ``` DROP VIEW [ IF EXISTS ] view_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP WEAK PASSWORD DICTIONARY Clears all weak passwords in **gs\_global\_config**. ``` DROP WEAK PASSWORD DICTIONARY; ``` ## END Commits all operations of a transaction. ``` END [ WORK | TRANSACTION ] ``` ## EXECUTE Executes a prepared statement. Because a prepared statement exists only in the lifetime of the session, the prepared statement must be created earlier in the current session by using the **PREPARE** statement. ``` EXECUTE name [ ( parameter [, ...] ) ]; ``` ## EXECUTE DIRECT Executes an SQL statement on a specified node. Generally, the cluster automatically allocates an SQL statement to proper nodes. **EXECUTE DIRECT** is mainly used for database maintenance and testing. ``` EXPLAIN [ ( option [, ...] ) ] statement; EXPLAIN { [ { ANALYZE | ANALYSE } ] [ VERBOSE ] | PERFORMANCE } statement; where option can be: ANALYZE [ boolean ] | ANALYSE [ boolean ] | VERBOSE [ boolean ] | COSTS [ boolean ] | CPU [ boolean ] | DETAIL [ boolean ] | NODES [ boolean ] | NUM_NODES [ boolean ] | BUFFERS [ boolean ] | TIMING [ boolean ] | PLAN [ boolean ] | FORMAT { TEXT | XML | JSON | YAML } openGauss=# \h EXECUTE DIRECT Command: EXECUTE DIRECT Description: launch queries directly to dedicated nodes Syntax: EXECUTE DIRECT ON ( nodename [, ... ] ) query; EXECUTE DIRECT ON { COORDINATORS | DATANODES | ALL } query; ``` ## EXPLAIN Shows the execution plan of an SQL statement. ``` EXPLAIN [ ( option [, ...] ) ] statement; EXPLAIN { [ { ANALYZE | ANALYSE } ] [ VERBOSE ] | PERFORMANCE } statement; where option can be: ANALYZE [ boolean ] | ANALYSE [ boolean ] | VERBOSE [ boolean ] | COSTS [ boolean ] | CPU [ boolean ] | DETAIL [ boolean ] | NODES [ boolean ] | NUM_NODES [ boolean ] | BUFFERS [ boolean ] | TIMING [ boolean ] | PLAN [ boolean ] | FORMAT { TEXT | XML | JSON | YAML } ``` ## FETCH Retrieves rows using a previously created cursor. ``` FETCH [ direction { FROM | IN } ] cursor_name; where direction can be: NEXT | PRIOR | FIRST | LAST | ABSOLUTE count | RELATIVE count | count | ALL | FORWARD | FORWARD count | FORWARD ALL | BACKWARD | BACKWARD count | BACKWARD ALL ``` ## GRANT Grants permissions to roles and users. ``` GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON { [ TABLE ] table_name [, ...] | ALL TABLES IN SCHEMA schema_name [, ...] } TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { {{ SELECT | INSERT | UPDATE | REFERENCES | COMMENT } ( column_name [, ...] )} [, ...] | ALL [ PRIVILEGES ] ( column_name [, ...] ) } ON [ TABLE ] table_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON { [ SEQUENCE ] sequence_name [, ...] | ALL SEQUENCES IN SCHEMA schema_name [, ...] } TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { CREATE | CONNECT | TEMPORARY | TEMP | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON DATABASE database_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { USAGE | ALL [ PRIVILEGES ] } ON DOMAIN domain_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEY client_master_key TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEY column_encryption_key TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { USAGE | ALL [ PRIVILEGES ] } ON FOREIGN DATA WRAPPER fdw_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FOREIGN SERVER server_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON { FUNCTION {function_name ( [ {[ argmode ] [ arg_name ] arg_type} [, ...] ] )} [, ...] | ALL FUNCTIONS IN SCHEMA schema_name [, ...] } TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { USAGE | ALL [ PRIVILEGES ] } ON LANGUAGE lang_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { CREATE | USAGE | COMPUTE | ALTER | DROP } [, ...] | ALL [ PRIVILEGES ] } ON NODE GROUP group_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { SELECT | UPDATE } [, ...] | ALL [ PRIVILEGES ] } ON LARGE OBJECT loid [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { CREATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SCHEMA schema_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { CREATE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TABLESPACE tablespace_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPE type_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { USAGE | ALL [PRIVILEGES] } ON DATA SOURCE src_name [, ...] TO { [GROUP] role_name | PUBLIC } [, ...] [WITH GRANT OPTION]; GRANT { { READ | WRITE } [, ...] | ALL [PRIVILEGES] } ON DIRECTORY directory_name [, ...] TO { [GROUP] role_name | PUBLIC } [, ...] [WITH GRANT OPTION]; GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON PACKAGE package_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT role_name [, ...] TO role_name [, ...] [ WITH ADMIN OPTION ]; GRANT ALL { PRIVILEGES | PRIVILEGE } TO role_name; ``` ## INSERT Inserts new rows into a table. ``` [ WITH [ RECURSIVE ] with_query [, ...] ] INSERT [/*+ plan_hint */] INTO table_name [ ( column_name [, ...] ) ] { DEFAULT VALUES | VALUES {( { expression | DEFAULT } [, ...] ) }[, ...] | query } [ ON CONFLICT [ conflict_target ] conflict_action ] [ ON DUPLICATE KEY UPDATE { NOTHING | { column_name = { expression | DEFAULT } } [, ...] } ] [ RETURNING {* | {output_expression [ [ AS ] output_name ] }[, ...]} ]; ``` ## LOCK Obtains a table-level lock. ``` LOCK [ TABLE ] {[ ONLY ] name [, ...]| {name [ * ]} [, ...]} [ IN {ACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE | SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVE} MODE ] [ NOWAIT ]; ``` ## MERGE INTO Conditionally matches data in a target table with that in a source table. If data matches, **UPDATE** is executed on the target table; if data does not match, **INSERT** is executed. You can use this syntax to run **UPDATE** and **INSERT** at a time for convenience ``` MERGE [/*+ plan_hint */] INTO table_name [ [ AS ] alias ] USING { { table_name | view_name } | subquery } [ [ AS ] alias ] ON ( condition ) [ WHEN MATCHED THEN UPDATE SET { column_name = { expression | DEFAULT } | ( column_name [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...] [ WHERE condition ] ] [ WHEN NOT MATCHED THEN INSERT { DEFAULT VALUES | [ ( column_name [, ...] ) ] VALUES ( { expression | DEFAULT } [, ...] ) [, ...] [ WHERE condition ] } ]; ``` ## MOVE Repositions a cursor without retrieving any data. **MOVE** works exactly like the **FETCH** command, except it only positions the cursor and does not return rows. ``` MOVE [ direction [ FROM | IN ] ] cursor_name; where direction can be: NEXT | PRIOR | FIRST | LAST | ABSOLUTE count | RELATIVE count | count | ALL | FORWARD | FORWARD count | FORWARD ALL | BACKWARD | BACKWARD count | BACKWARD ALL ``` ## PREPARE Creates a prepared statement. ``` PREPARE name [ ( data_type [, ...] ) ] AS statement; ``` ## PREPARE TRANSACTION Prepares the current transaction for two-phase commit. ``` PREPARE TRANSACTION transaction_id; ``` ## REASSIGN OWNED Changes the owner of the database object. ``` REASSIGN OWNED BY old_role [, ...] TO new_role; ``` ## REFRESH MATERIALIZED VIEW Refreshes a materialized view in complete refresh mode. ``` REFRESH [ INCREMENTAL ] MATERIALIZED VIEW name ``` ## REINDEX Rebuilds an index using the data stored in the index's table, replacing the old copy of the index. ``` REINDEX { INDEX | [INTERNAL] TABLE | DATABASE | SYSTEM } name [ FORCE ]; REINDEX { INDEX | [INTERNAL] TABLE } name PARTITION partition_name [ FORCE ]; ``` ## RESET Restores run-time parameters to their default values. The default values are defined in the **postgresql.conf** configuration file. ``` RESET {configuration_parameter | CURRENT_SCHEMA | TIME ZONE | TRANSACTION ISOLATION LEVEL | SESSION AUTHORIZATION | ALL }; ``` ## REVOKE Revokes permissions from one or more roles. ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON { [ TABLE ] table_name [, ...] | ALL TABLES IN SCHEMA schema_name [, ...] } FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { {{ SELECT | INSERT | UPDATE | REFERENCES | COMMENT } ( column_name [, ...] )} [, ...] | ALL [ PRIVILEGES ] ( column_name [, ...] ) } ON [ TABLE ] table_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON { [ SEQUENCE ] sequence_name [, ...] | ALL SEQUENCES IN SCHEMA schema_name [, ...] } FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { CREATE | CONNECT | TEMPORARY | TEMP | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON DATABASE database_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { USAGE | ALL [ PRIVILEGES ] } ON DOMAIN domain_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [PRIVILEGES] } ON CLIENT_MASTER_KEYS client_master_keys_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [PRIVILEGES]} ON COLUMN_ENCRYPTION_KEYS column_encryption_keys_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { READ | WRITE } [, ...] | ALL [ PRIVILEGES ] } ON DIRECTORY directory_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { USAGE | ALL [ PRIVILEGES ] } ON FOREIGN DATA WRAPPER fdw_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FOREIGN SERVER server_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON { FUNCTION {function_name ( [ {[ argmode ] [ arg_name ] arg_type} [, ...] ] )} [, ...] | ALL FUNCTIONS IN SCHEMA schema_name [, ...] } FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { USAGE | ALL [ PRIVILEGES ] } ON LANGUAGE lang_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { {CREATE | USAGE | COMPUTE | ALTER | DROP } [, ...] | ALL [ PRIVILEGES ] } ON NODE GROUP group_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE } [, ...] | ALL [ PRIVILEGES ] } ON LARGE OBJECT loid [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { CREATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SCHEMA schema_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { CREATE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TABLESPACE tablespace_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPE type_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { USAGE | ALL [ PRIVILEGES ] } ON DATA SOURCE src_name [, ...] FROM { [GROUP] role_name | PUBLIC } [, ...]; REVOKE [ GRANT OPTION FOR ] { { READ | WRITE } [, ...] | ALL [ PRIVILEGES ] } ON DIRECTORY directory_name [, ...] FROM { [GROUP] role_name | PUBLIC } [, ...]; REVOKE [ GRANT OPTION FOR ] { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON PACKAGE package_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ ADMIN OPTION FOR ] role_name [, ...] FROM role_name [, ...] [ CASCADE | RESTRICT ]; REVOKE ALL { PRIVILEGES | PRIVILEGE } FROM role_name; ``` ## ROLLBACK Rolls back the current transaction and backs out all updates in the transaction. ``` ROLLBACK [ WORK | TRANSACTION ]; ``` ## ROLLBACK PREPARED Prepares the current transaction for two-phase commit. ``` ROLLBACK PREPARED transaction_id; ``` ## SAVEPOINT Establishes a new savepoint within the current transaction. ``` SAVEPOINT savepoint_name; ``` ## SELECT Retrieves data from a table or view. ``` [ WITH [ RECURSIVE ] with_query [, ...] ] SELECT [/*+ plan_hint */] [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] { * | {expression [ [ AS ] output_name ]} [, ...] } [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY grouping_element [, ...] ] [ HAVING condition [, ...] ] [ WINDOW {window_name AS ( window_definition )} [, ...] ] [ { UNION | INTERSECT | EXCEPT | MINUS } [ ALL | DISTINCT ] select ] [ ORDER BY {expression [ [ ASC | DESC | USING operator ] | nlssort_expression_clause ] [ NULLS { FIRST | LAST } ]} [, ...] ] [ LIMIT { [offset,] count | ALL } ] [ OFFSET start [ ROW | ROWS ] ] [ FETCH { FIRST | NEXT } [ count ] [ PERCENT ] { ROW | ROWS } { ONLY | WITH TIES } ] [ {FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ]} [...] ]; TABLE { ONLY {(table_name)| table_name} | table_name [ * ]}; where from_item can be: [ ONLY ] table_name [ * ] [ partition_clause ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ] [ TABLESAMPLE sampling_method ( argument [, ...] ) [ REPEATABLE ( seed ) ] ] |( select ) [ AS ] alias [ ( column_alias [, ...] ) ] |with_query_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ] |function_name ( [ argument [, ...] ] ) [ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ] |function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] ) |from_item [ NATURAL ] join_type from_item [ ON join_condition | USING ( join_column [, ...] ) ] where grouping_element can be: () |expression |( expression [, ...] ) |ROLLUP ( { expression | ( expression [, ...] ) } [, ...] ) |CUBE ( { expression | ( expression [, ...] ) } [, ...] ) |GROUPING SETS ( grouping_element [, ...] ) where with_query can be: with_query_name [ ( column_name [, ...] ) ] AS ( {select | values | insert | update | delete} ) where partition_clause can be: PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } where nlssort_expression_clause can be: NLSSORT ( column_name, ' NLS_SORT = { SCHINESE_PINYIN_M | generic_m_ci } ' ) ``` ## SELECT INTO Defines a new table based on a query result and inserts data obtained by query to the new table. ``` [ WITH [ RECURSIVE ] with_query [, ...] ] SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] { * | {expression [ [ AS ] output_name ]} [, ...] } INTO [ UNLOGGED ] [ TABLE ] new_table [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY expression [, ...] ] [ HAVING condition [, ...] ] [ WINDOW {window_name AS ( window_definition )} [, ...] ] [ { UNION | INTERSECT | EXCEPT | MINUS } [ ALL | DISTINCT ] select ] [ ORDER BY {expression [ [ ASC | DESC | USING operator ] | nlssort_expression_clause ] [ NULLS { FIRST | LAST } ]} [, ...] ] [ LIMIT { count | ALL } ] [ OFFSET start [ ROW | ROWS ] ] [ FETCH { FIRST | NEXT } [ count ] [ PERCENT ] { ROW | ROWS } { ONLY | WITH TIES } ] [ {FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ]} [...] ]; ``` ## SET Modifies a run-time parameter. ``` SET [ LOCAL | SESSION ] { {config_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }}}; SET [ SESSION | LOCAL ] TIME ZONE { timezone | LOCAL | DEFAULT }; SET [ SESSION | LOCAL ] NAMES encoding_name; SET [ SESSION | LOCAL ] {CURRENT_SCHEMA { TO | = } { schema | DEFAULT } | SCHEMA 'schema'}; SET [ SESSION | LOCAL ] XML OPTION { DOCUMENT | CONTENT }; ``` ## SET CONSTRAINTS Sets a constraint for checking the current transaction. ``` SET CONSTRAINTS { ALL | name [, ...] } { DEFERRED | IMMEDIATE }; ``` ## SET ROLE Sets the current user identifier of the current session. ``` SET [ SESSION | LOCAL ] ROLE role_name PASSWORD 'password'; RESET ROLE; ``` ## SET SESSION AUTHORIZATION Sets the session user identifier and the current user identifier of the current SQL session to a specified user. ``` SET [ SESSION | LOCAL ] SESSION AUTHORIZATION role_name PASSWORD 'password'; {SET [ SESSION | LOCAL ] SESSION AUTHORIZATION DEFAULT | RESET SESSION AUTHORIZATION}; ``` ## SET TRANSACTION Sets constraints for checking the current transaction. ``` {SET [ LOCAL ] TRANSACTION|SET SESSION CHARACTERISTICS AS TRANSACTION} { ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED } | { READ WRITE | READ ONLY | SERIALIZABLE | REPEATABLE READ } } [, ...] SET TRANSACTION SNAPSHOT snapshot_id; ``` ## SHOW Sows the current value of a run-time parameter. ``` SHOW { configuration_parameter | CURRENT_SCHEMA | TIME ZONE | TRANSACTION ISOLATION LEVEL | SESSION AUTHORIZATION | ALL }; ``` ## START TRANSACTION Starts a transaction. If the isolation level or read/write mode is specified, a new transaction will have those characteristics. You can also specify them using **SET TRANSACTION**. ``` START TRANSACTION [ { ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED } | { READ WRITE | READ ONLY | SERIALIZABLE | REPEATABLE READ } } [, ...] ]; ``` ## TRUNCATE Quickly removes all rows from a database table. ``` TRUNCATE [ TABLE ] [ ONLY ] {table_name [ * ]} [, ... ] [ CONTINUE IDENTITY ] [ CASCADE | RESTRICT ]; ALTER TABLE [ IF EXISTS ] { [ ONLY ] table_name | table_name * | ONLY ( table_name ) } TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } ; ``` ## UPDATE Updates data in a table. Changes the values of the specified columns in all rows that satisfy the condition. The WHERE clause clarifies conditions. The SET clause specifies the columns to be modified and columns that not specified in the SET clause retain their previous values. ``` UPDATE [/*+ plan_hint */] [ ONLY ] table_name [ * ] [ [ AS ] alias ] SET {column_name = { expression | DEFAULT } | ( column_name [, ...] ) = {( { expression | DEFAULT } [, ...] ) |sub_query } }[, ...] [ FROM from_list] [ WHERE condition ] [ RETURNING {* | {output_expression [ [ AS ] output_name ]} [, ...] }]; ``` ## VACUUM Recycles storage space occupied by rows that have been deleted from a table or B-Tree index. In normal database operation, rows that have been deleted are not physically removed from their table; instead, they remain present until a **VACUUM** is done. Therefore, it is necessary to do **VACUUM** periodically, especially on frequently-updated tables. ``` VACUUM [ ( { FULL | FREEZE | VERBOSE | {ANALYZE | ANALYSE }} [,...] ) ] [ table_name [ (column_name [, ...] ) ] ] [ PARTITION ( partition_name ) ]; VACUUM [ FULL [ COMPACT ] ] [ FREEZE ] [ VERBOSE ] [ table_name ] [ PARTITION ( partition_name ) ]; VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ (column_name [, ...] ) ] ] [ PARTITION ( partition_name ) ]; VACUUM DELTAMERGE [ table_name ]; VACUUM HDFSDIRECTORY [ table_name ]; ``` ## VALUES Computes a row or a set of rows based on given values. It is most commonly used to generate a constant table within a large statement. ``` VALUES {( expression [, ...] )} [, ...] [ ORDER BY {sort_expression [ ASC | DESC | USING operator ]} [, ...] ] [ LIMIT { count | ALL } ] [ OFFSET start [ ROW | ROWS ] ] [ FETCH { FIRST | NEXT } [ count ] [ PERCENT ] { ROW | ROWS } { ONLY | WITH TIES } ]; ``` --- --- url: /en/docs/latest/sql_reference/brief_tutorial/appendix-sql-syntax.md --- # Appendix: SQL Syntax ## ABORT Exits the current transaction. ``` ABORT [ WORK | TRANSACTION ] ; ``` ## ALTER AUDIT POLICY Modifies the unified audit policy. ``` ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ADD | REMOVE } { [ privilege_audit_clause ] [ access_audit_clause ] }; ALTER AUDIT POLICY [ IF EXISTS ] policy_name MODIFY ( filter_group_clause ); ALTER AUDIT POLICY [ IF EXISTS ] policy_name DROP FILTER; ALTER AUDIT POLICY [ IF EXISTS ] policy_name COMMENTS policy_comments; ALTER AUDIT POLICY [ IF EXISTS ] policy_name { ENABLE | DISABLE }; where privilege_audit_clause can be: PRIVILEGES { DDL | ALL } where access_audit_clause can be: ACCESS { DML | ALL } where filter_group_clause can be: FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } where DDL can be: { ( ALTER | ANALYZE | COMMENT | CREATE | DROP | GRANT | REVOKE | SET | SHOW | LOGIN_ACCESS | LOGIN_FAILURE | LOGOUT | LOGIN ) } where DML can be: { ( COPY | DEALLOCATE | DELETE_P | EXECUTE | REINDEX | INSERT | REPARE | SELECT | TRUNCATE | UPDATE ) } ``` ## ALTER DATA SOURCE Modifies the attributes and content of the data source. ``` ALTER DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS ( { [ADD | SET | DROP] optname ['optvalue'] } [, ...] )]; ALTER DATA SOURCE src_name RENAME TO src_new_name; ALTER DATA SOURCE src_name OWNER TO new_owner; Valid optname are: DSN, USERNAME, PASSWORD, ENCODING ``` ## ALTER DATABASE Modifies a database, including its name, owner, connection limitation, and object isolation. ``` ALTER DATABASE database_name [ [ WITH ] CONNECTION LIMIT connlimit ]; ALTER DATABASE database_name RENAME TO new_name; ALTER DATABASE database_name OWNER TO new_owner; ALTER DATABASE database_name SET TABLESPACE new_tablespace; ALTER DATABASE database_name SET configuration_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }; ALTER DATABASE database_name RESET { configuration_parameter | ALL }; ALTER DATABASE database_name [ WITH ] { ENABLE | DISABLE } PRIVATE OBJECT; ``` ## ALTER DEFAULT PRIVILEGES Sets the permissions that will be applied to objects created in the future. (It does not affect permissions granted to existing objects.) ``` ALTER DEFAULT PRIVILEGES [ FOR { ROLE | USER } target_role [, ...] ] [ IN SCHEMA schema_name [, ...] ] abbreviated_grant_or_revoke; where abbreviated_grant_or_revoke can be: grant_on_tables_clause | grant_on_sequences_clause | grant_on_functions_clause | grant_on_types_clause | grant_on_client_master_keys_clause | grant_on_column_encryption_keys_clause | revoke_on_tables_clause | revoke_on_sequences_clause | revoke_on_functions_clause | revoke_on_types_clause | revoke_on_client_master_keys_clause | revoke_on_column_encryption_keys_clause where grant_on_tables_clause can be: GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_sequences_clause can be: GRANT { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_functions_clause can be: GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_types_clause can be: GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_client_master_keys_clause can be: GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where grant_on_column_encryption_keys_clause can be: GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ] where revoke_on_tables_clause can be: REVOKE [ GRANT OPTION FOR ] { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON TABLES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_sequences_clause can be: REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SEQUENCES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_functions_clause can be: REVOKE [ GRANT OPTION FOR ] { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FUNCTIONS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_types_clause can be: REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPES FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_client_master_keys_clause can be: REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] where revoke_on_column_encryption_keys_clause can be: REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEYS FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT | CASCADE CONSTRAINTS ] ``` ## ALTER DIRECTORY Modifies a directory. ``` CREATE [OR REPLACE] DIRECTORY directory_name AS 'path_name'; ``` ## ALTER EXTENSION Modifies an extension. ``` ALTER EXTENSION name UPDATE [ TO new_version ]; ALTER EXTENSION name SET SCHEMA new_schema; ALTER EXTENSION name ADD member_object; ALTER EXTENSION name DROP member_object; where member_object is: FOREIGN TABLE object_name | FUNCTION function_name ( [ [ argmode ] [ argname ] argtype [, ...] ] ) | [ PROCEDURAL ] LANGUAGE object_name | SCHEMA object_name | SERVER object_name | TABLE object_name | TEXT SEARCH CONFIGURATION object_name | TYPE object_name | VIEW object_name ``` ## ALTER FOREIGN TABLE Modifies a foreign table. ``` 1. GDS: ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] tablename OWNER TO new_owner; 2. HDFS: ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] tablename OWNER TO new_owner; ALTER FOREIGN TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ALTER FOREIGN TABLE [ IF EXISTS ] tablename ADD [CONSTRAINT constraint_name] {PRIMARY KEY | UNIQUE} (column_name) [NOT ENFORCED [ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION] | ENFORCED]; ALTER FOREIGN TABLE [ IF EXISTS ] tablename DROP CONSTRAINT constraint_name ; ALTER FOREIGN TABLE [ IF EXISTS ] tablename action [, ... ]; where action can be: ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS integer | ALTER [ COLUMN ] column_name OPTIONS ( {[ ADD | SET | DROP ] option ['value'] } [, ... ]) | MODIFY column_name data_type | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL 3. OBS: ALTER FOREIGN TABLE [ IF EXISTS ] table_name OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] tablename OWNER TO new_owner; ALTER FOREIGN TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ALTER FOREIGN TABLE [ IF EXISTS ] tablename ADD [CONSTRAINT constraint_name] {PRIMARY KEY | UNIQUE} (column_name) [NOT ENFORCED [ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION] | ENFORCED]; ALTER FOREIGN TABLE [ IF EXISTS ] tablename DROP CONSTRAINT constraint_name ; ALTER FOREIGN TABLE [ IF EXISTS ] tablename action [, ... ]; where action can be: ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS integer | ALTER [ COLUMN ] column_name OPTIONS ( {[ ADD | SET | DROP ] option ['value'] } [, ... ]) | MODIFY column_name data_type | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL 4. GC: ALTER FOREIGN TABLE [ IF EXISTS ] tablename OPTIONS ( {[ SET ] option ['value']} [, ... ]); ALTER FOREIGN TABLE [ IF EXISTS ] tablename OWNER TO new_owner; ALTER FOREIGN TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type [, ...] ); ALTER FOREIGN TABLE [ IF EXISTS ] tablename action [, ... ]; where action can be: ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type | MODIFY column_name data_type ``` ## ALTER FUNCTION Modifies the attributes of a user-defined function. ``` ALTER FUNCTION function_name ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) action [ ... ] [ RESTRICT ]; ALTER FUNCTION funname ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) RENAME TO new_name; ALTER FUNCTION funname ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) OWNER TO new_owner; ALTER FUNCTION funname ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) SET SCHEMA new_schema; where action can be: {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {IMMUTABLE | STABLE | VOLATILE} | {NOT FENCED | FENCED} | [ NOT ] LEAKPROOF | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER} | AUTHID { DEFINER | CURRENT_USER } | COST execution_cost | ROWS result_rows | SET configuration_parameter {{ TO | = } { value | DEFAULT }| FROM CURRENT} | RESET {configuration_parameter| ALL} ``` ## ALTER GROUP Modifies the attributes of a user group. ``` ALTER GROUP group_name ADD USER user_name [, ... ]; ALTER GROUP group_name DROP USER user_name [, ... ]; ALTER GROUP group_name RENAME TO new_name; ``` ## ALTER INDEX Modifies the definition of an existing index. ``` ALTER INDEX [ IF EXISTS ] index_name RENAME TO new_name; ALTER INDEX [ IF EXISTS ] index_name SET TABLESPACE tablespace_name; ALTER INDEX [ IF EXISTS ] index_name SET ( {storage_parameter = value} [, ... ] ); ALTER INDEX [ IF EXISTS ] index_name RESET ( storage_parameter [, ... ] ) ; ALTER INDEX [ IF EXISTS ] index_name [ MODIFY PARTITION partition_name ] UNUSABLE; ALTER INDEX index_name REBUILD [ PARTITION partition_name ]; ALTER INDEX [ IF EXISTS ] index_name RENAME PARTITION partition_name TO new_partition_name; ALTER INDEX [ IF EXISTS ] index_name MOVE PARTITION index_partition_name TABLESPACE new_tablespace; ``` ## ALTER LARGE OBJECT Modifies the definition of a large object. It is used to assign a new owner. ``` ALTER LARGE OBJECT large_object_oid OWNER TO new_owner; ``` ## ALTER MASKING POLICY Modifies a masking policy. ``` ALTER MASKING POLICY policy_name { ADD | REMOVE | MODIFY } masking_actions [, ... ]; ALTER MASKING POLICY policy_name MODIFY ( filter_group_clause ); ALTER MASKING POLICY policy_name DROP FILTER; ALTER MASKING POLICY policy_name { ENABLE | DISABLE }; where masking_actions can be: masking_function ON LABEL(label_name [, ... ]) where masking_function can be: { maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking } where filter_group_clause can be: FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## ALTER MATERIALIZED VIEW Modifies multiple auxiliary attributes of an existing materialized view. ``` ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name OWNER TO new_owner; ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME [COLUMN] column_name to new_column_name; ALTER MATERIALIZED VIEW [ IF EXISTS ] mv_name RENAME TO new_name; ``` ## ALTER OPERATOR Modifies the definition of an operator. ``` ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) OWNER TO new_owner ALTER OPERATOR name ( { left_type | NONE } , { right_type | NONE } ) SET SCHEMA new_schema ``` ## ALTER RESOURCE LABEL Modifies a resource label. ``` ALTER RESOURCE LABEL label_name { ADD | REMOVE } label_item_list [, ... ]; where label_item_list can be: resource_type(resource_path[, ... ]) where resource_type can be: { TABLE | COLUMN | SCHEMA | VIEW | FUNCTION } ``` ## ALTER RESOURCE POOL Modifies the Cgroup of a resource pool. ``` ALTER RESOURCE POOL pool_name WITH ({MEM_PERCENT=pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='priority' | nodegroup='nodegroup_name' }[, ... ]); ``` ## ALTER ROLE Modifies role attributes. ``` ALTER ROLE role_name [ [ WITH ] option [ ... ] ]; ALTER ROLE role_name RENAME TO new_name; ALTER ROLE role_name [ IN DATABASE database_name ] SET configuration_parameter {{ TO | = } { value | DEFAULT }|FROM CURRENT}; ALTER ROLE role_name [ IN DATABASE database_name ] RESET {configuration_parameter|ALL}; where option can be: {CREATEDB | NOCREATEDB} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {AUDITADMIN | NOAUDITADMIN} | {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {USEFT | NOUSEFT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' [ EXPIRED ] | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' | EXPIRED ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | ACCOUNT { LOCK | UNLOCK } | PGUSER ``` ## ALTER ROW LEVEL SECURITY POLICY Modifies an existing row-level access control policy, including the policy name and the users and expressions affected by the policy. ``` ALTER [ ROW LEVEL SECURITY ] POLICY [ IF EXISTS ] policy_name ON table_name RENAME TO new_policy_name ALTER [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ TO { role_name | PUBLIC } [, ...] ] [ USING ( using_expression ) ] ``` ## ALTER SCHEMA Modifies schema attributes. ``` ALTER SCHEMA schema_name RENAME TO new_name; ALTER SCHEMA schema_name OWNER TO new_owner; ALTER SCHEMA schema_name {WITH | WITHOUT} BLOCKCHAIN; ``` ## ALTER SEQUENCE Modifies the parameters of an existing sequence. ``` ALTER SEQUENCE [ IF EXISTS ] name [ MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE ] [ OWNED BY { table_name.column_name | NONE } ]; ALTER SEQUENCE [ IF EXISTS ] name OWNER TO new_owner; ``` ## ALTER SERVER Adds, modifies, or deletes the parameters of an existing server. You can query existing servers from the **pg\_foreign\_server** system catalog. ``` ALTER SERVER server_name [ VERSION 'new_version' ] [ OPTIONS ( {[ ADD | SET | DROP ] option ['value']} [, ... ] ) ]; ALTER SERVER server_name OWNER TO new_owner; ALTER SERVER server_name RENAME TO new_name; ``` ## ALTER SESSION Defines or modifies the conditions or parameters that affect the current session. Modified session parameters are kept until the current session is disconnected. ``` ALTER SESSION SET {{config_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }} | CURRENT_SCHEMA [ TO | = ] { schema | DEFAULT } | TIME ZONE time_zone | SCHEMA schema | NAMES encoding_name | ROLE role_name PASSWORD 'password' | SESSION AUTHORIZATION { role_name PASSWORD 'password' | DEFAULT } | XML OPTION { DOCUMENT | CONTENT } } ; ALTER SESSION SET [ SESSION CHARACTERISTICS AS ] TRANSACTION { ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED } | { READ ONLY | READ WRITE } } [, ...] ; ``` ## ALTER SYNONYM Modifies the attributes of the **SYNONYM** object. ``` ALTER SYNONYM synonym_name OWNER TO new_owner; ``` ## ALTER SYSTEM KILL SESSION Ends a session. ``` ALTER SYSTEM KILL SESSION 'session_sid, serial' [ IMMEDIATE ]; ``` ## ALTER SYSTEM SET Sets GUC parameters at the POSTMASTER, SIGHUP, and BACKEND levels. This command writes parameters into the configuration file. The time to take effect varies according to the level. ``` ALTER SYSTEM SET { GUC_name } TO { GUC_value }; ``` ## ALTER TABLE Modifies tables, including modifying table definitions, renaming tables, renaming specified columns in tables, renaming table constraints, setting table schemas, enabling or disabling row-level security policies, and adding or updating multiple columns. ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ALTER TABLE [ IF EXISTS ] table_name ADD ( { column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ]} [, ...] ); ALTER TABLE [ IF EXISTS ] table_name MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] ); ALTER TABLE [ IF EXISTS ] table_name RENAME TO new_table_name; ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME [ COLUMN ] column_name TO new_column_name; ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME CONSTRAINT constraint_name TO new_constraint_name; ALTER TABLE [ IF EXISTS ] table_name SET SCHEMA new_schema; where action can be: column_clause | ADD table_constraint [ NOT VALID ] | ADD table_constraint_using_index | VALIDATE CONSTRAINT constraint_name | DROP CONSTRAINT [ IF EXISTS ] constraint_name [ RESTRICT | CASCADE ] | CLUSTER ON index_name | SET WITHOUT CLUSTER | SET ( {storage_parameter = value} [, ... ] ) | RESET ( storage_parameter [, ... ] ) | OWNER TO new_owner | SET TABLESPACE new_tablespace | SET {COMPRESS|NOCOMPRESS} | TO { GROUP groupname | NODE ( nodename [, ... ] ) } | ADD NODE ( nodename [, ... ] ) | DELETE NODE ( nodename [, ... ] ) | UPDATE SLICE LIKE table_name | DISABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE TRIGGER [ trigger_name | ALL | USER ] | ENABLE REPLICA TRIGGER trigger_name | ENABLE ALWAYS TRIGGER trigger_name | ENABLE ROW LEVEL SECURITY | DISABLE ROW LEVEL SECURITY | FORCE ROW LEVEL SECURITY | NO FORCE ROW LEVEL SECURITY | ENCRYPTION KEY ROTATION where column_clause can be: ADD [ COLUMN ] column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | MODIFY column_name data_type | MODIFY column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | MODIFY column_name [ CONSTRAINT constraint_name ] NULL | DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ] | ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ] | ALTER [ COLUMN ] column_name { SET DEFAULT expression | DROP DEFAULT } | ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL | ALTER [ COLUMN ] column_name SET STATISTICS [PERCENT] integer | ADD STATISTICS (( column_1_name, column_2_name [, ...] )) | DELETE STATISTICS (( column_1_name, column_2_name [, ...] )) | ALTER [ COLUMN ] column_name SET ( {attribute_option = value} [, ... ] ) | ALTER [ COLUMN ] column_name RESET ( attribute_option [, ... ] ) | ALTER [ COLUMN ] column_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN } where column_constraint can be: [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED ALWAYS AS ( generation_expr ) STORED | UNIQUE index_parameters | PRIMARY KEY index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where compress_mode can be: { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } where table_constraint can be: [ CONSTRAINT constraint_name ] { CHECK ( expression ) | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where index_parameters can be: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] where table_constraint_using_index can be: [ CONSTRAINT constraint_name ] { UNIQUE | PRIMARY KEY } USING INDEX index_name [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` ## ALTER TABLE INHERIT ``` ALTER TABLE table_name { inherit | no inherit } parent_name; ``` ## ALTER TABLE PARTITION ``` ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} action [, ... ]; ALTER TABLE [ IF EXISTS ] { table_name [*] | ONLY table_name | ONLY ( table_name )} RENAME PARTITION { partion_name | FOR ( partition_value [, ...] ) } TO partition_new_name; where action can be: move_clause | exchange_clause | row_clause | merge_clause | modify_clause | split_clause | add_clause | drop_clause where move_clause can be: MOVE PARTITION { partion_name | FOR ( partition_value [, ...] ) } TABLESPACE tablespacename where exchange_clause can be: EXCHANGE PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } WITH TABLE {[ ONLY ] ordinary_table_name | ordinary_table_name * | ONLY ( ordinary_table_name )} [ { WITH | WITHOUT } VALIDATION ] [ VERBOSE ] where row_clause can be: { ENABLE | DISABLE } ROW MOVEMENT where merge_clause can be: MERGE PARTITIONS { partition_name } [, ...] INTO PARTITION partition_name [ TABLESPACE tablespacename ] where modify_clause can be: MODIFY PARTITION partition_name { UNUSABLE LOCAL INDEXES | REBUILD UNUSABLE LOCAL INDEXES } where split_clause can be: SPLIT PARTITION { partition_name | FOR ( partition_value [, ...] ) } { split_point_clause | no_split_point_clause } where split_point_clause can be: AT ( partition_value ) INTO ( PARTITION partition_name [ TABLESPACE tablespacename ] , PARTITION partition_name [ TABLESPACE tablespacename ] ) where no_split_point_clause can be: INTO {(partition_less_than_item [, ...] ) | (partition_start_end_item [, ...] )} where add_clause can be: ADD {partition_less_than_item | partition_start_end_item} where partition_less_than_item can be: PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } [, ...] ) [ TABLESPACE tablespacename ] where partition_start_end_item can be: PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] where drop_clause can be: DROP PARTITION { partition_name | FOR ( partition_value [, ...] ) } ``` ## ALTER TABLESPACE Modifies the attributes of a tablespace. ``` ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name; ALTER TABLESPACE tablespace_name OWNER TO new_owner; ALTER TABLESPACE tablespace_name SET ( {tablespace_option = value} [, ... ] ); ALTER TABLESPACE tablespace_name RESET ( tablespace_option [, ... ] ); ALTER TABLESPACE tablespace_name RESIZE MAXSIZE { UNLIMITED | 'space_size' }; ``` ## ALTER TEXT SEARCH CONFIGURATION Modifies the definition of a text search configuration. You can modify its mappings from strings to dictionaries, change the configuration's name or owner, or modify the parameters. ``` ALTER TEXT SEARCH CONFIGURATION name ADD MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ] ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] WITH dictionary_name [, ... ] ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING REPLACE old_dictionary WITH new_dictionary ALTER TEXT SEARCH CONFIGURATION name ALTER MAPPING FOR token_type [, ... ] REPLACE old_dictionary WITH new_dictionary ALTER TEXT SEARCH CONFIGURATION name DROP MAPPING [ IF EXISTS ] FOR token_type [, ... ] ALTER TEXT SEARCH CONFIGURATION name RENAME TO new_name ALTER TEXT SEARCH CONFIGURATION name OWNER TO new_owner ALTER TEXT SEARCH CONFIGURATION name SET SCHEMA new_schema ALTER TEXT SEARCH CONFIGURATION name SET ( {configuration_option = value} [, ...] ) ALTER TEXT SEARCH CONFIGURATION name RESET ( {configuration_option} [, ...] ) ``` ## ALTER TEXT SEARCH DICTIONARY Modifies the definition of a full-text search dictionary, including its parameters, name, owner, and schema. ``` ALTER TEXT SEARCH DICTIONARY name ( option = value | option [, ...] ); ALTER TEXT SEARCH DICTIONARY name RENAME TO new_name; ALTER TEXT SEARCH DICTIONARY name OWNER TO new_owner; ALTER TEXT SEARCH DICTIONARY name SET SCHEMA new_schema ``` ## ALTER TRIGGER Renames a trigger. ``` ALTER TRIGGER name ON table_name RENAME TO new_name ``` ## ALTER TYPE Modifies the definition of a type. ``` ALTER TYPE name action [, ... ] ALTER TYPE name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } ALTER TYPE name RENAME ATTRIBUTE attribute_name TO new_attribute_name [ CASCADE | RESTRICT ] ALTER TYPE name RENAME TO new_name ALTER TYPE name SET SCHEMA new_schema ALTER TYPE name ADD VALUE [ IF NOT EXISTS ] new_enum_value [ { BEFORE | AFTER } neighbor_enum_value ] ALTER TYPE name RENAME VALUE existing_enum_value TO new_enum_value where action is one of: ADD ATTRIBUTE attribute_name data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] DROP ATTRIBUTE [ IF EXISTS ] attribute_name [ CASCADE | RESTRICT ] ALTER ATTRIBUTE attribute_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ CASCADE | RESTRICT ] ``` ## ALTER USER Modifies the attributes of a database user. ``` ALTER USER user_name [ [ WITH ] option [ ... ] ]; ALTER USER user_name RENAME TO new_name; ALTER USER user_name [ IN DATABASE database_name ] SET configuration_parameter {{ TO | = } { value | DEFAULT }|FROM CURRENT}; ALTER USER user_name [ IN DATABASE database_name ] RESET {configuration_parameter|ALL}; where option can be: {CREATEDB | NOCREATEDB} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {AUDITADMIN | NOAUDITADMIN} | {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {USEFT | NOUSEFT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | [ ENCRYPTED | UNENCRYPTED ] PASSWORD { 'password' [ EXPIRED ] | DISABLE | EXPIRED } | [ ENCRYPTED | UNENCRYPTED ] IDENTIFIED BY { 'password' [ REPLACE 'old_password' | EXPIRED ] | DISABLE } | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | ACCOUNT { LOCK | UNLOCK } | PGUSER ``` ## ALTER VIEW Modifies the auxiliary attributes of a view. ``` ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name SET DEFAULT expression; ALTER VIEW [ IF EXISTS ] view_name ALTER [ COLUMN ] column_name DROP DEFAULT; ALTER VIEW [ IF EXISTS ] view_name OWNER TO new_owner; ALTER VIEW [ IF EXISTS ] view_name RENAME TO new_name; ALTER VIEW [ IF EXISTS ] view_name SET SCHEMA new_schema; ALTER VIEW [ IF EXISTS ] view_name SET ( {view_option_name [= view_option_value]} [, ... ] ); ALTER VIEW [ IF EXISTS ] view_name RESET ( view_option_name [, ... ] ); ``` ## ANALYSE|ANALYZE Collects statistics about ordinary tables in a database, and stores the results in the **PG\_STATISTIC** system catalog. The execution plan generator uses these statistics to determine which one is the most effective execution plan. ``` {ANALYZE | ANALYSE} [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ]; {ANALYZE | ANALYSE} [ VERBOSE ] [ table_name [ ( column_name [, ...] ) ] ] PARTITION partition_name; {ANALYZE | ANALYSE} [ VERBOSE ] { foreign_table_name | FOREIGN TABLES }; {ANALYZE | ANALYSE} [ VERBOSE ] table_name (( column_1_name, column_2_name [, ...] )); {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE}; {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name|index_name [CASCADE]; {ANALYZE | ANALYSE} VERIFY {FAST|COMPLETE} table_name PARTITION (partition_name) [CASCADE]; ``` ## ANONYMOUS BLOCK Applies to a script that is infrequently executed or a one-off activity. It is executed in a session and is not stored. ``` [DECLARE [declare_statements]] BEGIN execution_staements END; / ``` ## BEGIN Initiates an anonymous block or a single transaction. ``` start an anonymous block: [DECLARE [declare_statements]] BEGIN execution_statements END; / start a transaction: BEGIN [ WORK | TRANSACTION ] [ { ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED | SERIALIZABLE | REPEATABLE READ } | { READ WRITE | READ ONLY } } [, ...] ]; ``` ## CALL Calls defined functions and stored procedures. ``` CALL [schema.] func_name ( param_expr ); ``` ## CHECKPOINT A checkpoint is a point in the transaction log sequence at which all data files have been updated to reflect the information in the log. All data files will be flushed to a disk. ``` CHECKPOINT ``` ## CLEAN CONNECTION Clears database connections. You may use this statement to delete a specific user's connections to a specified database. ``` CLEAN CONNECTION TO { COORDINATOR ( nodename [, ... ] ) | NODE ( nodename [, ... ] ) | ALL [ CHECK ] [ FORCE ] } [ FOR DATABASE dbname ] [ TO USER username ]; ``` ## CLOSE Frees the resources associated with an open cursor. ``` CLOSE { cursor_name | ALL }; ``` ## CLUSTER Clusters a table based on an index. ``` CLUSTER [ VERBOSE ] table_name [ USING index_name ]; CLUSTER [ VERBOSE ] table_name PARTITION ( partition_name ) [ USING index_name ]; CLUSTER [ VERBOSE ]; ``` ## COMMENT Defines or changes the comment of an object. ``` COMMENT ON { AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | COLUMN { table_name.column_name | view_name.column_name } | CONSTRAINT constraint_name ON table_name | CONVERSION object_name | DATABASE object_name | DOMAIN object_name | EXTENSION object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) | INDEX object_name | LARGE OBJECT large_object_oid | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | ROLE object_name | RULE rule_name ON table_name | SCHEMA object_name | SERVER object_name | TABLE object_name | TABLESPACE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name } IS 'text'; ``` ## COMMIT Commits all operations of a transaction. ``` { COMMIT | END } [ WORK | TRANSACTION ]; ``` ## COMMIT PREPARED Commits a prepared two-phase transaction. ``` COMMIT PREPARED transaction_id; ``` ## COPY Copies data between tables and files. ``` COPY table_name [ ( column_name [, ...] ) ] FROM { 'filename' | STDIN } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ LOG ERRORS ] [ LOG ERRORS DATA ] [ REJECT LIMIT 'limit' ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ] | [ TRANSFORM ( { column_name [ data_type ] [ AS transform_expr ] } [, ...] ) ]; COPY table_name [ ( column_name [, ...] ) ] TO { 'filename' | STDOUT } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; COPY query TO { 'filename' | STDOUT } [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; where option can be: FORMAT 'format_name' | OIDS [ boolean ] | DELIMITER 'delimiter_character' | NULL 'null_string' | HEADER [ boolean ] | FILEHEADER 'header_file_string' | FREEZE [ boolean ] | QUOTE 'quote_character' | ESCAPE 'escape_character' | EOL 'newline_character' | NOESCAPING [ boolean ] | FORCE_QUOTE { ( column_name [, ...] ) | * } | FORCE_NOT_NULL ( column_name [, ...] ) | FORCE_NULL ( column_name [, ...] ) | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA [ boolean ] | FILL_MISSING_FIELDS [ boolean ] | COMPATIBLE_ILLEGAL_CHARS [ boolean ] | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' and copy_option can be: OIDS | NULL 'null_string' | HEADER | FILEHEADER 'header_file_string' | FREEZE | FORCE NOT NULL column_name [, ...] | FORCE NULL column_name [, ...] | FORCE QUOTE { column_name [, ...] | * } | BINARY | CSV | QUOTE [ AS ] 'quote_character' | ESCAPE [ AS ] 'escape_character' | EOL 'newline_character' | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA | FILL_MISSING_FIELDS | COMPATIBLE_ILLEGAL_CHARS | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` ## CREATE AUDIT POLICY Creates a unified audit policy. ``` CREATE AUDIT POLICY [ IF NOT EXISTS ] policy_name { { privilege_audit_clause | access_audit_clause } [ filter_group_clause ] [ ENABLED | DISABLED ] }; where privilege_audit_clause can be: PRIVILEGES { DDL | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] where access_audit_clause can be: ACCESS { DML | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] where filter_group_clause can be: FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } where DDL can be: { ( ALTER | ANALYZE | COMMENT | CREATE | DROP | GRANT | REVOKE | SET | SHOW | LOGIN_ACCESS | LOGIN_FAILURE | LOGOUT | LOGIN ) } where DML can be: { ( COPY | DEALLOCATE | DELETE_P | EXECUTE | REINDEX | INSERT | REPARE | SELECT | TRUNCATE | UPDATE ) } where FILTER_TYPE can be: { APP | ROLES | IP } ``` ## CREATE CLIENT MASTER KEY Creates a CMK object that can be used to encrypt a CEK object. ``` CREATE CLIENT MASTER KEY client_master_key_name [WITH] ( ['KEY_STORE' , 'KEY_PATH' , 'ALGORITHM'] ); ``` ## CREATE COLUMN ENCRYPTION KEY Creates a CEK that can be used to encrypt a specified column in a table. ``` CREATE COLUMN ENCRYPTION KEY column_encryption_key_name [WITH] [VALUES] ( ['CLIENT_MASTER_KEY' , 'ALGORITHM'] ); ``` ## CREATE DATA SOURCE Creates an external data source, which defines the information about the database that openGauss will connect to. ``` CREATE DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS (optname 'optvalue' [, ...])]; Valid optname are: DSN, USERNAME, PASSWORD, ENCODING ``` ## CREATE DATABASE Creates a database. By default, the new database will be created only by cloning the standard system database **template0**. ``` CREATE DATABASE database_name [ [ WITH ] {[ OWNER [=] user_name ]| [ TEMPLATE [=] template ]| [ ENCODING [=] encoding ]| [ LC_COLLATE [=] lc_collate ]| [ LC_CTYPE [=] lc_ctype ]| [ DBCOMPATIBILITY [=] compatibility_type ]| [ TABLESPACE [=] tablespace_name ]| [ CONNECTION LIMIT [=] connlimit ]}[...] ]; ``` ## CREATE DIRECTORY Creates a directory. The directory defines an alias for a path in the server file system and is used to store data files used by users. ``` CREATE [OR REPLACE] DIRECTORY directory_name AS 'path_name'; ``` ## CREATE EXTENSION Installs an extension. ``` CREATE EXTENSION [ IF NOT EXISTS ] extension_name [ WITH ] [ SCHEMA schema_name ] [ VERSION version ] [ FROM old_version ]; ``` ## CREATE FOREIGN TABLE Creates a foreign table. ``` CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( { column_name type_name POSITION(offset,length) [column_constraint ] | LIKE source_table | table_constraint } [, ...] ) SEVER gsmpp_server OPTIONS ( { option_name ' value ' } [, ...] ) [ { WRITE ONLY | READ ONLY }] [ WITH error_table_name | LOG INTO error_table_name] [REMOTE LOG 'name'] [PER NODE REJECT LIMIT 'value'] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ]; CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( { column_name type_name [ { [CONSTRAINT constraint_name] NULL | [CONSTRAINT constraint_name] NOT NULL | column_constraint [...]} ] | table_constraint} [, ...] ) SERVER server_name OPTIONS ( { option_name ' value ' } [, ...] ) DISTRIBUTE BY {ROUNDROBIN | REPLICATION} [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] [ PARTITION BY ( column_name ) [AUTOMAPPED]] ; CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( [ { column_name type_name | LIKE source_table } [, ...] ] ) SERVER server_name OPTIONS ( { option_name ' value ' } [, ...] ) [ READ ONLY ] [ DISTRIBUTE BY {ROUNDROBIN} ] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ]; where column_constraint can be: [CONSTRAINT constraint_name] {PRIMARY KEY | UNIQUE} [NOT ENFORCED [ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION] | ENFORCED] where table_constraint can be: [CONSTRAINT constraint_name] {PRIMARY KEY | UNIQUE} (column_name) [NOT ENFORCED [ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION] | ENFORCED] ``` ## CREATE FUNCTION Creates a function. ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ]} [, ...] ] ) [ RETURNS rettype [ DETERMINISTIC ] | RETURNS TABLE ( { column_name column_type } [, ...] )] LANGUAGE lang_name [ {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | [ NOT ] LEAKPROOF | WINDOW | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | {FENCED | NOT FENCED} | {PACKAGE} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } ] [...] { AS 'definition' | AS 'obj_file', 'link_symbol' } CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ DETERMINISTIC ] [ {IMMUTABLE | STABLE | VOLATILE } | {SHIPPABLE | NOT SHIPPABLE} | {PACKAGE} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } ][...] { IS | AS } plsql_body / ``` ## CREATE GROUP Creates a user group. ``` CREATE GROUP group_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; where option can be: {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_group_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN role_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## CREATE INDEX Create an index on a specified table. ``` CREATE [ UNIQUE ] INDEX [ [schema_name.] index_name ] ON table_name [ USING method ] ({ { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ WHERE predicate ]; CREATE [ UNIQUE ] INDEX [ [schema_name.] index_name ] ON table_name [ USING method ] ( {{ column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ WITH ( { storage_parameter = value } [, ...] ) ] [ TABLESPACE tablespace_name ]; ``` ## CREATE LANGUAGE Defines a new procedural language. A standalone or centralized system does not support creating procedural languages. ``` CREATE [ UNIQUE ] INDEX [ [schema_name.] index_name ] ON table_name [ USING method ] ({ { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ WHERE predicate ]; CREATE [ UNIQUE ] INDEX [ [schema_name.] index_name ] ON table_name [ USING method ] ( {{ column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ WITH ( { storage_parameter = value } [, ...] ) ] [ TABLESPACE tablespace_name ]; openGauss=# \h CREATE LANGUAGE Command: CREATE LANGUAGE Description: define a new procedural language Syntax: CREATE [ OR REPLACE ] [ PROCEDURAL ] LANGUAGE name; CREATE [ OR REPLACE ] [ TRUSTED ] [ PROCEDURAL ] LANGUAGE name HANDLER call_handler [ INLINE inline_handler ] [ VALIDATOR valfunction ]; ``` ## CREATE MASKING POLICY Creates a masking policy. ``` CREATE MASKING POLICY policy_name masking_clause [, ... ] [ policy_filter_clause ] [ ENABLE | DISABLE ]; where masking_clause can be: masking_function ON LABEL(label_name [, ... ]) where masking_function can be: { maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking } where policy_filter_clause can be: FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } where FILTER_TYPE can be: { APP | ROLES | IP } ``` ## CREATE MATERIALIZED VIEW Creates a complete-refresh materialized view that can be refreshed by using **REFRESH MATERIALIZED VIEW** to refresh the data in the materialized view. ``` CREATE [ INCREMENTAL ] MATERIALIZED VIEW table_name [ (column_name [, ...] ) ] [ TABLESPACE tablespace_name ] AS query ``` ## CREATE MODEL Trains a machine learning model and saves the model. ``` CREATE MODEL model_name USING algorithm_name [FEATURES { {expression [ [ AS ] output_name ]} [, ...] }] [TARGET { {expression [ [ AS ] output_name ]} [, ...] }] FROM { table_name | select_query } WITH hyperparameter_name = { hyperparameter_value | DEFAULT } [, ...] } ``` ## CREATE OPERATOR Defines a new operator. ``` CREATE OPERATOR name ( PROCEDURE = function_name [, LEFTARG = left_type ] [, RIGHTARG = right_type ] [, COMMUTATOR = com_op ] [, NEGATOR = neg_op ] [, RESTRICT = res_proc ] [, JOIN = join_proc ] [, HASHES ] [, MERGES ] ) ``` ## CREATE PACKAGE Creates a package. ``` CREATE [ OR REPLACE ] PACKAGE [ schema ] package_name [ invoker_rights_clause ] { IS | AS } item_list_1 END package_name; ``` ## CREATE PROCEDURE Creates a stored procedure. ``` CREATE [ OR REPLACE ] PACKAGE [ schema ] package_name [ invoker_rights_clause ] { IS | AS } item_list_1 END package_name; openGauss=# \h CREATE PROCEDURE Command: CREATE PROCEDURE Description: create a procedure Syntax: CREATE [ OR REPLACE ] PROCEDURE procedure_name [ ( {[ argmode ] [ argname ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] { IS | AS } plsql_body / ``` ## CREATE RESOURCE LABEL Creates a resource label. ``` CREATE RESOURCE LABEL [ IF NOT EXISTS ] label_name ADD label_item_list[ , ... ]; where label_item_list can be: resource_type(resource_path[, ... ]) where resource_type can be: { TABLE | COLUMN | SCHEMA | VIEW | FUNCTION } ``` ## CREATE RESOURCE POOL Creates a resource pool and specifies the Cgroup of the resource pool. ``` CREATE RESOURCE POOL pool_name [WITH ({MEM_PERCENT=pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='priority' | nodegroup='nodegroup_name' | is_foreign = boolean }[, ... ])]; ``` ## CREATE ROLE Creates a role. ``` CREATE ROLE role_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; where option can be: {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN role_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## CREATE ROW LEVEL SECURITY POLICY Creates a row-level access control policy for a table. ``` CREATE [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ AS { PERMISSIVE | RESTRICTIVE } ] [ FOR { ALL | SELECT | UPDATE | DELETE } ] [ TO { role_name | PUBLIC } [, ...] ] USING ( using_expression ) ``` ## CREATE SCHEMA Creates a schema. ``` CREATE SCHEMA schema_name [ AUTHORIZATION user_name ] [WITH BLOCKCHAIN] [ schema_element [ ... ] ]; ``` ## CREATE SEQUENCE Aadds a sequence to the current database. The owner of the sequence is the user who creates it. ``` CREATE SEQUENCE name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE] [ MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE] [ GLOBAL | SESSION ] [ OWNED BY { table_name.column_name | NONE } ]; ``` ## CREATE SERVER Defines a new foreign server. ``` CREATE SERVER server_name FOREIGN DATA WRAPPER fdw_name OPTIONS ( { option_name ' value ' } [, ...] ) ; ``` ## CREATE SYNONYM Creates a synonym object. A synonym is an alias of a database object and is used to record the mapping between database object names. You can use synonyms to access associated database objects. ``` CREATE [ OR REPLACE ] [ PUBLIC ] SYNONYM synonym_name FOR object_name; ``` ## CREATE TABLE Creates an empty table in the current database. The table will be owned by the creator. ``` CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] [encrypted with ('column_encryption_key', 'encryption_type')] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ]) [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ]; where column_constraint can be: [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED ALWAYS AS ( generation_expr ) STORED | UNIQUE index_parameters | PRIMARY KEY index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where table_constraint can be: [ CONSTRAINT constraint_name ] { CHECK ( expression ) | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where compress_mode can be: { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } where like_option can be: { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | PARTITION | RELOPTIONS | DISTRIBUTION | ALL } where index_parameters can be: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## CREATE TABLE AS Creates a table from the results of a query. ``` CREATE [ UNLOGGED ] TABLE table_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ DISTRIBUTE BY { REPLICATION | { [HASH ] ( column_name ) } } ] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] AS query [ WITH [ NO ] DATA ]; ``` ## CREATE TABLE PARTITION Creates a partitioned table. Partitioning refers to splitting what is logically one large table into smaller physical pieces based on specific schemes. The table based on the logic is called a partitioned table, and each physical piece is called a partition. A partitioned table is a logical table and does not store data. Data is stored in physical partitions. ``` CREATE TABLE [ IF NOT EXISTS ] partition_table_name ( [ { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ] ] ) [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ DISTRIBUTE BY { REPLICATION | { [ HASH ] ( column_name ) } } ] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] PARTITION BY { {VALUES (partition_key)} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN ( tablespace_name [, ... ] ) ] ] ( partition_less_than_item [, ... ] )} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN ( tablespace_name [, ... ] ) ] ] ( partition_start_end_item [, ... ] )} | {LIST | HASH (partition_key) (PARTITION partition_name [VALUES (list_values_clause)] opt_table_space )} NOTICE: LIST/HASH partition is only available in CENTRALIZED mode! } [ { ENABLE | DISABLE } ROW MOVEMENT ]; where column_constraint can be: [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED ALWAYS AS ( generation_expr ) STORED | UNIQUE index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where table_constraint can be: [ CONSTRAINT constraint_name ] { CHECK ( expression ) | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters | FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] where index_parameters can be: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] where like_option can be: { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS | DISTRIBUTION | ALL } where partition_less_than_item can be: PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } ) [TABLESPACE tablespace_name] where partition_start_end_item can be: PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` ## CREATE TABLE INHERITS Creates a tablespace in a database. ``` CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] TABLE inherit_table_name( [ {LIKE fathername} [INCLUDING ALL]} ] ) [ INHERITS ( parent_table [, ... ] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ]; ``` ## CREATE TABLESPACE Creates a tablespace in a database. ``` CREATE TABLESPACE tablespace_name [ OWNER user_name ] [ RELATIVE ] LOCATION 'directory' [ MAXSIZE 'space_size' ] [with_option_clause]; where option_clause can be: WITH ( filesystem= { 'systemtype '| " systemtype " | systemtype } [ { , address = { ' ip:port [ , ... ] ' | " ip:port [ , ... ] "} } ] , cfgpath = { 'path '| " path " } ,storepath = { 'rootpath '| " rootpath "} [{, random_page_cost = { 'value '| " value " | value }}] [{,seq_page_cost = { 'value '| " value " | value }}]) ``` ## CREATE TEXT SEARCH CONFIGURATION Creates a text search configuration. A text search configuration specifies a text search parser that can divide a string into tokens, plus dictionaries that can be used to determine which tokens are of interest for searching. ``` CREATE TEXT SEARCH CONFIGURATION name ( PARSER = parser_name | COPY = source_config ) [ WITH ( {configuration_option = value} [, ...] )]; ``` ## CREATE TEXT SEARCH DICTIONARY Deletes a full-text retrieval dictionary. ``` CREATE TEXT SEARCH DICTIONARY name ( TEMPLATE = template_name | COPY = source_config [, option = value [, ...] ] ); ``` ## CREATE TRIGGER Creates a trigger. The trigger will be associated with the specified table or view, and will execute the specified functions under certain conditions. ``` CREATE [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] } ON table_name [ FROM referenced_table_name ] { NOT DEFERRABLE | [ DEFERRABLE ] { INITIALLY IMMEDIATE | INITIALLY DEFERRED } } [ FOR [ EACH ] { ROW | STATEMENT } ] [ WHEN ( condition ) ] EXECUTE PROCEDURE function_name ( arguments ) where event can be one of: INSERT UPDATE [ OF column_name [, ... ] ] DELETE TRUNCATE ``` ## CREATE TYPE Defines a new data type for use in the current database. The user who defines a type becomes its owner. Types are designed only for row-store tables. ``` CREATE TYPE name AS ( [ attribute_name data_type [ COLLATE collation ] [, ... ] ] ) CREATE TYPE name AS ENUM ( [ 'label' [, ... ] ] ) CREATE TYPE name ( INPUT = input_function, OUTPUT = output_function [ , RECEIVE = receive_function ] [ , SEND = send_function ] [ , TYPMOD_IN = type_modifier_input_function ] [ , TYPMOD_OUT = type_modifier_output_function ] [ , ANALYZE = analyze_function ] [ , INTERNALLENGTH = { internallength | VARIABLE } ] [ , PASSEDBYVALUE ] [ , ALIGNMENT = alignment ] [ , STORAGE = storage ] [ , LIKE = like_type ] [ , CATEGORY = category ] [ , PREFERRED = preferred ] [ , DEFAULT = default ] [ , ELEMENT = element ] [ , DELIMITER = delimiter ] [ , COLLATABLE = collatable ] ) CREATE TYPE name ``` ## CREATE USER Creates a user. ``` CREATE USER user_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; where option can be: {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN role_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## CREATE VIEW Creates a view. ``` CREATE [ OR REPLACE ] [ TEMP | TEMPORARY ] VIEW view_name [ ( column_name [, ...] ) ] [ WITH ( {view_option_name [= view_option_value]} [, ... ] ) ] AS query; ``` ## CREATE WEAK PASSWORD DICTIONARY Inserts one or more weak passwords into the **gs\_global\_config** table. ``` CREATE WEAK PASSWORD DICTIONARY [WITH VALUES] ( {'weak_password'} [, ...] ); ``` ## CURSOR Defines a cursor to retrieve a small number of rows out of a large query. ``` CURSOR cursor_name [ BINARY ] [ INSENSITIVE ] [ [ NO ] SCROLL ] FOR query ; ``` ## DEALLOCATE Deallocates a previously prepared statement. If you do not explicitly deallocate a prepared statement, it is deallocated when the session ends. ``` DEALLOCATE [ PREPARE ] { name | ALL }; ``` ## DECLARE Deallocates a previously prepared statement. If you do not explicitly deallocate a prepared statement, it is deallocated when the session ends. ``` 1. declare a cursor: DECLARE cursor_name [ BINARY ] [ NO SCROLL ] CURSOR [ { WITH | WITHOUT } HOLD ] FOR query ; 2. start an anonymous block: [DECLARE [declare_statements]] BEGIN execution_statements END; / ``` ## DELETE Deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, it will delete all rows in the table. The result is a valid, but an empty table. ``` [ WITH [ RECURSIVE ] with_query [, ...] ] DELETE [/*+ plan_hint */] FROM [ ONLY ] table_name [ * ] [ [ AS ] alias ] [ USING using_list ] [ WHERE condition | WHERE CURRENT OF cursor_name ] [ LIMIT row_count ] [ RETURNING { * | { output_expr [ [ AS ] output_name ] } [, ...] } ]; ``` ## DO Executes an anonymous code block. ``` DO [ LANGUAGE lang_name ] code; ``` ## DROP AUDIT POLICY Deletes an audit policy. ``` DROP AUDIT POLICY [IF EXISTS] policy_name; ``` ## DROP CLIENT MASTER KEY Deletes a CMK. ``` DROP CLIENT MASTER KEY [ IF EXISTS ] client_master_key_name [, ...]; ``` ## DROP COLUMN ENCRYPTION KEY Deletes a CEK. ``` DROP COLUMN ENCRYPTION KEY [ IF EXISTS ] client_column_key_name [, ...]; ``` ## DROP DATA SOURCE Deletes a data source. ``` DROP DATA SOURCE [IF EXISTS] src_name [CASCADE | RESTRICT]; ``` ## DROP DATABASE Deletes a database. ``` DROP DATABASE [ IF EXISTS ] database_name; ``` ## DROP DIRECTORY Deletes a directory. ``` DROP DIRECTORY [ IF EXISTS ] directory_name; ``` ## DROP EXTENSION Deletes an extension. ``` DROP EXTENSION [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP FOREIGN TABLE Deletes a foreign table. ``` DROP FOREIGN TABLE [ IF EXISTS ] table_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP FUNCTION Deletes a function. ``` DROP FUNCTION [ IF EXISTS ] function_name [ ( [ {[ argmode ] [ argname ] argtype} [, ...] ] ) [ CASCADE | RESTRICT ] ]; ``` ## DROP GROUP Deletes a user group. ``` DROP GROUP [ IF EXISTS ] group_name [, ...]; ``` ## DROP INDEX Deletes an index. ``` DROP INDEX [ IF EXISTS ] index_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP MASKING POLICY Deletes a masking policy. ``` DROP MASKING POLICY [IF EXISTS] policy_name; ``` ## DROP MATERIALIZED VIEW Forcibly deletes an existing materialized view from the database. ``` DROP MATERIALIZED VIEW [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ] ``` ## DROP MODEL Deletes a model that has been trained and saved. ``` DROP MODEL model_name; ``` ## DROP OPERATOR Not supported in openGauss currently. ``` DROP OPERATOR [ IF EXISTS ] name ( { left_type | NONE } , { right_type | NONE } ) [ CASCADE | RESTRICT ] ``` ## DROP OWNED Deletes the database objects owned by a database role. ``` DROP OWNED BY name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP PACKAGE Deletes a package or package body. ``` DROP PACKAGE [ IF EXISTS ] package_name; ``` ## DROP PROCEDURE Deletes a stored procedure. ``` DROP PROCEDURE [ IF EXISTS ] procedure_name; ``` ## DROP RESOURCE LABEL Deletes a resource label. ``` DROP RESOURCE LABEL [ IF EXISTS ] policy_name[, ... ]; ``` ## DROP RESOURCE POOL Deletes a resource pool. ``` DROP RESOURCE POOL [ IF EXISTS ] pool_name; ``` ## DROP ROLE Deletes a role. ``` DROP ROLE [ IF EXISTS ] role_name [, ...]; ``` ## DROP ROW LEVEL SECURITY POLICY Deletes a row-level access control policy from a table. ``` DROP [ ROW LEVEL SECURITY ] POLICY [ IF EXISTS ] policy_name ON table_name [ CASCADE | RESTRICT ] ``` ## DROP SCHEMA Deletes a schema from the current database. ``` DROP SCHEMA [ IF EXISTS ] schema_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP SEQUENCE Deletes a sequence from the current database. ``` DROP SEQUENCE [ IF EXISTS ] {[schema.]sequence_name} [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP SERVER Deletes a data server. ``` DROP SERVER [ IF EXISTS ] server_name [ { CASCADE | RESTRICT } ] ; ``` ## DROP SYNONYM Deletes a synonym. ``` DROP [ PUBLIC ] SYNONYM [ IF EXISTS ] synonym_name [ CASCADE | RESTRICT ]; ``` ## DROP TABLE Deletes a table. ``` DROP TABLE [ IF EXISTS ] {[schema.]table_name} [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP TABLESPACE Deletes a tablespace. ``` DROP TABLESPACE [ IF EXISTS ] tablespace_name; ``` ## DROP TEXT SEARCH CONFIGURATION Deletes a text search configuration. ``` DROP TEXT SEARCH CONFIGURATION [ IF EXISTS ] name [ CASCADE | RESTRICT ] ``` ## DROP TEXT SEARCH DICTIONARY Deletes a full-text retrieval dictionary. ``` DROP TEXT SEARCH DICTIONARY [ IF EXISTS ] name [ CASCADE | RESTRICT ]; ``` ## DROP TRIGGER Deletes a trigger. ``` DROP TRIGGER [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ] ``` ## DROP TYPE Deletes a user-defined data type. ``` DROP TYPE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ] ``` ## DROP USER Deletes a user and the schema with the same name as the user. ``` DROP USER [ IF EXISTS ] user_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP VIEW Forcibly deletes a view from the database. ``` DROP VIEW [ IF EXISTS ] view_name [, ...] [ CASCADE | RESTRICT ]; ``` ## DROP WEAK PASSWORD DICTIONARY Clears all weak passwords in **gs\_global\_config**. ``` DROP WEAK PASSWORD DICTIONARY; ``` ## END Commits all operations of a transaction. ``` END [ WORK | TRANSACTION ] ``` ## EXECUTE Executes a prepared statement. Because a prepared statement exists only in the lifetime of the session, the prepared statement must be created earlier in the current session by using the **PREPARE** statement. ``` EXECUTE name [ ( parameter [, ...] ) ]; ``` ## EXECUTE DIRECT Executes an SQL statement on a specified node. Generally, the cluster automatically allocates an SQL statement to proper nodes. **EXECUTE DIRECT** is mainly used for database maintenance and testing. ``` EXPLAIN [ ( option [, ...] ) ] statement; EXPLAIN { [ { ANALYZE | ANALYSE } ] [ VERBOSE ] | PERFORMANCE } statement; where option can be: ANALYZE [ boolean ] | ANALYSE [ boolean ] | VERBOSE [ boolean ] | COSTS [ boolean ] | CPU [ boolean ] | DETAIL [ boolean ] | NODES [ boolean ] | NUM_NODES [ boolean ] | BUFFERS [ boolean ] | TIMING [ boolean ] | PLAN [ boolean ] | FORMAT { TEXT | XML | JSON | YAML } openGauss=# \h EXECUTE DIRECT Command: EXECUTE DIRECT Description: launch queries directly to dedicated nodes Syntax: EXECUTE DIRECT ON ( nodename [, ... ] ) query; EXECUTE DIRECT ON { COORDINATORS | DATANODES | ALL } query; ``` ## EXPLAIN Shows the execution plan of an SQL statement. ``` EXPLAIN [ ( option [, ...] ) ] statement; EXPLAIN { [ { ANALYZE | ANALYSE } ] [ VERBOSE ] | PERFORMANCE } statement; where option can be: ANALYZE [ boolean ] | ANALYSE [ boolean ] | VERBOSE [ boolean ] | COSTS [ boolean ] | CPU [ boolean ] | DETAIL [ boolean ] | NODES [ boolean ] | NUM_NODES [ boolean ] | BUFFERS [ boolean ] | TIMING [ boolean ] | PLAN [ boolean ] | FORMAT { TEXT | XML | JSON | YAML } ``` ## FETCH Retrieves rows using a previously created cursor. ``` FETCH [ direction { FROM | IN } ] cursor_name; where direction can be: NEXT | PRIOR | FIRST | LAST | ABSOLUTE count | RELATIVE count | count | ALL | FORWARD | FORWARD count | FORWARD ALL | BACKWARD | BACKWARD count | BACKWARD ALL ``` ## GRANT Grants permissions to roles and users. ``` GRANT { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON { [ TABLE ] table_name [, ...] | ALL TABLES IN SCHEMA schema_name [, ...] } TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { {{ SELECT | INSERT | UPDATE | REFERENCES | COMMENT } ( column_name [, ...] )} [, ...] | ALL [ PRIVILEGES ] ( column_name [, ...] ) } ON [ TABLE ] table_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { SELECT | UPDATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON { [ SEQUENCE ] sequence_name [, ...] | ALL SEQUENCES IN SCHEMA schema_name [, ...] } TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { CREATE | CONNECT | TEMPORARY | TEMP | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON DATABASE database_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { USAGE | ALL [ PRIVILEGES ] } ON DOMAIN domain_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON CLIENT_MASTER_KEY client_master_key TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { USAGE | DROP } [, ...] | ALL [ PRIVILEGES ] } ON COLUMN_ENCRYPTION_KEY column_encryption_key TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { USAGE | ALL [ PRIVILEGES ] } ON FOREIGN DATA WRAPPER fdw_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FOREIGN SERVER server_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON { FUNCTION {function_name ( [ {[ argmode ] [ arg_name ] arg_type} [, ...] ] )} [, ...] | ALL FUNCTIONS IN SCHEMA schema_name [, ...] } TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { USAGE | ALL [ PRIVILEGES ] } ON LANGUAGE lang_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { CREATE | USAGE | COMPUTE | ALTER | DROP } [, ...] | ALL [ PRIVILEGES ] } ON NODE GROUP group_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { SELECT | UPDATE } [, ...] | ALL [ PRIVILEGES ] } ON LARGE OBJECT loid [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { CREATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SCHEMA schema_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { CREATE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TABLESPACE tablespace_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPE type_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT { USAGE | ALL [PRIVILEGES] } ON DATA SOURCE src_name [, ...] TO { [GROUP] role_name | PUBLIC } [, ...] [WITH GRANT OPTION]; GRANT { { READ | WRITE } [, ...] | ALL [PRIVILEGES] } ON DIRECTORY directory_name [, ...] TO { [GROUP] role_name | PUBLIC } [, ...] [WITH GRANT OPTION]; GRANT { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON PACKAGE package_name [, ...] TO { [ GROUP ] role_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]; GRANT role_name [, ...] TO role_name [, ...] [ WITH ADMIN OPTION ]; GRANT ALL { PRIVILEGES | PRIVILEGE } TO role_name; ``` ## INSERT Inserts new rows into a table. ``` [ WITH [ RECURSIVE ] with_query [, ...] ] INSERT [/*+ plan_hint */] INTO table_name [ ( column_name [, ...] ) ] { DEFAULT VALUES | VALUES {( { expression | DEFAULT } [, ...] ) }[, ...] | query } [ ON CONFLICT [ conflict_target ] conflict_action ] [ ON DUPLICATE KEY UPDATE { NOTHING | { column_name = { expression | DEFAULT } } [, ...] } ] [ RETURNING {* | {output_expression [ [ AS ] output_name ] }[, ...]} ]; ``` ## LOCK Obtains a table-level lock. ``` LOCK [ TABLE ] {[ ONLY ] name [, ...]| {name [ * ]} [, ...]} [ IN {ACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE | SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVE} MODE ] [ NOWAIT ]; ``` ## MERGE INTO Conditionally matches data in a target table with that in a source table. If data matches, **UPDATE** is executed on the target table; if data does not match, **INSERT** is executed. You can use this syntax to run **UPDATE** and **INSERT** at a time for convenience ``` MERGE [/*+ plan_hint */] INTO table_name [ [ AS ] alias ] USING { { table_name | view_name } | subquery } [ [ AS ] alias ] ON ( condition ) [ WHEN MATCHED THEN UPDATE SET { column_name = { expression | DEFAULT } | ( column_name [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...] [ WHERE condition ] ] [ WHEN NOT MATCHED THEN INSERT { DEFAULT VALUES | [ ( column_name [, ...] ) ] VALUES ( { expression | DEFAULT } [, ...] ) [, ...] [ WHERE condition ] } ]; ``` ## MOVE Repositions a cursor without retrieving any data. **MOVE** works exactly like the **FETCH** command, except it only positions the cursor and does not return rows. ``` MOVE [ direction [ FROM | IN ] ] cursor_name; where direction can be: NEXT | PRIOR | FIRST | LAST | ABSOLUTE count | RELATIVE count | count | ALL | FORWARD | FORWARD count | FORWARD ALL | BACKWARD | BACKWARD count | BACKWARD ALL ``` ## PREPARE Creates a prepared statement. ``` PREPARE name [ ( data_type [, ...] ) ] AS statement; ``` ## PREPARE TRANSACTION Prepares the current transaction for two-phase commit. ``` PREPARE TRANSACTION transaction_id; ``` ## REASSIGN OWNED Changes the owner of the database object. ``` REASSIGN OWNED BY old_role [, ...] TO new_role; ``` ## REFRESH MATERIALIZED VIEW Refreshes a materialized view in complete refresh mode. ``` REFRESH [ INCREMENTAL ] MATERIALIZED VIEW name ``` ## REINDEX Rebuilds an index using the data stored in the index's table, replacing the old copy of the index. ``` REINDEX { INDEX | [INTERNAL] TABLE | DATABASE | SYSTEM } name [ FORCE ]; REINDEX { INDEX | [INTERNAL] TABLE } name PARTITION partition_name [ FORCE ]; ``` ## RESET Restores run-time parameters to their default values. The default values are defined in the **postgresql.conf** configuration file. ``` RESET {configuration_parameter | CURRENT_SCHEMA | TIME ZONE | TRANSACTION ISOLATION LEVEL | SESSION AUTHORIZATION | ALL }; ``` ## REVOKE Revokes permissions from one or more roles. ``` REVOKE [ GRANT OPTION FOR ] { { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | ALTER | DROP | COMMENT | INDEX | VACUUM } [, ...] | ALL [ PRIVILEGES ] } ON { [ TABLE ] table_name [, ...] | ALL TABLES IN SCHEMA schema_name [, ...] } FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { {{ SELECT | INSERT | UPDATE | REFERENCES | COMMENT } ( column_name [, ...] )} [, ...] | ALL [ PRIVILEGES ] ( column_name [, ...] ) } ON [ TABLE ] table_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON { [ SEQUENCE ] sequence_name [, ...] | ALL SEQUENCES IN SCHEMA schema_name [, ...] } FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { CREATE | CONNECT | TEMPORARY | TEMP | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON DATABASE database_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { USAGE | ALL [ PRIVILEGES ] } ON DOMAIN domain_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [PRIVILEGES] } ON CLIENT_MASTER_KEYS client_master_keys_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { USAGE | DROP } [, ...] | ALL [PRIVILEGES]} ON COLUMN_ENCRYPTION_KEYS column_encryption_keys_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { READ | WRITE } [, ...] | ALL [ PRIVILEGES ] } ON DIRECTORY directory_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { USAGE | ALL [ PRIVILEGES ] } ON FOREIGN DATA WRAPPER fdw_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON FOREIGN SERVER server_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON { FUNCTION {function_name ( [ {[ argmode ] [ arg_name ] arg_type} [, ...] ] )} [, ...] | ALL FUNCTIONS IN SCHEMA schema_name [, ...] } FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { USAGE | ALL [ PRIVILEGES ] } ON LANGUAGE lang_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { {CREATE | USAGE | COMPUTE | ALTER | DROP } [, ...] | ALL [ PRIVILEGES ] } ON NODE GROUP group_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { SELECT | UPDATE } [, ...] | ALL [ PRIVILEGES ] } ON LARGE OBJECT loid [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { CREATE | USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON SCHEMA schema_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { CREATE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TABLESPACE tablespace_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { { USAGE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON TYPE type_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ GRANT OPTION FOR ] { USAGE | ALL [ PRIVILEGES ] } ON DATA SOURCE src_name [, ...] FROM { [GROUP] role_name | PUBLIC } [, ...]; REVOKE [ GRANT OPTION FOR ] { { READ | WRITE } [, ...] | ALL [ PRIVILEGES ] } ON DIRECTORY directory_name [, ...] FROM { [GROUP] role_name | PUBLIC } [, ...]; REVOKE [ GRANT OPTION FOR ] { { EXECUTE | ALTER | DROP | COMMENT } [, ...] | ALL [ PRIVILEGES ] } ON PACKAGE package_name [, ...] FROM { [ GROUP ] role_name | PUBLIC } [, ...] [ CASCADE | RESTRICT ]; REVOKE [ ADMIN OPTION FOR ] role_name [, ...] FROM role_name [, ...] [ CASCADE | RESTRICT ]; REVOKE ALL { PRIVILEGES | PRIVILEGE } FROM role_name; ``` ## ROLLBACK Rolls back the current transaction and backs out all updates in the transaction. ``` ROLLBACK [ WORK | TRANSACTION ]; ``` ## ROLLBACK PREPARED Prepares the current transaction for two-phase commit. ``` ROLLBACK PREPARED transaction_id; ``` ## SAVEPOINT Establishes a new savepoint within the current transaction. ``` SAVEPOINT savepoint_name; ``` ## SELECT Retrieves data from a table or view. ``` [ WITH [ RECURSIVE ] with_query [, ...] ] SELECT [/*+ plan_hint */] [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] { * | {expression [ [ AS ] output_name ]} [, ...] } [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY grouping_element [, ...] ] [ HAVING condition [, ...] ] [ WINDOW {window_name AS ( window_definition )} [, ...] ] [ { UNION | INTERSECT | EXCEPT | MINUS } [ ALL | DISTINCT ] select ] [ ORDER BY {expression [ [ ASC | DESC | USING operator ] | nlssort_expression_clause ] [ NULLS { FIRST | LAST } ]} [, ...] ] [ LIMIT { [offset,] count | ALL } ] [ OFFSET start [ ROW | ROWS ] ] [ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ] [ {FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ]} [...] ]; TABLE { ONLY {(table_name)| table_name} | table_name [ * ]}; where from_item can be: [ ONLY ] table_name [ * ] [ partition_clause ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ] [ TABLESAMPLE sampling_method ( argument [, ...] ) [ REPEATABLE ( seed ) ] ] |( select ) [ AS ] alias [ ( column_alias [, ...] ) ] |with_query_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ] |function_name ( [ argument [, ...] ] ) [ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ] |function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] ) |from_item [ NATURAL ] join_type from_item [ ON join_condition | USING ( join_column [, ...] ) ] where grouping_element can be: () |expression |( expression [, ...] ) |ROLLUP ( { expression | ( expression [, ...] ) } [, ...] ) |CUBE ( { expression | ( expression [, ...] ) } [, ...] ) |GROUPING SETS ( grouping_element [, ...] ) where with_query can be: with_query_name [ ( column_name [, ...] ) ] AS ( {select | values | insert | update | delete} ) where partition_clause can be: PARTITION { ( partition_name ) | FOR ( partition_value [, ...] ) } where nlssort_expression_clause can be: NLSSORT ( column_name, ' NLS_SORT = { SCHINESE_PINYIN_M | generic_m_ci } ' ) ``` ## SELECT INTO Defines a new table based on a query result and inserts data obtained by query to the new table. ``` [ WITH [ RECURSIVE ] with_query [, ...] ] SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] { * | {expression [ [ AS ] output_name ]} [, ...] } INTO [ UNLOGGED ] [ TABLE ] new_table [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY expression [, ...] ] [ HAVING condition [, ...] ] [ WINDOW {window_name AS ( window_definition )} [, ...] ] [ { UNION | INTERSECT | EXCEPT | MINUS } [ ALL | DISTINCT ] select ] [ ORDER BY {expression [ [ ASC | DESC | USING operator ] | nlssort_expression_clause ] [ NULLS { FIRST | LAST } ]} [, ...] ] [ LIMIT { count | ALL } ] [ OFFSET start [ ROW | ROWS ] ] [ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ] [ {FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ]} [...] ]; ``` ## SET Modifies a run-time parameter. ``` SET [ LOCAL | SESSION ] { {config_parameter { { TO | = } { value | DEFAULT } | FROM CURRENT }}}; SET [ SESSION | LOCAL ] TIME ZONE { timezone | LOCAL | DEFAULT }; SET [ SESSION | LOCAL ] NAMES encoding_name; SET [ SESSION | LOCAL ] {CURRENT_SCHEMA { TO | = } { schema | DEFAULT } | SCHEMA 'schema'}; SET [ SESSION | LOCAL ] XML OPTION { DOCUMENT | CONTENT }; ``` ## SET CONSTRAINTS Sets a constraint for checking the current transaction. ``` SET CONSTRAINTS { ALL | name [, ...] } { DEFERRED | IMMEDIATE }; ``` ## SET ROLE Sets the current user identifier of the current session. ``` SET [ SESSION | LOCAL ] ROLE role_name PASSWORD 'password'; RESET ROLE; ``` ## SET SESSION AUTHORIZATION Sets the session user identifier and the current user identifier of the current SQL session to a specified user. ``` SET [ SESSION | LOCAL ] SESSION AUTHORIZATION role_name PASSWORD 'password'; {SET [ SESSION | LOCAL ] SESSION AUTHORIZATION DEFAULT | RESET SESSION AUTHORIZATION}; ``` ## SET TRANSACTION Sets constraints for checking the current transaction. ``` {SET [ LOCAL ] TRANSACTION|SET SESSION CHARACTERISTICS AS TRANSACTION} { ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED } | { READ WRITE | READ ONLY | SERIALIZABLE | REPEATABLE READ } } [, ...] SET TRANSACTION SNAPSHOT snapshot_id; ``` ## SHOW Sows the current value of a run-time parameter. ``` SHOW { configuration_parameter | CURRENT_SCHEMA | TIME ZONE | TRANSACTION ISOLATION LEVEL | SESSION AUTHORIZATION | ALL }; ``` ## START TRANSACTION Starts a transaction. If the isolation level or read/write mode is specified, a new transaction will have those characteristics. You can also specify them using **SET TRANSACTION**. ``` START TRANSACTION [ { ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED } | { READ WRITE | READ ONLY | SERIALIZABLE | REPEATABLE READ } } [, ...] ]; ``` ## TRUNCATE Quickly removes all rows from a database table. ``` TRUNCATE [ TABLE ] [ ONLY ] {table_name [ * ]} [, ... ] [ CONTINUE IDENTITY ] [ CASCADE | RESTRICT ]; ALTER TABLE [ IF EXISTS ] { [ ONLY ] table_name | table_name * | ONLY ( table_name ) } TRUNCATE PARTITION { partition_name | FOR ( partition_value [, ...] ) } ; ``` ## UPDATE Updates data in a table. Changes the values of the specified columns in all rows that satisfy the condition. The WHERE clause clarifies conditions. The SET clause specifies the columns to be modified and columns that not specified in the SET clause retain their previous values. ``` UPDATE [/*+ plan_hint */] [ ONLY ] table_name [ * ] [ [ AS ] alias ] SET {column_name = { expression | DEFAULT } | ( column_name [, ...] ) = {( { expression | DEFAULT } [, ...] ) |sub_query } }[, ...] [ FROM from_list] [ WHERE condition ] [ RETURNING {* | {output_expression [ [ AS ] output_name ]} [, ...] }]; ``` ## VACUUM Recycles storage space occupied by rows that have been deleted from a table or B-Tree index. In normal database operation, rows that have been deleted are not physically removed from their table; instead, they remain present until a **VACUUM** is done. Therefore, it is necessary to do **VACUUM** periodically, especially on frequently-updated tables. ``` VACUUM [ ( { FULL | FREEZE | VERBOSE | {ANALYZE | ANALYSE }} [,...] ) ] [ table_name [ (column_name [, ...] ) ] ] [ PARTITION ( partition_name ) ]; VACUUM [ FULL [ COMPACT ] ] [ FREEZE ] [ VERBOSE ] [ table_name ] [ PARTITION ( partition_name ) ]; VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] { ANALYZE | ANALYSE } [ VERBOSE ] [ table_name [ (column_name [, ...] ) ] ] [ PARTITION ( partition_name ) ]; VACUUM DELTAMERGE [ table_name ]; VACUUM HDFSDIRECTORY [ table_name ]; ``` ## VALUES Computes a row or a set of rows based on given values. It is most commonly used to generate a constant table within a large statement. ``` VALUES {( expression [, ...] )} [, ...] [ ORDER BY {sort_expression [ ASC | DESC | USING operator ]} [, ...] ] [ LIMIT { count | ALL } ] [ OFFSET start [ ROW | ROWS ] ] [ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ]; ``` --- --- url: /en/docs/latest-lite/technical_whitepaper/application-scenario.md --- # Application Scenario * Transaction applications Applications need to process highly concurrent online transactions containing a large volume of data, such as e-commerce, finance, O2O, telecom customer relationship management (CRM), and billing. * IoT data In IoT scenarios, such as industrial monitoring, remote control, smart cities, smart homes, and loV, challenges come from a large number of sensors and monitoring devices, high sampling frequency, additional storage modes, and concurrent operation and analysis. --- --- url: /en/docs/latest-lite/about_opengauss/application_scenarios.md --- # Application Scenarios * Transaction applications Applications need to process highly concurrent online transactions containing a large volume of data, such as e-commerce, finance, O2O, telecom customer relationship management (CRM), and billing. * IoT data In IoT scenarios, such as industrial monitoring, remote control, smart cities, smart homes, and loV, challenges come from a large number of sensors and monitoring devices, high sampling frequency, additional storage modes, and concurrent operation and analysis. --- --- url: /en/docs/latest/about_opengauss/application_scenarios.md --- # Application Scenarios * Transaction applications Applications need to process highly concurrent online transactions containing a large volume of data, such as e-commerce, finance, O2O, telecom customer relationship management (CRM), and billing. * IoT data In IoT scenarios, such as industrial monitoring, remote control, smart cities, smart homes, and loV, challenges come from a large number of sensors and monitoring devices, high sampling frequency, additional storage modes, and concurrent operation and analysis. --- --- url: /en/docs/latest-lite/database_om_guide/architecture.md --- # Architecture Changes on publishers are sent to subscribers in real time as they occur. The subscriber applies data in the order in which it is committed on the publisher to ensure transactional consistency of publications in any single subscription. Logical replication is built with an architecture similar to physical streaming replication. It is implemented by the walsender and apply processes. The walsender process starts logical decoding of the WAL and loads the standard logical decoding plug-in (pgoutput). The plug-in transforms the changes read from the WAL into a logical replication protocol and filters the data according to the publication specifications. The data is then continuously transferred to the apply worker using the streaming replication protocol, and the apply worker maps the data to the local table and applies the changes they receive in the correct transactional order. The apply process in the subscriber database always runs with **session\_replication\_role** set to **replica**, which produces the usual effects on triggers and constraints. The logical replication apply process currently fires only row triggers, not statement triggers. However, the initial table synchronization is implemented through methods similar to **COPY** command execution, and therefore, row and statement triggers for INSERT are fired. --- --- url: /en/docs/latest/database_om_guide/architecture.md --- # Architecture Changes on publishers are sent to subscribers in real time as they occur. The subscriber applies data in the order in which it is committed on the publisher to ensure transactional consistency of publications in any single subscription. Logical replication is built with an architecture similar to physical streaming replication. It is implemented by the walsender and apply processes. The walsender process starts logical decoding of the WAL and loads the standard logical decoding plug-in (pgoutput). The plug-in transforms the changes read from the WAL into a logical replication protocol and filters the data according to the publication specifications. The data is then continuously transferred to the apply worker using the streaming replication protocol, and the apply worker maps the data to the local table and applies the changes they receive in the correct transactional order. The apply process in the subscriber database always runs with **session\_replication\_role** set to **replica**, which produces the usual effects on triggers and constraints. The logical replication apply process currently fires only row triggers, not statement triggers. However, the initial table synchronization is implemented through methods similar to **COPY** command execution, and therefore, row and statement triggers for INSERT are fired. --- --- url: /en/docs/latest-lite/database_reference/archiving.md --- # Archiving ## archive\_mode **Parameter description**: Specifies whether to archive WALs. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * When **[wal\_level](settings.md#en-us_topic_0283137354_en-us_topic_0237124707_en-us_topic_0059778393_s2c76f5957066407a959191148f2c780f)** is set to **minimal**, the **archive\_mode** parameter is unavailable. > * The archiving function can be enabled on both the synchronous and asynchronous standby nodes. The method of enabling the archiving function is the same as that of enabling the archiving function on a single node. To enable the archiving function, set **archive\_mode** to **on** and set **archive\_dest** or **archive\_command** correctly. > * If the maximum availability mode is not enabled and the standby node is disconnected from the primary node, the primary node cannot send the archiving location to the standby node due to service congestion. As a result, the archiving fails. **Value range**: Boolean * **on** indicates that the archiving is enabled. * **off** indicates that the archiving is disabled. **Default value**: **off** ## archive\_command **Parameter description:** Specifies the command set by the administrator to archive WALs. You are advised to set the archive log path to an absolute path. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * If both **archive\_dest** and **archive\_command** are configured, WALs are preferentially saved to the directory specified by **archive\_dest**. The command configured by **archive\_command** does not take effect. > * Any **%p** in the string is replaced by the absolute path of the file to archive, and any **%f** is replaced by only the file name. (The relative path is relative to the data directory.) Use **%%** to embed an actual **%** character in the command. > * This command returns zero only if it succeeds. The command example is as follows: > > ``` > archive_command = 'cp --remove-destination %p /mnt/server/archivedir/%f' > ``` > > * **--remove-destination** indicates that files will be overwritten during the archiving. > * If there are multiple archive commands, write them to the shell script file and set **archive\_command** to the command for executing the script. The command example is as follows: > > ``` > -- Assume that multiple commands are as follows: > test ! -f dir/%f && cp %p dir/%f > -- The content of the test.sh script is as follows: > test ! -f dir/$2 && cp $1 dir/$2 > -- The archive command is as follows: > archive_command='sh dir/test.sh %p %f' > ``` **Value range**: a string **Default value:** **(disabled)** ## archive\_dest **Parameter description:** Specifies the path set by the administrator to archive WALs. You are advised to set the archive log path to an absolute path. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * If both **archive\_dest** and **archive\_command** are configured, WALs are preferentially saved to the directory specified by **archive\_dest**. The command configured by **archive\_command** does not take effect. > * If the string is a relative path, it is relative to the data directory. The following is an example: > > ``` > archive_dest = '/mnt/server/archivedir/' > ``` **Value range**: a string **Default value**: empty ## archive\_timeout **Parameter description**: Specifies the archiving period. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * The server is forced to switch to a new WAL segment file when the period specified by this parameter has elapsed since the last file switch. > * Archived files that are closed early due to a forced switch are still of the same length as full files. Therefore, a very short **archive\_timeout** will bloat the archive storage. You are advised to set **archive\_timeout** to **60s**. **Value range**: an integer ranging from 0 to 1073741823. The unit is second. **0** indicates that archiving timeout is disabled. **Default value**: **0** --- --- url: /en/docs/latest/database_reference/archiving.md --- # Archiving ## archive\_mode **Parameter description**: Specifies whether to archive WALs. This parameter is a **SIGHUP** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * When **[wal\_level](settings.md#en-us_topic_0283137354_en-us_topic_0237124707_en-us_topic_0059778393_s2c76f5957066407a959191148f2c780f)** is set to **minimal**, the **archive\_mode** parameter is unavailable. **Value range**: Boolean * **on** indicates that the archiving is enabled. * **off** indicates that the archiving is disabled. **Default value**: **off** ## archive\_command **Parameter description:** Specifies the command set by the administrator to archive WALs. You are advised to set the archive log path to an absolute path. This parameter is a **SIGHUP** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * If both **archive\_dest** and **archive\_command** are configured, WALs are preferentially saved to the directory specified by **archive\_dest**. The command configured by **archive\_command** does not take effect. > * Any **%p** in the string is replaced by the absolute path of the file to archive, and any **%f** is replaced by only the file name. (The relative path is relative to the data directory.) Use **%%** to embed an actual **%** character in the command. > * This command returns zero only if it succeeds. The command example is as follows: > > ``` > archive_command = 'cp --remove-destination %p /mnt/server/archivedir/%f' > ``` > > * **--remove-destination** indicates that files will be overwritten during the archiving. > * If there are multiple archive commands, write them to the shell script file and set **archive\_command** to the command for executing the script. The command example is as follows: > > ``` > -- Assume that multiple commands are as follows: > test ! -f dir/%f && cp %p dir/%f > -- The content of the test.sh script is as follows: > test ! -f dir/$2 && cp $1 dir/$2 > -- The archive command is as follows: > archive_command='sh dir/test.sh %p %f' > ``` **Value range**: a string **Default value:** **(disabled)** ## archive\_dest **Parameter description:** Specifies the path set by the administrator to archive WALs. You are advised to set the archive log path to an absolute path. This parameter is a **SIGHUP** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * If both **archive\_dest** and **archive\_command** are configured, WALs are preferentially saved to the directory specified by **archive\_dest**. The command configured by **archive\_command** does not take effect. > * If the string is a relative path, it is relative to the data directory. The following is an example: > > ``` > archive_dest = '/mnt/server/archivedir/' > ``` **Value range**: a string **Default value**: empty ## archive\_timeout **Parameter description**: Specifies the archiving period. This parameter is a **SIGHUP** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * The server is forced to switch to a new WAL segment file when the period specified by this parameter has elapsed since the last file switch. > * Archived files that are closed early due to a forced switch are still of the same length as full files. Therefore, a very short **archive\_timeout** will bloat the archive storage. You are advised to set **archive\_timeout** to **60s**. **Value range**: an integer ranging from 0 to 1073741823. The unit is s. **0** indicates that archiving timeout is disabled. **Default value**: **0** --- --- url: >- /en/docs/latest-lite/database_administration_guide/archiving_a_ledger_database.md --- # Archiving a Ledger Database ## Prerequisites * You are an audit administrator or a role that has the audit administrator permissions. * The database is running properly, and a series of addition, deletion, and modification operations are performed on the tamper-proof database to ensure that operation records are generated in the ledger for query. * The storage path **audit\_directory** of audit files has been correctly configured in the database. ## Context * Currently, the ledger database provides two archiving interfaces: [ledger\_hist\_archive(text...](../sql_reference/ledger_database_functions.md) and \[ledger\_gchain\_archive(vo...]\(../sql\_reference/ledger\_database\_functions.md. Only the audit administrator can invoke the ledger database interfaces. * The interface for archiving the user history table is **pg\_catalog.ledger\_hist\_archive**. To archive the table, run the following command: ``` SELECT pg_catalog.ledger_hist_archive(schema_name text,table_name text); ``` If the archiving is successful, the function returns **t**. Otherwise, the function returns **f**. * The interface for archiving the global blockchain table is **pg\_catalog.ledger\_gchain\_archive**. To archive the table, run the following command: ``` SELECT pg_catalog.ledger_gchain_archive(); ``` If the archiving is successful, the function returns **t**. Otherwise, the function returns **f**. ## Procedure 1. Archive a specified user history table. ``` openGauss=# SELECT pg_catalog.ledger_hist_archive('ledgernsp', 'usertable') ``` The command output is as follows: ``` ledger_hist_archive --------------------- t (1 row) ``` The user history table is archived as a record: ``` openGauss=# SELECT * FROM blockchain.ledgernsp_usertable_hist; rec_num | hash_ins | hash_del | pre_hash ---------+------------------+------------------+---------------------------------- 3 | e78e75b00d396899 | 8fcd74a8a6a4b484 | fd61cb772033da297d10c4e658e898d7 (1 row) ``` The command output indicates that the user history table of the current node is exported successfully. 2. Export the global blockchain table. ``` openGauss=# SELECT pg_catalog.ledger_gchain_archive(); ``` The command output is as follows: ``` ledger_gchain_archive ----------------------- t (1 row) ``` The global history table will be archived to *n* (number of user tables) data records by user table: ``` openGauss=# SELECT * FROM gs_global_chain; blocknum | dbname | username | starttime | relid | relnsp | relname | relhash | globalhash | txcommand ----------+----------+----------+-------------------------------+-------+-----------+-----------+------------------+----------------------------------+----------- 1 | postgres | libc | 2021-05-10 19:59:38.619472+08 | 16388 | ledgernsp | usertable | 57c101076694b415 | be82f98ee68b2bc4e375f69209345406 | Archived. (1 row) ``` The command output indicates that the global blockchain table of the current node is successfully exported. --- --- url: /en/docs/latest/database_administration_guide/archiving_a_ledger_database.md --- # Archiving a Ledger Database ## Prerequisites * You are an audit administrator or a role that has the audit administrator permissions. * The database is running properly, and a series of addition, deletion, and modification operations are performed on the tamper-proof database to ensure that operation records are generated in the ledger for query. * The storage path **audit\_directory** of audit files has been correctly configured in the database. ## Context * Currently, the ledger database provides two archiving interfaces: [ledger\_hist\_archive(text...](../sql_reference/ledger_database_functions.md) and [ledger\_gchain\_archive(vo...](../sql_reference/ledger_database_functions.md). Only the audit administrator can invoke the ledger database interfaces. * The interface for archiving the user history table is **pg\_catalog.ledger\_hist\_archive**. To archive the table, run the following command: ``` SELECT pg_catalog.ledger_hist_archive(schema_name text,table_name text); ``` If the archiving is successful, the function returns **t**. Otherwise, the function returns **f**. * The interface for archiving the global blockchain table is **pg\_catalog.ledger\_gchain\_archive**. To archive the table, run the following command: ``` SELECT pg_catalog.ledger_gchain_archive(); ``` If the archiving is successful, the function returns **t**. Otherwise, the function returns **f**. ## Procedure 1. Archive a specified user history table. ``` openGauss=# SELECT pg_catalog.ledger_hist_archive('ledgernsp', 'usertable'); ``` The command output is as follows: ``` ledger_hist_archive --------------------- t (1 row) ``` The user history table is archived as a record: ``` openGauss=# SELECT * FROM blockchain.ledgernsp_usertable_hist; rec_num | hash_ins | hash_del | pre_hash ---------+------------------+------------------+---------------------------------- 3 | e78e75b00d396899 | 8fcd74a8a6a4b484 | fd61cb772033da297d10c4e658e898d7 (1 row) ``` The command output indicates that the user history table of the current node is exported successfully. 2. Export the global blockchain table. ``` openGauss=# SELECT pg_catalog.ledger_gchain_archive(); ``` The command output is as follows: ``` ledger_gchain_archive ----------------------- t (1 row) ``` The global history table will be archived to *n* (number of user tables) data records by user table: ``` openGauss=# SELECT * FROM gs_global_chain; blocknum | dbname | username | starttime | relid | relnsp | relname | relhash | globalhash | txcommand ----------+----------+----------+-------------------------------+-------+-----------+-----------+------------------+----------------------------------+----------- 1 | postgres | libc | 2021-05-10 19:59:38.619472+08 | 16388 | ledgernsp | usertable | 57c101076694b415 | be82f98ee68b2bc4e375f69209345406 | Archived. (1 row) ``` The command output indicates that the global blockchain table of the current node is successfully exported. --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_arithmetic_functions_and_operators.md --- # Arithmetic Functions and Operators Compared with the original openGauss, Dolphin modifies the time/date function as follows: 1. The DIV, MOD, XOR, and ^ operators are added. 2. The truncate, rand, crc32, conv, float8\_bool, oct, and float4\_bool functions are added. 3. Implement the atan function to support the usage of atan(y, x). * DIV Description: Division (rounded) Example: ``` openGauss=# SELECT 8 DIV 3 AS RESULT; result -------- 2 (1 row) ``` * MOD Description: Model (to obtain the remainder) Example: ``` openGauss=# SELECT 4 MOD 3 AS RESULT; result -------- 1 (1 row) ``` * XOR Description: Binary XOR Example: ``` openGauss=# SELECT 4 XOR 3 AS RESULT; result -------- 0 (1 row) ``` * truncate(v numeric, s int) Description: Truncates a number with **s** digits after the decimal point. It is equivalent to trunc. Return type: numeric Example: ``` openGauss=# SELECT truncate(42.4382, 2); truncate ---------- 42.43 (1 row) ``` * rand() Description: Random number between 0.0 and 1.0 It is equivalent to random. Return type: double precision Example: ``` openGauss=# SELECT rand(); rand ------------------- 0.254671605769545 (1 row) ``` * crc32(string) Description: Calculates the crc32 value of string. Return type: int Example: ``` openGauss=# SELECT crc32('abc'); crc32 ----------- 891568578 (1 row) ``` * conv(input in, current\_base int, new\_base int) Description: Converts a number or string from one number base system to another. The value of in can be a number or a character string. Return type: text Example: ``` openGauss=# SELECT conv(20, 10, 2); conv ------- 10100 (1 row) openGauss=# SELECT conv('8D', 16, 10); conv ------ 141 (1 row) ``` * ^ Description: Implements bitwise XOR between two integers. Return type: INT Example: ``` openGauss=# SELECT 1^1; ?column? ---------- 0 (1 row) ``` Description: After `set b_compatibility_mode` is set to `1`, the float data can be bitwise XOR or XOR after rounded off. Return type: DOUBLE Example: ``` openGauss=# select 0.5678::float^1.1234::float; ?column? ---------- 0 (1 row) ``` * float8\_bool(float) Description: Returns a Boolean value based on the value of a floating point number. If the value is **0**, **false** is returned. Otherwise, **true** is returned. Return type: Boolean Example: ``` openGauss=# select float8_bool(0.1); float8_bool ------------- t (1 row) ``` ``` openGauss=# select float8_bool(0.0); float8_bool ------------- f (1 row) ``` * oct(input N) Description: Converts a number or string from a decimal number to an octal number. Return type: text Example: ``` openGauss=# SELECT OCT(10); oct ----- 12 (1 row) openGauss=# SELECT OCT('10'); oct ----- 12 (1 row) ``` * float4\_bool(float) Description: Returns a Boolean value based on the value of a floating point number. If the value is **0**, **false** is returned. Otherwise, **true** is returned. Return type: Boolean Example: ``` openGauss=# select float4_bool(0.1); float4_bool ------------- t (1 row) ``` ``` openGauss=# select float4_bool(0.0); float4_bool ------------- f (1 row) ``` * atan(y, x) Description: Arc tangent of y/x. Return type: double precision Example: ``` openGauss=# SELECT atan(2, 1); atan ------------------ 1.10714871779409 (1 row) ``` --- --- url: /en/docs/latest-lite/sql_reference/array_expressions.md --- # Array Expressions ## IN *expression *\*\*IN \*\**(value \[, ...])* The parentheses on the right contain an expression list. The expression result on the left is compared with the content in the expression list. If the content in the list meets the expression result on the left, the result of **IN** is **true**. If no result meets the requirements, the result of **IN** is **false**. Example: ``` openGauss=# SELECT 8000+500 IN (10000, 9000) AS RESULT; result ---------- f (1 row) ``` If the expression result is null or the expression list does not meet the expression conditions and at least one empty value is returned for the expression list on the right, the result of **IN** is **null** rather than **false**. This method is consistent with the Boolean rules used when SQL statements return empty values. ## NOT IN *expression ***NOT IN*** (value \[, ...])* The parentheses on the right contain an expression list. The expression result on the left is compared with the content in the expression list. If the content in the list does not meet the expression result on the left, the result of **NOT IN** is **true**. If any content meets the expression result, the result of **NOT IN** is **false**. Example: ``` openGauss=# SELECT 8000+500 NOT IN (10000, 9000) AS RESULT; result ---------- t (1 row) ``` If the query statement result is null or the expression list does not meet the expression conditions and at least one empty value is returned for the expression list on the right, the result of **NOT IN** is **null** rather than **false**. This method is consistent with the Boolean rules used when SQL statements return empty values. > \[!NOTE]NOTE > In all situations, **X NOT IN Y** equals to **NOT(X IN Y)**. ## ANY/SOME (array) *expression operator *\*\*ANY \*\**(array expression)* *expression operator *\*\*SOME \*\**(array expression)* ``` openGauss=# SELECT 8000+500 < SOME (array[10000,9000]) AS RESULT; result ---------- t (1 row) ``` ``` openGauss=# SELECT 8000+500 < ANY (array[10000,9000]) AS RESULT; result ---------- t (1 row) ``` The right-hand side is a parenthesized expression, which must yield an array value. The result of the expression on the left uses operators to compute and compare the results in each row of the array expression. The comparison result must be a Boolean value. * If at least one comparison result is true, the result of **ANY** is **true**. * If no comparison result is true, the result of ANY is false. * If no comparison result is true and the array expression generates at least one null value, the value of ANY is NULL, rather than false. This method is consistent with the Boolean rules used when SQL statements return empty values. > \[!NOTE]NOTE > **SOME** is a synonym of **ANY**. ## ALL (array) *expression operator *\*\*ALL \*\**(array expression)* The right-hand side is a parenthesized expression, which must yield an array value. The result of the expression on the left uses operators to compute and compare the results in each row of the array expression. The comparison result must be a Boolean value. * The result of **ALL** is **true** if all comparisons yield **true** (including the case where the array has zero elements). * The result of **ALL** is **false** if one or multiple comparisons yield **false**. * If the array expression yields a null array, the result of **ALL** will be null. If the left-hand expression yields null, the result of **ALL** is ordinarily null (though a non-strict comparison operator could possibly yield a different result). Also, if the right-hand array contains any null elements and no false comparison result is obtained, the result of **ALL** will be null, not true (again, assuming a strict comparison operator). This method is consistent with the Boolean rules used when SQL statements return empty values. ``` openGauss=# SELECT 8000+500 < ALL (array[10000,9000]) AS RESULT; result ---------- t (1 row) ``` --- --- url: /en/docs/latest/sql_reference/array_expressions.md --- # Array Expressions ## IN expression **IN** (value \[, ...]) The parentheses on the right contain an expression list. The expression result on the left is compared with the content in the expression list. If the content in the list meets the expression result on the left, the result of **IN** is **true**. If no result meets the requirements, the result of **IN** is **false**. Example: ``` openGauss=# SELECT 8000+500 IN (10000, 9000) AS RESULT; result ---------- f (1 row) ``` If the expression result is null or the expression list does not meet the expression conditions and at least one empty value is returned for the expression list on the right, the result of **IN** is **null** rather than **false**. This method is consistent with the Boolean rules used when SQL statements return empty values. ## NOT IN expression **NOT IN** (value \[, ...]) The parentheses on the right contain an expression list. The expression result on the left is compared with the content in the expression list. If the content in the list does not meet the expression result on the left, the result of **NOT IN** is **true**. If any content meets the expression result, the result of **NOT IN** is **false**. Example: ``` openGauss=# SELECT 8000+500 NOT IN (10000, 9000) AS RESULT; result ---------- t (1 row) ``` If the query statement result is null or the expression list does not meet the expression conditions and at least one empty value is returned for the expression list on the right, the result of **NOT IN** is **null** rather than **false**. This method is consistent with the Boolean rules used when SQL statements return empty values. > \[!NOTE]NOTE > In all situations, **X NOT IN Y** equals to **NOT(X IN Y)**. ## ANY/SOME (array) expression operator **ANY** (array expression) expression operator **SOME** (array expression) ``` openGauss=# SELECT 8000+500 < SOME (array[10000,9000]) AS RESULT; result ---------- t (1 row) ``` ``` openGauss=# SELECT 8000+500 < ANY (array[10000,9000]) AS RESULT; result ---------- t (1 row) ``` The right-hand side is a parenthesized expression, which must yield an array value. The result of the expression on the left uses operators to compute and compare the results in each row of the array expression. The comparison result must be a Boolean value. * If at least one comparison result is true, the result of **ANY** is **true**. * If no comparison result is true, the result of ANY is false. * If no comparison result is true and the array expression generates at least one null value, the value of ANY is NULL, rather than false. This method is consistent with the Boolean rules used when SQL statements return empty values. > \[!NOTE]NOTE > **SOME** is a synonym of **ANY**. ## ALL (array) expression operator **ALL** (array expression) The right-hand side is a parenthesized expression, which must yield an array value. The result of the expression on the left uses operators to compute and compare the results in each row of the array expression. The comparison result must be a Boolean value. * The result of **ALL** is **true** if all comparisons yield **true** (including the case where the array has zero elements). * The result of **ALL** is **false** if one or multiple comparisons yield **false**. * If the array expression yields a null array, the result of **ALL** will be null. If the left-hand expression yields null, the result of **ALL** is ordinarily null (though a non-strict comparison operator could possibly yield a different result). Also, if the right-hand array contains any null elements and no false comparison result is obtained, the result of **ALL** will be null, not true (again, assuming a strict comparison operator). This method is consistent with the Boolean rules used when SQL statements return empty values. ``` openGauss=# SELECT 8000+500 < ALL (array[10000,9000]) AS RESULT; result ---------- t (1 row) ``` --- --- url: /en/docs/latest-lite/sql_reference/array_functions_and_operators.md --- # Array Functions and Operators ## Array Operators * \= Description: Specifies whether two arrays are equal. Example: ``` openGauss=# SELECT ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3] AS RESULT ; result -------- t (1 row) ``` * <> Description: Specifies whether two arrays are not equal. Example: ``` openGauss=# SELECT ARRAY[1,2,3] <> ARRAY[1,2,4] AS RESULT; result -------- t (1 row) ``` * < Description: Specifies whether an array is less than another. Example: ``` openGauss=# SELECT ARRAY[1,2,3] < ARRAY[1,2,4] AS RESULT; result -------- t (1 row) ``` * \> Description: Specifies whether an array is greater than another. Example: ``` openGauss=# SELECT ARRAY[1,4,3] > ARRAY[1,2,4] AS RESULT; result -------- t (1 row) ``` * <= Description: Specifies whether an array is less than another. Example: ``` openGauss=# SELECT ARRAY[1,2,3] <= ARRAY[1,2,3] AS RESULT; result -------- t (1 row) ``` * \>= Description: Specifies whether an array is greater than or equal to another. Example: ``` openGauss=# SELECT ARRAY[1,4,3] >= ARRAY[1,4,3] AS RESULT; result -------- t (1 row) ``` * @> Description: Specifies whether an array contains another. Example: ``` openGauss=# SELECT ARRAY[1,4,3] @> ARRAY[3,1] AS RESULT; result -------- t (1 row) ``` * <@ Description: Specifies whether an array is contained in another. Example: ``` openGauss=# SELECT ARRAY[2,7] <@ ARRAY[1,7,4,2,6] AS RESULT; result -------- t (1 row) ``` * && Description: Specifies whether an array overlaps another (have common elements). Example: ``` openGauss=# SELECT ARRAY[1,4,3] && ARRAY[2,1] AS RESULT; result -------- t (1 row) ``` * || Description: Array-to-array concatenation Example: ``` openGauss=# SELECT ARRAY[1,2,3] || ARRAY[4,5,6] AS RESULT; result --------------- {1,2,3,4,5,6} (1 row) ``` ``` openGauss=# SELECT ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9]] AS RESULT; result --------------------------- {{1,2,3},{4,5,6},{7,8,9}} (1 row) ``` * || Description: Element-to-array concatenation Example: ``` openGauss=# SELECT 3 || ARRAY[4,5,6] AS RESULT; result ----------- {3,4,5,6} (1 row) ``` * || Description: Array-to-element concatenation Example: ``` openGauss=# SELECT ARRAY[4,5,6] || 7 AS RESULT; result ----------- {4,5,6,7} (1 row) ``` Array comparisons compare the array contents element-by-element, using the default B-tree comparison function for the element data type. In multidimensional arrays, the elements are accessed in row-major order. If the contents of two arrays are equal but the dimensionality is different, the first difference in the dimensionality information determines the sort order. ## Array Functions * array\_append(anyarray, anyelement) Description: Appends an element to the end of an array, and only supports dimension-1 arrays. Return type: anyarray Example: ``` openGauss=# SELECT array_append(ARRAY[1,2], 3) AS RESULT; result --------- {1,2,3} (1 row) ``` * array\_prepend(anyelement, anyarray) Description: Appends an element to the beginning of an array, and only supports dimension-1 arrays. Return type: anyarray Example: ``` openGauss=# SELECT array_prepend(1, ARRAY[2,3]) AS RESULT; result --------- {1,2,3} (1 row) ``` * array\_cat(anyarray, anyarray) Description: Concatenates two arrays, and supports multi-dimensional arrays. Return type: anyarray Example: ``` openGauss=# SELECT array_cat(ARRAY[1,2,3], ARRAY[4,5]) AS RESULT; result ------------- {1,2,3,4,5} (1 row) openGauss=# SELECT array_cat(ARRAY[[1,2],[4,5]], ARRAY[6,7]) AS RESULT; result --------------------- {{1,2},{4,5},{6,7}} (1 row) ``` * array\_union(anyarray, anyarray) Description: Concatenates two arrays, and supports only one-dimensional arrays. Return type: anyarray Example: ``` openGauss=# SELECT array_union(ARRAY[1,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {1,2,3,3,4,5} (1 row) ``` * array\_union\_distinct(anyarray, anyarray) Description: Concatenates two arrays and deduplicates them. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_union_distinct(ARRAY[1,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {1,2,3,4,5} (1 row) ``` * array\_intersect(anyarray, anyarray) Description: Intersects two arrays. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_intersect(ARRAY[1,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {3} (1 row) ``` * array\_intersect\_distinct(anyarray, anyarray) Description: Intersects two arrays and deduplicates them. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_intersect_distinct(ARRAY[1,2,2], ARRAY[2,2,4,5]) AS RESULT; result ------------- {2} (1 row) ``` * array\_except(anyarray, anyarray) Description: Calculates the difference between two arrays. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_except(ARRAY[1,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {1,2} (1 row) ``` * array\_except\_distinct(anyarray, anyarray) Description: Calculates the difference between two arrays and deduplicates them. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_except_distinct(ARRAY[1,2,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {1,2} (1 row) ``` * array\_ndims(anyarray) Description: Returns the number of dimensions of an array. Return type: int Example: ``` openGauss=# SELECT array_ndims(ARRAY[[1,2,3], [4,5,6]]) AS RESULT; result -------- 2 (1 row) ``` * array\_dims(anyarray) Description: Returns the low-order flag bits and high-order flag bits of each dimension in an array. Return type: text Example: ``` openGauss=# SELECT array_dims(ARRAY[[1,2,3], [4,5,6]]) AS RESULT; result ------------ [1:2][1:3] (1 row) ``` * array\_length(anyarray, int) Description: Returns the length of the requested array dimension. **int** is the requested array dimension. Return type: int Example: ``` openGauss=# SELECT array_length(array[1,2,3], 1) AS RESULT; result -------- 3 (1 row) openGauss=# SELECT array_length(array[[1,2,3],[4,5,6]], 2) AS RESULT; result -------- 3 (1 row) ``` * array\_lower(anyarray, int) Description: Returns lower bound of the requested array dimension. **int** is the requested array dimension. Return type: int Example: ``` openGauss=# SELECT array_lower('[0:2]={1,2,3}'::int[], 1) AS RESULT; result -------- 0 (1 row) ``` * array\_upper(anyarray, int) Description: Returns upper bound of the requested array dimension. **int** is the requested array dimension. Return type: int Example: ``` openGauss=# SELECT array_upper(ARRAY[1,8,3,7], 1) AS RESULT; result -------- 4 (1 row) ``` * array\_upper(anyarray, int) Description: Returns upper bound of the requested array dimension. **int** is the requested array dimension. Return type: int Example: ``` openGauss=# SELECT array_upper(ARRAY[1,8,3,7], 1) AS RESULT; result -------- 4 (1 row) ``` * array\_remove(anyarray, anyelement) Description: Removes all specified elements from an array. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_remove(ARRAY[1,8,8,7], 8) AS RESULT; result -------- {1,7} (1 row) ``` * array\_to\_string(anyarray, text \[, text]) Description: Uses the first **text** as the new delimiter and the second **text** to replace **NULL** values. Return type: text Example: ``` openGauss=# SELECT array_to_string(ARRAY[1, 2, 3, NULL, 5], ',', '*') AS RESULT; result ----------- 1,2,3,*,5 (1 row) ``` * array\_delete(anyarray) Description: Clears elements in an array and returns an empty array of the same type. Return type: anyarray Example: ``` openGauss=# SELECT array_delete(ARRAY[1,8,3,7]) AS RESULT; result -------- {} (1 row) ``` * array\_deleteidx(anyarray, int) Description: Deletes specified subscript elements from an array and returns an array consisting of the remaining elements. Return type: anyarray Example: ``` openGauss=# SELECT array_deleteidx(ARRAY[1,2,3,4,5], 1) AS RESULT; result ----------- {2,3,4,5} (1 row) ``` * array\_extendnull(anyarray, int) Description: This API has been discarded and is unavailable currently. * array\_trim(anyarray, int) Description: Deletes a specified number of elements from the end of an array. Return type: anyarray Example: ``` openGauss=# SELECT array_trim(ARRAY[1,8,3,7],1) AS RESULT; result --------- {1,8,3} (1 row) ``` * array\_exists(anyarray, int) Description: Checks whether the second parameter is a valid subscript of an array. Return type: Boolean Example: ``` openGauss=# SELECT array_exists(ARRAY[1,8,3,7],1) AS RESULT; result -------- t (1 row) ``` * array\_next(anyarray, int) Description: Returns the subscript of the element following a specified subscript in an array based on the second input parameter. Return type: int Example: ``` openGauss=# SELECT array_next(ARRAY[1,8,3,7],1) AS RESULT; result -------- 2 (1 row) ``` * array\_prior(anyarray, int) Description: Returns the subscript of the element followed by a specified subscript in an array based on the second input parameter. Return type: int Example: ``` openGauss=# SELECT array_prior(ARRAY[1,8,3,7],2) AS RESULT; result -------- 1 (1 row) ``` * string\_to\_array(text, text \[, text]) Description: Uses the second **text** as the new delimiter and the third **text** as the substring to be replaced by **NULL** values. A substring can be replaced by **NULL** values only when it is the same as the third **text**. Return type: text\[] Example: ``` openGauss=# SELECT string_to_array('xx~^~yy~^~zz', '~^~', 'yy') AS RESULT; result -------------- {xx,NULL,zz} (1 row) openGauss=# SELECT string_to_array('xx~^~yy~^~zz', '~^~', 'y') AS RESULT; result ------------ {xx,yy,zz} (1 row) ``` * unnest(anyarray) Description: Expands an array to a set of rows. Return type: setof anyelement Example: ``` openGauss=# SELECT unnest(ARRAY[1,2]) AS RESULT; result -------- 1 2 (2 rows) ``` In **string\_to\_array**, if the delimiter parameter is NULL, each character in the input string will become a separate element in the resulting array. If the delimiter is an empty string, then the entire input string is returned as a one-element array. Otherwise the input string is split at each occurrence of the delimiter string. In **string\_to\_array**, if the null-string parameter is omitted or NULL, none of the substrings of the input will be replaced by NULL. In **array\_to\_string**, if the null-string parameter is omitted or NULL, any null elements in the array are simply skipped and not represented in the output string. --- --- url: /en/docs/latest/sql_reference/array_functions_and_operators.md --- # Array Functions and Operators ## Array Operators * \= Description: Specifies whether two arrays are equal. Example: ``` openGauss=# SELECT ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3] AS RESULT ; result -------- t (1 row) ``` * <> Description: Specifies whether two arrays are not equal. Example: ``` openGauss=# SELECT ARRAY[1,2,3] <> ARRAY[1,2,4] AS RESULT; result -------- t (1 row) ``` * < Description: Specifies whether an array is less than another. Example: ``` openGauss=# SELECT ARRAY[1,2,3] < ARRAY[1,2,4] AS RESULT; result -------- t (1 row) ``` * \> Description: Specifies whether an array is greater than another. Example: ``` openGauss=# SELECT ARRAY[1,4,3] > ARRAY[1,2,4] AS RESULT; result -------- t (1 row) ``` * <= Description: Specifies whether an array is less than another. Example: ``` openGauss=# SELECT ARRAY[1,2,3] <= ARRAY[1,2,3] AS RESULT; result -------- t (1 row) ``` * \>= Description: Specifies whether an array is greater than or equal to another. Example: ``` openGauss=# SELECT ARRAY[1,4,3] >= ARRAY[1,4,3] AS RESULT; result -------- t (1 row) ``` * @> Description: Specifies whether an array contains another. Example: ``` openGauss=# SELECT ARRAY[1,4,3] @> ARRAY[3,1] AS RESULT; result -------- t (1 row) ``` * <@ Description: Specifies whether an array is contained in another. Example: ``` openGauss=# SELECT ARRAY[2,7] <@ ARRAY[1,7,4,2,6] AS RESULT; result -------- t (1 row) ``` * && Description: Specifies whether an array overlaps another (have common elements). Example: ``` openGauss=# SELECT ARRAY[1,4,3] && ARRAY[2,1] AS RESULT; result -------- t (1 row) ``` * || Description: Array-to-array concatenation Example: ``` openGauss=# SELECT ARRAY[1,2,3] || ARRAY[4,5,6] AS RESULT; result --------------- {1,2,3,4,5,6} (1 row) ``` ``` openGauss=# SELECT ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9]] AS RESULT; result --------------------------- {{1,2,3},{4,5,6},{7,8,9}} (1 row) ``` * || Description: Element-to-array concatenation Example: ``` openGauss=# SELECT 3 || ARRAY[4,5,6] AS RESULT; result ----------- {3,4,5,6} (1 row) ``` * || Description: Array-to-element concatenation Example: ``` openGauss=# SELECT ARRAY[4,5,6] || 7 AS RESULT; result ----------- {4,5,6,7} (1 row) ``` Array comparisons compare the array contents element-by-element, using the default B-tree comparison function for the element data type. In multidimensional arrays, the elements are accessed in row-major order. If the contents of two arrays are equal but the dimensionality is different, the first difference in the dimensionality information determines the sort order. ## Array Functions * array\_append(anyarray, anyelement) Description: Appends an element to the end of an array, and only supports dimension-1 arrays. Return type: anyarray Example: ``` openGauss=# SELECT array_append(ARRAY[1,2], 3) AS RESULT; result --------- {1,2,3} (1 row) ``` * array\_prepend(anyelement, anyarray) Description: Appends an element to the beginning of an array, and only supports dimension-1 arrays. Return type: anyarray Example: ``` openGauss=# SELECT array_prepend(1, ARRAY[2,3]) AS RESULT; result --------- {1,2,3} (1 row) ``` * array\_cat(anyarray, anyarray) Description: Concatenates two arrays, and supports multi-dimensional arrays. Return type: anyarray Example: ``` openGauss=# SELECT array_cat(ARRAY[1,2,3], ARRAY[4,5]) AS RESULT; result ------------- {1,2,3,4,5} (1 row) openGauss=# SELECT array_cat(ARRAY[[1,2],[4,5]], ARRAY[6,7]) AS RESULT; result --------------------- {{1,2},{4,5},{6,7}} (1 row) ``` * array\_union(anyarray, anyarray) Description: Concatenates two arrays, and supports only one-dimensional arrays. Return type: anyarray Example: ``` openGauss=# SELECT array_union(ARRAY[1,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {1,2,3,3,4,5} (1 row) ``` * array\_union\_distinct(anyarray, anyarray) Description: Concatenates two arrays and deduplicates them. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_union_distinct(ARRAY[1,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {1,2,3,4,5} (1 row) ``` * array\_intersect(anyarray, anyarray) Description: Intersects two arrays. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_intersect(ARRAY[1,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {3} (1 row) ``` * array\_intersect\_distinct(anyarray, anyarray) Description: Intersects two arrays and deduplicates them. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_intersect_distinct(ARRAY[1,2,2], ARRAY[2,2,4,5]) AS RESULT; result ------------- {2} (1 row) ``` * array\_except(anyarray, anyarray) Description: Calculates the difference between two arrays. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_except(ARRAY[1,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {1,2} (1 row) ``` * array\_except\_distinct(anyarray, anyarray) Description: Calculates the difference between two arrays and deduplicates them. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_except_distinct(ARRAY[1,2,2,3], ARRAY[3,4,5]) AS RESULT; result ------------- {1,2} (1 row) ``` * array\_ndims(anyarray) Description: Returns the number of dimensions of an array. Return type: int Example: ``` openGauss=# SELECT array_ndims(ARRAY[[1,2,3], [4,5,6]]) AS RESULT; result -------- 2 (1 row) ``` * array\_dims(anyarray) Description: Returns the low-order flag bits and high-order flag bits of each dimension in an array. Return type: text Example: ``` openGauss=# SELECT array_dims(ARRAY[[1,2,3], [4,5,6]]) AS RESULT; result ------------ [1:2][1:3] (1 row) ``` * array\_length(anyarray, int) Description: Returns the length of the requested array dimension. **int** is the requested array dimension. Return type: int Example: ``` openGauss=# SELECT array_length(array[1,2,3], 1) AS RESULT; result -------- 3 (1 row) openGauss=# SELECT array_length(array[[1,2,3],[4,5,6]], 2) AS RESULT; result -------- 3 (1 row) ``` * array\_lower(anyarray, int) Description: Returns lower bound of the requested array dimension. **int** is the requested array dimension. Return type: int Example: ``` openGauss=# SELECT array_lower('[0:2]={1,2,3}'::int[], 1) AS RESULT; result -------- 0 (1 row) ``` * array\_upper(anyarray, int) Description: Returns upper bound of the requested array dimension. **int** is the requested array dimension. Return type: int Example: ``` openGauss=# SELECT array_upper(ARRAY[1,8,3,7], 1) AS RESULT; result -------- 4 (1 row) ``` * array\_upper(anyarray, int) Description: Returns upper bound of the requested array dimension. **int** is the requested array dimension. Return type: int Example: ``` openGauss=# SELECT array_upper(ARRAY[1,8,3,7], 1) AS RESULT; result -------- 4 (1 row) ``` * array\_remove(anyarray, anyelement) Description: Removes all specified elements from an array. Only one-dimensional arrays are supported. Return type: anyarray Example: ``` openGauss=# SELECT array_remove(ARRAY[1,8,8,7], 8) AS RESULT; result -------- {1,7} (1 row) ``` * array\_to\_string(anyarray, text \[, text]) Description: Uses the first **text** as the new delimiter and the second **text** to replace **NULL** values. Return type: text Example: ``` openGauss=# SELECT array_to_string(ARRAY[1, 2, 3, NULL, 5], ',', '*') AS RESULT; result ----------- 1,2,3,*,5 (1 row) ``` * array\_delete(anyarray) Description: Clears elements in an array and returns an empty array of the same type. Return type: anyarray Example: ``` openGauss=# SELECT array_delete(ARRAY[1,8,3,7]) AS RESULT; result -------- {} (1 row) ``` * array\_deleteidx(anyarray, int) Description: Deletes specified subscript elements from an array and returns an array consisting of the remaining elements. Return type: anyarray Example: ``` openGauss=# SELECT array_deleteidx(ARRAY[1,2,3,4,5], 1) AS RESULT; result ----------- {2,3,4,5} (1 row) ``` * array\_extendnull(anyarray, int) Description: This API has been discarded and is unavailable currently. * array\_trim(anyarray, int) Description: Deletes a specified number of elements from the end of an array. Return type: anyarray Example: ``` openGauss=# SELECT array_trim(ARRAY[1,8,3,7],1) AS RESULT; result --------- {1,8,3} (1 row) ``` * array\_exists(anyarray, int) Description: Checks whether the second parameter is a valid subscript of an array. Return type: Boolean Example: ``` openGauss=# SELECT array_exists(ARRAY[1,8,3,7],1) AS RESULT; result -------- t (1 row) ``` * array\_next(anyarray, int) Description: Returns the subscript of the element following a specified subscript in an array based on the second input parameter. Return type: int Example: ``` openGauss=# SELECT array_next(ARRAY[1,8,3,7],1) AS RESULT; result -------- 2 (1 row) ``` * array\_prior(anyarray, int) Description: Returns the subscript of the element followed by a specified subscript in an array based on the second input parameter. Return type: int Example: ``` openGauss=# SELECT array_prior(ARRAY[1,8,3,7],2) AS RESULT; result -------- 1 (1 row) ``` * string\_to\_array(text, text \[, text]) Description: Uses the second **text** as the new delimiter and the third **text** as the substring to be replaced by **NULL** values. A substring can be replaced by **NULL** values only when it is the same as the third **text**. Return type: text\[] Example: ``` openGauss=# SELECT string_to_array('xx~^~yy~^~zz', '~^~', 'yy') AS RESULT; result -------------- {xx,NULL,zz} (1 row) openGauss=# SELECT string_to_array('xx~^~yy~^~zz', '~^~', 'y') AS RESULT; result ------------ {xx,yy,zz} (1 row) ``` * unnest(anyarray) Description: Expands an array to a set of rows. Return type: setof anyelement Example: ``` openGauss=# SELECT unnest(ARRAY[1,2]) AS RESULT; result -------- 1 2 (2 rows) ``` In **string\_to\_array**, if the delimiter parameter is NULL, each character in the input string will become a separate element in the resulting array. If the delimiter is an empty string, then the entire input string is returned as a one-element array. Otherwise the input string is split at each occurrence of the delimiter string. In **string\_to\_array**, if the null-string parameter is omitted or NULL, none of the substrings of the input will be replaced by NULL. In **array\_to\_string**, if the null-string parameter is omitted or NULL, any null elements in the array are simply skipped and not represented in the output string. --- --- url: /zh/docs/latest/ograc/sql_reference/array_types.md --- # Array Types 数组元素可以是本章节中介绍的基础数据类型。声明语法如下。 ## 数组常量表达式 声明语法如下: ``` ARRAY [ param ] ``` 或 ``` '{ param }' ``` 其中: * param:数组包含的值,允许出现零个或多个,多个值之间用逗号分隔,成员没有值可写成NULL。 * 以第一个元素的数据类型作为数组的数据类型,因此要求所有元素的类型相同,或者能够相互转换。 > **说明:** > > * 不支持BINARY、VARBINARY、CLOB、BLOB、CURSOR、RAW、IMAGE数据类型的数组。 > * 不支持多维数组。 > * 不支持在数组类型的字段上创建索引、主键、外键和唯一键约束。 ## 字段类型 建表时支持将字段类型设置为数组类型,语法如下: ``` data_type [(n)] ``` 其中: * data\_type:基础数据类型 * n:数组长度 > **说明:** > > * 给定的数组长度n并没有实际作用,数组会自动增长,访问越界会返回一个NULL,不会报错。长度最大可达2^31 - 1。数组字段中的元素值实际存储于LOB段中,最大支持4GB - 1,因此能够存储的元素个数取决于元素的数据类型。 > * 支持使用中括号来访问数组元素,下标从1开始。 示例: ``` SQL> CREATE TABLE array_t1 (a int[2]); SQL> insert into array_t1 values (array[1,2]); 1 rows affected. SQL> select a[3] from array_t1; A ---------------------------------------- 1 rows fetched. SQL> select a[2] from array_t1; A ---------------------------------------- 2 1 rows fetched. -- 批量更新数组元素 SQL> update array_t1 set a[2:4] = '{3,4,5}'; SQL> select a from array_t1; A ---------------------------------------------------------------- {1,3,4,5} 1 rows fetched. SQL> drop table array_t1; ``` --- --- url: /en/docs/latest-lite/sql_reference/arrays.md --- # Arrays ## Use of Array Types Before the use of arrays, an array type needs to be defined. Define an array type immediately after the **AS** keyword in a stored procedure. The definition method is as follows: ``` TYPE array_type IS VARRAY(size) OF data_type; ``` In the preceding information: * **array\_type**: indicates the name of the array type to be defined. * **VARRAY**: indicates the array type to be defined. * **size**: indicates the maximum number of members in the array to be defined. The value is a positive integer. * **data\_type**: indicates the types of members in the array to be created. > \[!NOTE]NOTE > > * In openGauss, an array automatically increases. If an access violation occurs, a null value is returned, and no error message is reported. > * The scope of an array type defined in a stored procedure takes effect only in this stored procedure. > * It is recommended that you use one of the preceding methods to define an array type. If both methods are used to define the same array type, openGauss prefers the array type defined in a stored procedure to declare array variables. > * **data\_type** can also be the record type defined in a stored procedure (anonymous blocks are not supported), array or set type defined in the stored procedure. > * When declaring a nested array, that is, when the **data\_type** of an **array\_type** is defined to be an array, a record or a set, the maxium layers of nested type allowed is 6. Also, it's not allowed to assign an array variable or a table variable to a nested array's element directly openGauss supports access to array elements by using parentheses, and it also supports the **extend**, **count**, **first**, **last**, **prior**, **exists**, **trim**, **next**, and **delete** functions. However, they're not recommended for accessing elements of nested arrays that are refered by subscripts (even if the elements are of array or table type). > \[!NOTE]NOTE > > * If a stored procedure contains a DML statement (such as SELECT, UPDATE, INSERT, and DELETE), you are advised to use square brackets to access array elements. Using parentheses will access arrays by default. If no array exists, function expressions will be identified. > * When the CLOB size is greater than 1 GB, the table of type, record type, and CLOB cannot be used in the input or output parameter, cursor, or raise info in a stored procedure. --- --- url: /en/docs/latest/sql_reference/arrays.md --- # Arrays ## Use of Array Types Before the use of arrays, an array type needs to be defined. Define an array type immediately after the **AS** keyword in a stored procedure. The definition method is as follows: ``` TYPE array_type IS VARRAY(size) OF data_type; ``` In the preceding information: * **array\_type**: indicates the name of the array type to be defined. * **VARRAY**: indicates the array type to be defined. * **size**: indicates the maximum number of members in the array to be defined. The value is a positive integer. * **data\_type**: indicates the types of members in the array to be created. > \[!NOTE]NOTE > > * In openGauss, an array automatically increases. If an access violation occurs, a null value is returned, and no error message is reported. > * The scope of an array type defined in a stored procedure takes effect only in this stored procedure. > * It is recommended that you use one of the preceding methods to define an array type. If both methods are used to define the same array type, openGauss prefers the array type defined in a stored procedure to declare array variables. > * **data\_type** can also be the record type defined in a stored procedure (anonymous blocks are not supported), array or set type defined in the stored procedure. > * When declaring a nested array, that is, when the **data\_type** of an **array\_type** is defined to be an array, a record or a set, the maxium layers of nested type allowed is 6. Also, it's not allowed to assign an array variable or a table variable to a nested array's element directly openGauss supports access to array elements by using parentheses, and it also supports the **extend**, **count**, **first**, **last**, **prior**, **exists**, **trim**, **next**, and **delete** functions. However, they're not recommended for accessing elements of nested arrays that are refered by subscripts (even if the elements are of array or table type). > \[!NOTE]NOTE > > * If a stored procedure contains a DML statement (such as SELECT, UPDATE, INSERT, and DELETE), you are advised to use square brackets to access array elements. Using parentheses will access arrays by default. If no array exists, function expressions will be identified. > * When the CLOB size is greater than 1 GB, the table of type, record type, and CLOB cannot be used in the input or output parameter, cursor, or raise info in a stored procedure. --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_assignment_operators.md --- # Assignment Operators Compared with the original openGauss, Dolphin modifies the assignment operators as follows: Values can be assigned using `:=`. For example, `UPDATE table_name SET col_name := new_val;`. --- --- url: /en/docs/latest-lite/sql_reference/assignment_statements.md --- # Assignment Statements ## Syntax [Figure 1](#en-us_topic_0283137492_en-us_topic_0237122222_en-us_topic_0059778597_f1087f61f4ec24addbb3b79a2ccf21917) shows the syntax diagram for assigning a value to a variable. **Figure 1** assignment\_value::=\ ![](figures/assignment_value.png "assignment_value") The above syntax diagram is explained as follows: * **variable\_name** indicates the name of a variable. * **value** can be a value or an expression. The type of **value** must be compatible with the type of **variable\_name**. Example: ``` openGauss=# DECLARE emp_id INTEGER := 7788; -- Assignment BEGIN emp_id := 5; -- Assignment emp_id := 5*7784; END; / ``` ## Nested Value Assignment [Figure 2](#fig178291445115118) shows the syntax diagram for assigning a nested value to a variable. **Figure 2** nested\_assignment\_value::=\ ![](figures/nested_assignment_value.png "nested_assignment_value") The syntax in [Figure 2](#fig178291445115118) is described as follows: * **variable\_name**: variable name * **col\_name**: column name * **subscript**: subscript, which is used for an array variable. The value can be a value or an expression and must be of the int type. * **value**: value or expression. The type of **value** must be compatible with the type of **variable\_name**. Example: ``` openGauss=#CREATE TYPE o1 as (a int, b int); openGauss=# DECLARE TYPE r1 is VARRAY(10) of o1; emp_id r1; BEGIN emp_id(1).a := 5;-- Assign a value. emp_id(1).b := 5*7784; END; / ``` > \[!TIP]NOTICE > > * In INTO mode, values can be assigned only to the columns at the first layer. Two-dimensional or above arrays are not supported. > * When a nested column value is referenced, if an array subscript exists, only one parenthesis can exist in the first three layers of columns. You are advised to use square brackets to reference the subscript. ## Assignment Of Variables With Type Names In addition to the above, openGauss supports assignment methods with type names (including RECORD, VARRAY, TABLE OF types and types created by CREATE TYPE). For compatibility with historical versions, such type names are usually ignored and treated as normal arrays or records. Only when enable\_pltype\_name\_check switch is turned on will throw an error if the type name is different. ## Examples ``` set enable_pltype_name_check = on; -- Turn on the type name detection switch (default is off) DECLARE TYPE t_rec IS RECORD (val1 VARCHAR2(10), val2 VARCHAR2(10)); TYPE t_rec2 IS RECORD (val1 VARCHAR2(10), val2 VARCHAR2(10)); l_rec t_rec; BEGIN l_rec := t_rec2('ONE', 'TWO'); -- Assignment of variables with type names raise info 'l_rec is %', NVL(l_rec.val1,'NULL'); END; / ERROR: "t_rec2" cannot be used to assign "l_rec" ``` ## INTO/BULK COLLECT INTO **INTO** and **BULK COLLECT INTO** store values returned by statements in a stored procedure to variables. **BULK COLLECT INTO** allows some or all returned values to be temporarily stored in an array. Example: ``` openGauss=# DECLARE my_id integer; BEGIN select id into my_id from customers limit 1; -- Assign a value. END; / openGauss=# DECLARE type id_list is varray(6) of customers.id%type; id_arr id_list; BEGIN select id bulk collect into id_arr from customers order by id DESC limit 20; -- Assign values in batches. END; / ``` > \[!TIP]NOTICE > **BULK COLLECT INTO** can only assign values to arrays in batches. Use **LIMIT** properly to prevent performance deterioration caused by excessive operations on data. --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_assignment_statements.md --- # Assignment Statements ## Notice Compared with the original openGauss, Dolphin modifies the assignment syntax as follows: 1. The syntax function of assigning values to variables through **set** is added between BEGIN and END. ## Syntax [Figure 1](#en-us_topic_0283137492_en-us_topic_0237122222_en-us_topic_0059778597_f1087f61f4ec24addbb3b79a2ccf21917) shows the syntax diagram for assigning a value to a variable. **Figure 1** assignment\_value::=\ ![](figures/assignment_value.png "assignment_value") The following is supported in B-compatible mode: ``` set variable_name := value; ``` The syntax is described as follows: * **variable\_name** indicates the name of a variable. * **value** can be a value or an expression. The type of **value** must be compatible with the type of **variable\_name**. Example: ``` openGauss=# DECLARE emp_id INTEGER := 7788; -- Assignment BEGIN emp_id := 5; -- Assignment emp_id := 5*7784; END; / In B-compatible mode: openGauss=# DECLARE emp_id INTEGER := 7788; -- Assignment BEGIN set emp_id := 5;-- Assignment set emp_id := 5*7784; END; / ``` > \[!TIP]NOTICE > > * You can run the **set variable\_name :=(=) value** command to assign a value to a variable between BEGIN and END. --- --- url: /en/docs/latest/sql_reference/assignment_statements.md --- # Assignment Statements ## Syntax [Figure 1](#en-us_topic_0283137492_en-us_topic_0237122222_en-us_topic_0059778597_f1087f61f4ec24addbb3b79a2ccf21917) shows the syntax diagram for assigning a value to a variable. **Figure 1** assignment\_value::=\ ![](figures/assignment_value.png "assignment_value") The above syntax diagram is explained as follows: * **variable\_name** indicates the name of a variable. * **value** can be a value or an expression. The type of **value** must be compatible with the type of **variable\_name**. ## Examples ``` openGauss=# DECLARE emp_id INTEGER := 7788; -- Assignment BEGIN emp_id := 5; -- Assignment emp_id := 5*7784; END; / ``` ## Nested Value Assignment [Figure 2](#fig178291445115118) shows the syntax diagram for assigning a nested value to a variable. **Figure 2** nested\_assignment\_value::=\ ![](figures/nested_assignment_value.png "nested_assignment_value") The syntax in [Figure 2](#fig178291445115118) is described as follows: * **variable\_name**: variable name * **col\_name**: column name * **subscript**: subscript, which is used for an array variable. The value can be a value or an expression and must be of the int type. * **value**: value or expression. The type of **value** must be compatible with the type of **variable\_name**. ## Examples ``` openGauss=#CREATE TYPE o1 as (a int, b int); openGauss=# DECLARE TYPE r1 is VARRAY(10) of o1; emp_id r1; BEGIN emp_id(1).a := 5;-- Assign a value. emp_id(1).b := 5*7784; END; / ``` > \[!TIP]NOTICE > > * In INTO mode, values can be assigned only to the columns at the first layer. Two-dimensional or above arrays are not supported. > * When a nested column value is referenced, if an array subscript exists, only one parenthesis can exist in the first three layers of columns. You are advised to use square brackets to reference the subscript. ## Assignment Of Variables With Type Names In addition to the above, openGauss supports assignment methods with type names (including RECORD, VARRAY, TABLE OF types and types created by CREATE TYPE). For compatibility with historical versions, such type names are usually ignored and treated as normal arrays or records. Only when enable\_pltype\_name\_check switch is turned on will throw an error if the type name is different. ## Examples ``` set enable_pltype_name_check = on; -- Turn on the type name detection switch (default is off) DECLARE TYPE t_rec IS RECORD (val1 VARCHAR2(10), val2 VARCHAR2(10)); TYPE t_rec2 IS RECORD (val1 VARCHAR2(10), val2 VARCHAR2(10)); l_rec t_rec; BEGIN l_rec := t_rec2('ONE', 'TWO'); -- Assignment of variables with type names raise info 'l_rec is %', NVL(l_rec.val1,'NULL'); END; / ERROR: "t_rec2" cannot be used to assign "l_rec" ``` ## INTO/BULK COLLECT INTO **INTO** and **BULK COLLECT INTO** store values returned by statements in a stored procedure to variables. **BULK COLLECT INTO** allows some or all returned values to be temporarily stored in an array. ## Examples ``` openGauss=# DECLARE my_id integer; BEGIN select id into my_id from customers limit 1; -- Assign a value. END; / openGauss=# DECLARE type id_list is varray(6) of customers.id%type; id_arr id_list; BEGIN select id bulk collect into id_arr from customers order by id DESC limit 20; -- Assign values in batches. END; / ``` > \[!TIP]NOTICE > **BULK COLLECT INTO** can only assign values to arrays in batches. Use **LIMIT** properly to prevent performance deterioration caused by excessive operations on data. --- --- url: /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-ast.md --- # AST ## Function Verifies the openGauss syntax tree. Checks whether the statements following the AST syntax support the generation of the openGauss syntax tree. ## Precautions If the verification fails, a syntax parsing error is thrown. If the verification is successful, no command output is displayed. ## Syntax ``` AST [ STMT ] ; ``` ## Parameter Description * **STMT** Any type of SQL statements and stored procedure statements are supported. ## Examples ``` -- Verify table creation statements. openGauss=# AST CREATE TABLE TEST(ID INT6); -- Statement verification is not supported. openGauss=# AST CREATE TABLE TEST; ERRPR: syntax error at or near ";" LINE 1:AST CREATE TABLE TEST; ^ ``` --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-AST.md --- # AST ## 功能描述 openGauss语法树校验。 对AST语法后的语句是否支持生成openGauss语法树作判断。 ## 注意事项 校验不通过时,会抛出语法解析相应错误。校验通过时不作任何回显操作。 ## 语法格式 ``` AST [ STMT ] ; ``` ## 参数说明 * **STMT** 支持任意类型SQL语句、存储过程语句等。 ## 示例 ``` -- 建表语句校验 openGauss=# AST CREATE TABLE TEST(ID INT6); -- 不支持语句校验 openGauss=# AST CREATE TABLE TEST; ERRPR: syntax error at or near ";" LINE 1:AST CREATE TABLE TEST; ^ ``` --- --- url: /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-AST.md --- # AST ## 功能描述 openGauss语法树校验。 对AST语法后的语句是否支持生成openGauss语法树作判断。 ## 注意事项 校验不通过时,会抛出语法解析相应错误。校验通过时不作任何回显操作。 ## 语法格式 ``` AST [ STMT ] ; ``` ## 参数说明 * **STMT** 支持任意类型SQL语句、存储过程语句等。 ## 示例 ``` -- 建表语句校验 openGauss=# AST CREATE TABLE TEST(ID INT6); -- 不支持语句校验 openGauss=# AST CREATE TABLE TEST; ERRPR: syntax error at or near ";" LINE 1:AST CREATE TABLE TEST; ^ ``` --- --- url: /en/docs/latest-lite/database_reference/asynchronous_i_o_operations.md --- # Asynchronous I/O Operations ## enable\_adio\_debug **Parameter description**: Specifies whether O\&M personnel are allowed to generate some ADIO logs to locate ADIO issues. This parameter is used only by developers. Common users are advised not to use it. This parameter is a SUSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** or **true** indicates that generation of ADIO logs is allowed. * **off** or **false** indicates that generation of ADIO logs is disallowed. **Default value**: **off** > \[!NOTE]NOTE > This parameter cannot be enabled on in the current version. Even if it is manually enabled, the system automatically disables it. ## enable\_adio\_function **Parameter description**: Specifies whether to enable the ADIO function. > \[!NOTE]NOTE > The current version does not support the asynchronous I/O function. This function is disabled by default. Do not modify the setting. **Value range**: Boolean * **on** or **true** indicates that the function is enabled. * **off** or **false** indicates that the function is disabled. **Default value**: **off** ## enable\_fast\_allocate **Parameter description**: Specifies whether the quick disk space allocation is enabled. This parameter is a SUSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). This function can be enabled only in the XFS file system. **Value range**: Boolean * **on** or **true** indicates that the function is enabled. * **off** or **false** indicates that the function is disabled. **Default value**: **off** ## prefetch\_quantity **Parameter description**: Specifies the amount of the I/O that the row-store prefetches using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 128 to 131072. The unit is 8 KB. **Default value**: **32 MB** (4096 x 8 KB) ## backwrite\_quantity **Parameter description**: Specifies the amount of I/O that the row-store writes using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 128 to 131072. The unit is 8 KB. **Default value**: **8 MB** (1024 x 8 KB) ## cstore\_prefetch\_quantity **Parameter description**: Specifies the amount of I/O that the column-store prefetches using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 1048576. The unit is KB. **Default value**: **32 MB** ## cstore\_backwrite\_quantity **Parameter description**: Specifies the amount of I/O that the column-store writes using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 1048576. The unit is KB. **Default value**: **8 MB** ## cstore\_backwrite\_max\_threshold **Parameter description**: Specifies the maximum amount of buffer I/O that the column-store writes in the database using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 4096 to *INT\_MAX*/2. The unit is KB. **Default value**: **2 GB** ## fast\_extend\_file\_size **Parameter description**: Specifies the disk size that the row-store pre-scales using the ADIO. This parameter is a SUSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 1048576. The unit is KB. **Default value**: **8 MB** ## effective\_io\_concurrency **Parameter description**: Specifies the number of requests that can be simultaneously processed by a disk subsystem. For the RAID array, the parameter value must be the number of disk drive spindles in the array. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 1000 **Default value**: **1** ## checkpoint\_flush\_after **Parameter description:** Specifies the threshold for the number of pages flushed by the checkpointer thread. If the threshold is exceeded, the operating system is instructed to flush the pages cached in the operating system asynchronously. In openGauss, the disk page size is 8 KB. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 256. **0** indicates that the asynchronous flush function is disabled. For example, if the value is **32**, the checkpointer thread continuously writes 32 disk pages (that is, 32 x 8 = 256 KB) before asynchronous flush. **Default value**: **256 KB** ## bgwriter\_flush\_after **Parameter description:** Specifies the threshold for the number of pages flushed by the background writer thread. If the threshold is exceeded, the background writer thread instructs the operating system to asynchronously flush the pages cached in the operating system to disks. In openGauss, the disk page size is 8 KB. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 256. **0** indicates that the asynchronous flush function is disabled. The size of a single page is 8 KB. For example, if the value is **64**, the background writer thread continuously writes 64 disk pages (that is, 64 x 8 = 512 KB) before asynchronous flush. **Default value**: **512 KB** (64 pages) ## backend\_flush\_after **Parameter description:** Specifies the threshold for the number of pages flushed by the background writer thread. If the number of pages exceeds the threshold, the background writer thread instructs the operating system to asynchronously flush the pages cached in the operating system to disks. In openGauss, the disk page size is 8 KB. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 256. **0** indicates that the asynchronous flush function is disabled. The size of a single page is 8 KB. For example, if the value is **64**, the backend thread continuously writes 64 disk pages (that is, 64 x 8 = 512 KB) before asynchronous flush. **Default value**: **0** --- --- url: /en/docs/latest/database_reference/asynchronous_i_o_operations.md --- # Asynchronous I/O Operations ## enable\_adio\_debug **Parameter description**: Specifies whether O\&M personnel are allowed to generate some ADIO logs to locate ADIO issues. This parameter is used only by developers. Common users are advised not to use it. This parameter is a SUSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** or **true** indicates that generation of ADIO logs is allowed. * **off** or **false** indicates that generation of ADIO logs is disallowed. **Default value**: **off** > \[!NOTE]NOTE > This parameter cannot be enabled on in the current version. Even if it is manually enabled, the system automatically disables it. ## enable\_adio\_function **Parameter description**: Specifies whether to enable the ADIO function. > \[!NOTE]NOTE > The current version does not support the asynchronous I/O function. This function is disabled by default. Do not modify the setting. **Value range**: Boolean * **on** or **true** indicates that the function is enabled. * **off** or **false** indicates that the function is disabled. **Default value**: **off** ## enable\_fast\_allocate **Parameter description**: Specifies whether the quick disk space allocation is enabled. This parameter is a SUSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). This function can be enabled only in the XFS file system. **Value range**: Boolean * **on** or **true** indicates that the function is enabled. * **off** or **false** indicates that the function is disabled. **Default value**: **off** ## prefetch\_quantity **Parameter description**: Specifies the amount of the I/O that the row-store prefetches using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 128 to 131072. The unit is 8 KB. **Default value**: **32 MB** (4096 x 8 KB) ## backwrite\_quantity **Parameter description**: Specifies the amount of I/O that the row-store writes using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 128 to 131072. The unit is 8 KB. **Default value**: **8 MB** (1024 x 8 KB) ## cstore\_prefetch\_quantity **Parameter description**: Specifies the amount of I/O that the column-store prefetches using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 1048576. The unit is KB. **Default value**: **32 MB** ## cstore\_backwrite\_quantity **Parameter description**: Specifies the amount of I/O that the column-store writes using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 1048576. The unit is KB. **Default value**: **8 MB** ## cstore\_backwrite\_max\_threshold **Parameter description**: Specifies the maximum amount of buffer I/O that the column-store writes in the database using the ADIO. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 4096 to *INT\_MAX*/2. The unit is KB. **Default value**: **2 GB** ## fast\_extend\_file\_size **Parameter description**: Specifies the disk size that the row-store pre-scales using the ADIO. This parameter is a SUSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 1048576. The unit is KB. **Default value**: **8 MB** ## effective\_io\_concurrency **Parameter description**: Specifies the number of requests that can be simultaneously processed by a disk subsystem. For the RAID array, the parameter value must be the number of disk drive spindles in the array. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 1000 **Default value**: **1** ## checkpoint\_flush\_after **Parameter description:** Specifies the threshold for the number of pages flushed by the checkpointer thread. If the threshold is exceeded, the operating system is instructed to flush the pages cached in the operating system asynchronously. In openGauss, the disk page size is 8 KB. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 256. **0** indicates that the asynchronous flush function is disabled. For example, if the value is **32**, the checkpointer thread continuously writes 32 disk pages (that is, 32 x 8 = 256 KB) before asynchronous flush. **Default value**: **256 KB** ## bgwriter\_flush\_after **Parameter description:** Specifies the threshold for the number of pages flushed by the background writer thread. If the threshold is exceeded, the background writer thread instructs the operating system to asynchronously flush the pages cached in the operating system to disks. In openGauss, the disk page size is 8 KB. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 256. **0** indicates that the asynchronous flush function is disabled. The size of a single page is 8 KB. For example, if the value is **64**, the background writer thread continuously writes 64 disk pages (that is, 64 x 8 = 512 KB) before asynchronous flush. **Default value**: **512 KB** (64 pages) ## backend\_flush\_after **Parameter description:** Specifies the threshold for the number of pages flushed by the background writer thread. If the number of pages exceeds the threshold, the background writer thread instructs the operating system to asynchronously flush the pages cached in the operating system to disks. In openGauss, the disk page size is 8 KB. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 256. **0** indicates that the asynchronous flush function is disabled. The size of a single page is 8 KB. For example, if the value is **64**, the backend thread continuously writes 64 disk pages (that is, 64 x 8 = 512 KB) before asynchronous flush. **Default value**: **0** --- --- url: /en/docs/latest-lite/database_reference/audit_switch.md --- # Audit Switch ## audit\_enabled **Parameter description**: Specifies whether to enable or disable the audit process. After the audit process is enabled, the auditing information written by the background process can be read from the pipe and written into audit files. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that the auditing function is enabled. * **off** indicates that the auditing function is disabled. **Default value**: **on** ## audit\_directory **Parameter description**: Specifies the storage directory of audit files. A path relative to the **data** directory. Only the sysadmin user can access this parameter. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string **Default value:** **pg\_audit**. If **om** is used for openGauss deployment, audit logs are stored in **$GAUSSLOG/pg\_audit/*Instance name***. > \[!TIP]NOTICE > > * You need to set different audit file directories for different DNs. Otherwise, audit logs will be abnormal. > > * If the value of **audit\_directory** in the configuration file is an invalid path, the audit function cannot be used. > > * Path description: > * Valid path: You have read and write permissions on the path. > * Invalid path: You do not have read or write permissions on an invalid path. ## audit\_data\_format **Parameter description**: Audits the format of log files. Currently, only the binary format is supported. Only the sysadmin user can access this parameter. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string **Default value**: **binary** ## audit\_rotation\_interval **Parameter description**: Specifies the interval of creating an audit log file. If the difference between the current time and the time when the previous audit log file is created is greater than the value of **audit\_rotation\_interval**, a new audit log file will be generated. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to \*INT\*MAX\_/60. The unit is min. **Default value:** **1d** > \[!TIP]NOTICE > Adjust this parameter only when required. Otherwise, **audit\_resource\_policy** may fail to take effect. To control the storage space and time of audit logs, set the [audit\_resource\_policy](#en-us_topic_0283137524_en-us_topic_0237124745_section939915522551), [audit\_space\_limit](#en-us_topic_0283137524_en-us_topic_0237124745_en-us_topic_0059777744_s167d5900250946bca199444c0617c714), and [audit\_file\_remain\_time](#en-us_topic_0283137524_en-us_topic_0237124745_section149961828185211) parameters. ## audit\_rotation\_size **Parameter description**: Specifies the maximum capacity of an audit log file. If the total number of messages in an audit log exceeds the value of **audit\_rotation\_size**, the server will generate a new audit log file. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 1048576. The unit is kB. **Default value**: **10 MB** > \[!TIP]NOTICE > Adjust this parameter only when required. Otherwise, **audit\_resource\_policy** may fail to take effect. To control the storage space and time of audit logs, set the **audit\_resource\_policy**, **audit\_space\_limit**, and **audit\_file\_remain\_time** parameters. ## audit\_resource\_policy **Parameter description**: Specifies the policy for determining whether audit logs are preferentially stored by space or time. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that audit logs are preferentially stored by space. A maximum of [audit\_space\_limit](#en-us_topic_0283137524_en-us_topic_0237124745_en-us_topic_0059777744_s167d5900250946bca199444c0617c714) logs can be stored. * **off** indicates that audit logs are preferentially stored by time. A minimum duration of [audit\_file\_remain\_time](#en-us_topic_0283137524_en-us_topic_0237124745_section149961828185211) logs must be stored. **Default value**: **on** ## audit\_file\_remain\_time **Parameter description**: Specifies the minimum duration required for recording audit logs. This parameter is valid only when [audit\_resource\_policy](#en-us_topic_0283137524_en-us_topic_0237124745_section939915522551) is set to **off**. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 730. The unit is day. **0** indicates that the storage duration is not limited. **Default value**: **90** ## audit\_space\_limit **Parameter description**: Specifies the total disk space occupied by audit files. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 kB to 1024 GB. The unit is kB. **Default value**: **1GB** ## audit\_file\_remain\_threshold **Parameter description**: Specifies the maximum number of audit files in the audit directory. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 100 to 1048576 **Default value:** **1024** > \[!TIP]NOTICE > Ensure that this parameter is set to **1048576**. Adjust this parameter only when required. Otherwise, **audit\_resource\_policy** may fail to take effect. To control the storage space and time of audit logs, set the **audit\_resource\_policy**, **audit\_space\_limit**, and **audit\_file\_remain\_time** parameters. ## audit\_thread\_num **Parameter description**: Specifies the number of audit threads. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 1 to 48 **Default value**: **1** > \[!TIP]NOTICE > When **audit\_dml\_state** is enabled and high performance is required, you are advised to increase the value of this parameter to ensure that audit messages can be processed and recorded in a timely manner. --- --- url: /en/docs/latest/database_reference/audit_switch.md --- # Audit Switch ## audit\_enabled **Parameter description**: Specifies whether to enable or disable the audit process. After the audit process is enabled, the auditing information written by the background process can be read from the pipe and written into audit files. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that the auditing function is enabled. * **off** indicates that the auditing function is disabled. **Default value**: **on** ## audit\_directory **Parameter description**: Specifies the storage directory of audit files. A path relative to the **data** directory. Only the sysadmin user can access this parameter. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string **Default value:** **pg\_audit** If **om** is used for openGauss deployment, audit logs are stored in \**$GAUSSLOG/pg\_audit/*Instance name**. > \[!TIP]NOTICE > > * You need to set different audit file directories for different DNs. Otherwise, audit logs will be abnormal. > * If the value of **audit\_directory** in the configuration file is an invalid path, the audit function cannot be used. > * Path description: > * Valid path: You have read and write permissions on the path. > * Invalid path: You do not have read or write permissions on an invalid path. ## audit\_data\_format **Parameter description**: Audits the format of log files. Currently, only the binary format is supported. Only the sysadmin user can access this parameter. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string **Default value**: **binary** ## audit\_rotation\_interval **Parameter description**: Specifies the interval of creating an audit log file. If the difference between the current time and the time when the previous audit log file is created is greater than the value of **audit\_rotation\_interval**, a new audit log file will be generated. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to \*INT\*MAX\_/60. The unit is min. **Default value:** **1d** > \[!TIP]NOTICE > Adjust this parameter only when required. Otherwise, **audit\_resource\_policy** may fail to take effect. To control the storage space and time of audit logs, set the [audit\_resource\_policy](#en-us_topic_0283137524_en-us_topic_0237124745_section939915522551), [audit\_space\_limit](#en-us_topic_0283137524_en-us_topic_0237124745_en-us_topic_0059777744_s167d5900250946bca199444c0617c714), and [audit\_file\_remain\_time](#en-us_topic_0283137524_en-us_topic_0237124745_section149961828185211) parameters. ## audit\_rotation\_size **Parameter description**: Specifies the maximum capacity of an audit log file. If the total number of messages in an audit log exceeds the value of **audit\_rotation\_size**, the server will generate a new audit log file. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 1048576. The unit is kB. **Default value**: **10 MB** > \[!TIP]NOTICE > Adjust this parameter only when required. Otherwise, **audit\_resource\_policy** may fail to take effect. To control the storage space and time of audit logs, set the **audit\_resource\_policy**, **audit\_space\_limit**, and **audit\_file\_remain\_time** parameters. ## audit\_resource\_policy **Parameter description**: Specifies the policy for determining whether audit logs are preferentially stored by space or time. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that audit logs are preferentially stored by space. A maximum of [audit\_space\_limit](#en-us_topic_0283137524_en-us_topic_0237124745_en-us_topic_0059777744_s167d5900250946bca199444c0617c714) logs can be stored. * **off** indicates that audit logs are preferentially stored by time. A minimum duration of [audit\_file\_remain\_time](#en-us_topic_0283137524_en-us_topic_0237124745_section149961828185211) logs must be stored. **Default value**: **on** ## audit\_file\_remain\_time **Parameter description**: Specifies the minimum duration required for recording audit logs. This parameter is valid only when [audit\_resource\_policy](#en-us_topic_0283137524_en-us_topic_0237124745_section939915522551) is set to **off**. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 730. The unit is day. **0** indicates that the storage duration is not limited. **Default value**: **90** ## audit\_space\_limit **Parameter description**: Specifies the total disk space occupied by audit files. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 kB to 1024 GB. The unit is kB. **Default value**: **1GB** ## audit\_file\_remain\_threshold **Parameter description**: Specifies the maximum number of audit files in the audit directory. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 100 to 1048576 **Default value**: **1048576** > \[!TIP]NOTICE > Ensure that this parameter is set to **1048576**. Adjust this parameter only when required. Otherwise, **audit\_resource\_policy** may fail to take effect. To control the storage space and time of audit logs, set the **audit\_resource\_policy**, **audit\_space\_limit**, and **audit\_file\_remain\_time** parameters. ## audit\_thread\_num **Parameter description**: Specifies the number of audit threads. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 1 to 48 **Default value**: **1** > \[!TIP]NOTICE > When **audit\_dml\_state** is enabled and high performance is required, you are advised to increase the value of this parameter to ensure that audit messages can be processed and recorded in a timely manner. --- --- url: >- /en/docs/latest-lite/characteristic_description/automatic_job_retry_upon_failure.md --- # Automatic Job Retry upon Failure ## Availability This feature is available since openGauss 1.0.0. ## Introduction If an error occurs in batch processing jobs due to network exceptions or deadlocks, failed jobs are automatically retried. ## Benefits In common fault scenarios, such as network exception and deadlock, queries retry automatically in case of failure to improve database usability. ## Description openGauss provides the job retry mechanism: gsql retry. * The gsql retry mechanism uses a unique error code (SQL STATE) to identify an error that requires a retry. The function of the client tool gsql is enhanced. The error code configuration file **retry\_errcodes.conf** is used to configure the list of errors that require a retry. The file is stored in the installation directory at the same level as gsql. **gsql** provides the **\set RETRY**\[*number*] command to enable or disable the retry function. The number of retry times ranges from 5 to 10, and the default value is **5**. When this function is enabled, **gsql** reads the preceding configuration file. The error retry controller records the error code list through the container. If an error occurs in the configuration file after the function is enabled, the controller sends the cached query statement to the server for retry until the query is successful or an error is reported when the number of retry times exceeds the maximum. ## Enhancements None. ## Constraints * Functionality constraints: Retrying increases execution success rate but does not guarantee success. * Error type constraints: Only the error types in [Table 1](#table123551925257) are supported. **Table 1** Supported error types * Statement type constraints: Support single-statement stored procedures, functions, and anonymous blocks. Statements in transaction blocks are not supported. * Statement constraints of a stored procedure: * If an error occurs during the execution of a stored procedure containing EXCEPTION (including statement block execution and statement execution in EXCEPTION), the stored procedure can be retried. If the error is captured by EXCEPTION, the stored procedure cannot be retried. * Advanced packages that use global variables are not supported. * DBE\_TASK is not supported. * PKG\_UTIL file operation is not supported. * Data import constraints: * The **COPY FROM STDIN** statement is not supported. * The **gsql \copy from** metacommand is not supported. * Data cannot be imported using **JDBC CopyManager copyIn**. ## Dependencies Valid only if the **gsql** tool works normally and the error list is correctly configured. --- --- url: /en/docs/latest/characteristic_description/automatic_job_retry_upon_failure.md --- # Automatic Job Retry upon Failure ## Availability This feature is available since openGauss 1.0.0. ## Introduction If an error occurs in batch processing jobs due to network exceptions or deadlocks, failed jobs are automatically retried. ## Benefits In common fault scenarios, such as network exception and deadlock, queries retry automatically in case of failure to improve database usability. ## Description openGauss provides the job retry mechanism: gsql Retry. * The gsql retry mechanism uses a unique error code (SQL STATE) to identify an error that requires a retry. The function of the client tool gsql is enhanced. The error code configuration file **retry\_errcodes.conf** is used to configure the list of errors that require a retry. The file is stored in the installation directory at the same level as gsql. **gsql** provides the **\set RETRY**\[*number*] command to enable or disable the retry function. The number of retry times ranges from 5 to 10, and the default value is **5**. When this function is enabled, **gsql** reads the preceding configuration file. The error retry controller records the error code list through the container. If an error occurs in the configuration file after the function is enabled, the controller sends the cached query statement to the server for retry until the query is successful or an error is reported when the number of retry times exceeds the maximum. ## Enhancements None ## Constraints * Functionality constraints: * Retrying increases execution success rate but does not guarantee success. * Error type constraints: Only the error types in [Table 1](#table123551925257) are supported. **Table 1** Supported error types * Statement type constraints: Support single-statement stored procedures, functions, and anonymous blocks. Statements in transaction blocks are not supported. * Statement constraints of a stored procedure: * If an error occurs during the execution of a stored procedure containing EXCEPTION (including statement block execution and statement execution in EXCEPTION), the stored procedure can be retried. If the error is captured by EXCEPTION, the stored procedure cannot be retried. * Advanced packages that use global variables are not supported. * DBE\_TASK is not supported. * PKG\_UTIL file operation is not supported. * Data import constraints: * The **COPY FROM STDIN** statement is not supported. * The **gsql \copy from** metacommand is not supported. * Data cannot be imported using **JDBC CopyManager copyIn**. ## Dependencies Valid only if the **gsql** tool works normally and the error list is correctly configured. --- --- url: /en/docs/latest-lite/database_reference/automatic_vacuuming.md --- # Automatic Vacuuming The **autovacuum** process automatically runs the **VACUUM** and **ANALYZE** statements to recycle the record space marked as deleted and update statistics about the table. ## autovacuum **Parameter description**: Specifies whether to start the **autovacuum** process in the database. Ensure that the [track\_counts](query_and_index_statistics_collector.md#en-us_topic_0283136895_en-us_topic_0237124727_en-us_topic_0059779313_s3f4fb0b1004041f69e1454c701952411) parameter is set to **on** before starting the automatic cleanup process. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). > \[!NOTE]NOTE > > * Set the **autovacuum** parameter to **on** if you want to start the automatic cleanup of abnormal two-phase transactions when the system recovers from faults. > * If **autovacuum** is set to **on** and **[autovacuum\_max\_workers](#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s76932f79410248ba8923017d19982673)** to **0**, the autovacuum process is started only when the system recovers from faults to clean up abnormal two-phase transactions. > * If **autovacuum** is set to **on** and the value of [autovacuum\_max\_workers](#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s76932f79410248ba8923017d19982673) is greater than **0**, the system will automatically clean up the two-phase transactions and processes after recovering from faults. > \[!TIP]NOTICE > Even if **autovacuum** is set to **off**, the autovacuum process will be started automatically when a transaction ID wraparound is about to occur. When a **CREATE DATABASE** or **DROP DATABASE** operation fails, it is possible that the transaction has been committed or rolled back on some nodes whereas some nodes are still in the prepared state. In this case, perform the following operations to manually restore the nodes: **Value range**: Boolean * **on** indicates that the **autovacuum** process is started. * **off** indicates that the **autovacuum** process is not started. **Default value**: **on** ## autovacuum\_mode **Parameter description**: Specifies whether the autoanalyze or autovacuum function is started. This parameter is valid only when **autovacuum** is set to **on**. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: enumerated values * **analyze** indicates that only autoanalyze is performed. * **vacuum** indicates that only autovacuum is performed. * **mix** indicates that both autoanalyze and autovacuum are performed. * **none** indicates that neither of them is performed. **Default value**: **mix** ## autoanalyze\_timeout **Parameter description**: Specifies the timeout period of autoanalyze. If the duration of autoanalyze on a table exceeds the value of **autoanalyze\_timeout**, the autoanalyze is automatically canceled. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to 2147483. The unit is s. **Default value**: **5min** (300s) ## autovacuum\_io\_limits **Parameter description**: Specifies the upper limit of I/Os triggered by the autovacuum process per second. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer. The value can be **–1** or a number ranging from 0 to 1073741823. **–1** indicates that the default cgroup is used. **Default value**: **–1** ## log\_autovacuum\_min\_duration **Parameter description**: Records each step performed by the autovacuum process to the server log when the execution time of the autovacuum process is greater than or equal to a certain value. This parameter helps track the autovacuum behavior. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). A setting example is as follows: Set the **log\_autovacuum\_min\_duration** parameter to 250 ms to record the actions of autovacuum if it runs for 250 ms or longer. **Value range**: an integer ranging from –1 to 2147483647. The unit is ms. * **0** indicates that all autovacuum actions are recorded in the log. * **–1** indicates that all autovacuum actions are not recorded in the log. * A value other than **–1** indicates that a message is recorded when an autovacuum action is skipped due to a lock conflict. **Default value**: **–1** ## autovacuum\_max\_workers **Parameter description**: Specifies the maximum number of autovacuum worker threads that can run at the same time. The upper limit of this parameter is related to the values of **max\_connections** and **job\_queue\_processes**. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer. The minimum value is **0**, indicating that autovacuum is not enabled. The theoretical maximum value is **262143**, but the actual maximum value is a dynamic value calculated by the following formula: 262143 - **max\_connections** - **job\_queue\_processes** - Number of auxiliary threads - Number of autovacuum launcher threads - 1. The number of auxiliary threads and the number of autovacuum launcher threads are specified by two macros. Their default values are **20** and **2** respectively. **Default value**: **3** ## autovacuum\_naptime **Parameter description**: Specifies the interval between activity rounds for the autovacuum process. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 1 to 2147483. The unit is s. **Default value**: **10min** (600s) ## autovacuum\_vacuum\_threshold **Parameter description**: Specifies the threshold for triggering the **VACUUM** operation. When the number of deleted or updated records in a table exceeds the specified threshold, the **VACUUM** operation is executed on this table. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to 2147483647. **Default value**: **50** ## autovacuum\_analyze\_threshold **Parameter description**: Specifies the threshold for triggering the **ANALYZE** operation. When the number of deleted, inserted, or updated records in a table exceeds the specified threshold, the **ANALYZE** operation is executed on this table. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to 2147483647. **Default value**: **50** ## autovacuum\_vacuum\_scale\_factor **Parameter description**: Specifies a fraction of the table size added to the **autovacuum\_vacuum\_threshold** parameter when deciding whether to vacuum a table. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: a floating point number ranging from 0.0 to 100.0 **Default value**: **0.2** ## autovacuum\_analyze\_scale\_factor **Parameter description**: Specifies a fraction of the table size added to the **autovacuum\_analyze\_threshold** parameter when deciding whether to analyze a table. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: a floating point number ranging from 0.0 to 100.0 **Default value**: **0.1** ## autovacuum\_freeze\_max\_age **Parameter description**: Specifies the maximum age (in transactions) that a table's **pg\_class.relfrozenxid** field can attain before a VACUUM operation is performed. * The old files under the subdirectory of **pg\_clog/** can also be deleted by the **VACUUM** operation. * Even if the **autovacuum** process is not started, the system will invoke the process to prevent transaction ID wraparound. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 100000 to 576460752303423487 **Default value**: **4000000000** ## autovacuum\_vacuum\_cost\_delay **Parameter description**: Specifies the value of the cost delay used in the **autovacuum** operation. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from –1 to 100. The unit is ms. **–1** indicates that the normal vacuum cost delay is used. **Default value**: **20ms** ## autovacuum\_vacuum\_cost\_limit **Parameter description:** sets the value of the cost limit used in the **autovacuum** operation. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from –1 to 10000 **–1** indicates that the normal vacuum cost limit is used. **Default value**: **–1** ## defer\_csn\_cleanup\_time **Parameter description**: Specifies the interval of recycling transaction IDs. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to *INT\_MAX*. The unit is ms. **Default value**: **5s** (5000 ms) --- --- url: /en/docs/latest/database_reference/automatic_vacuuming.md --- # Automatic Vacuuming The **autovacuum** process automatically runs the **VACUUM** and **ANALYZE** statements to recycle the record space marked as deleted and update statistics about the table. ## autovacuum **Parameter description**: Specifies whether to start the **autovacuum** process in the database. Ensure that the [track\_counts](query_and_index_statistics_collector.md#en-us_topic_0283136895_en-us_topic_0237124727_en-us_topic_0059779313_s3f4fb0b1004041f69e1454c701952411) parameter is set to **on** before starting the automatic cleanup process. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). > \[!NOTE]NOTE > > * Set the **autovacuum** parameter to **on** if you want to start the automatic cleanup of abnormal two-phase transactions when the system recovers from faults. > * If **autovacuum** is set to **on** and **[autovacuum\_max\_workers](#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s76932f79410248ba8923017d19982673)** to **0**, the autovacuum process is started only when the system recovers from faults to clean up abnormal two-phase transactions. > * If **autovacuum** is set to **on** and the value of [autovacuum\_max\_workers](#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s76932f79410248ba8923017d19982673) is greater than **0**, the system will automatically clean up the two-phase transactions and processes after recovering from faults. > \[!TIP]NOTICE > Even if **autovacuum** is set to **off**, the autovacuum process will be started automatically when a transaction ID wraparound is about to occur. When a **CREATE DATABASE** or **DROP DATABASE** operation fails, it is possible that the transaction has been committed or rolled back on some nodes whereas some nodes are still in the prepared state. In this case, perform the following operations to manually restore the nodes: **Value range**: Boolean * **on** indicates that the **autovacuum** process is started. * **off** indicates that the **autovacuum** process is not started. **Default value**: **on** ## autovacuum\_mode **Parameter description**: Specifies whether the autoanalyze or autovacuum function is started. This parameter is valid only when **autovacuum** is set to **on**. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: enumerated values * **analyze** indicates that only autoanalyze is performed. * **vacuum** indicates that only autovacuum is performed. * **mix** indicates that both autoanalyze and autovacuum are performed. * **none** indicates that neither of them is performed. **Default value**: **mix** ## autoanalyze\_timeout **Parameter description**: Specifies the timeout period of autoanalyze. If the duration of autoanalyze on a table exceeds the value of **autoanalyze\_timeout**, the autoanalyze is automatically canceled. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to 2147483. The unit is s. **Default value**: **5min** (300s) ## autovacuum\_io\_limits **Parameter description**: Specifies the upper limit of I/Os triggered by the autovacuum process per second. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer. The value can be **–1** or a number ranging from 0 to 1073741823. **–1** indicates that the default cgroup is used. **Default value**: **–1** ## log\_autovacuum\_min\_duration **Parameter description**: Records each step performed by the autovacuum process to the server log when the execution time of the autovacuum process is greater than or equal to a certain value. This parameter helps track the autovacuum behavior. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). A setting example is as follows: Set the **log\_autovacuum\_min\_duration** parameter to 250 ms to record the actions of autovacuum if it runs for 250 ms or longer. **Value range**: an integer ranging from –1 to 2147483647. The unit is ms. * **0** indicates that all autovacuum actions are recorded in the log. * **–1** indicates that all autovacuum actions are not recorded in the log. * A value other than **–1** indicates that a message is recorded when an autovacuum action is skipped due to a lock conflict. **Default value**: **–1** ## autovacuum\_max\_workers **Parameter description**: Specifies the maximum number of autovacuum worker threads that can run at the same time. The upper limit of this parameter is related to the values of **max\_connections** and **job\_queue\_processes**. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer. The minimum value is **0**, indicating that autovacuum is not enabled. The theoretical maximum value is **262143**, but the actual maximum value is a dynamic value calculated by the following formula: 262143 - **max\_connections** - **job\_queue\_processes** - Number of auxiliary threads - Number of autovacuum launcher threads - 1. The number of auxiliary threads and the number of autovacuum launcher threads are specified by two macros. Their default values are **20** and **2** respectively. **Default value**: **3** ## autovacuum\_naptime **Parameter description**: Specifies the interval between activity rounds for the autovacuum process. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 1 to 2147483. The unit is s. **Default value**: **10min** (600s) ## autovacuum\_vacuum\_threshold **Parameter description**: Specifies the threshold for triggering the **VACUUM** operation. When the number of deleted or updated records in a table exceeds the specified threshold, the **VACUUM** operation is executed on this table. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to 2147483647. **Default value**: **50** ## autovacuum\_analyze\_threshold **Parameter description**: Specifies the threshold for triggering the **ANALYZE** operation. When the number of deleted, inserted, or updated records in a table exceeds the specified threshold, the **ANALYZE** operation is executed on this table. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to 2147483647. **Default value**: **50** ## autovacuum\_vacuum\_scale\_factor **Parameter description**: Specifies a fraction of the table size added to the **autovacuum\_vacuum\_threshold** parameter when deciding whether to vacuum a table. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: a floating point number ranging from 0.0 to 100.0 **Default value**: **0.2** ## autovacuum\_analyze\_scale\_factor **Parameter description**: Specifies a fraction of the table size added to the **autovacuum\_analyze\_threshold** parameter when deciding whether to analyze a table. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: a floating point number ranging from 0.0 to 100.0 **Default value**: **0.1** ## autovacuum\_freeze\_max\_age **Parameter description**: Specifies the maximum age (in transactions) that a table's **pg\_class.relfrozenxid** field can attain before a VACUUM operation is performed. * The old files under the subdirectory of **pg\_clog/** can also be deleted by the **VACUUM** operation. * Even if the **autovacuum** process is not started, the system will invoke the process to prevent transaction ID wraparound. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 100000 to 576460752303423487 **Default value**: **4000000000** ## autovacuum\_vacuum\_cost\_delay **Parameter description**: Specifies the value of the cost delay used in the **autovacuum** operation. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from –1 to 100. The unit is ms. **–1** indicates that the normal vacuum cost delay is used. **Default value**: **20ms** ## autovacuum\_vacuum\_cost\_limit **Parameter description:** sets the value of the cost limit used in the **autovacuum** operation. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from –1 to 10000 **–1** indicates that the normal vacuum cost limit is used. **Default value**: **–1** ## defer\_csn\_cleanup\_time **Parameter description**: Specifies the interval of recycling transaction IDs. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to *INT\_MAX*. The unit is ms. **Default value**: **5s** (5000 ms) --- --- url: /en/docs/latest-lite/characteristic_description/autonomous_transaction.md --- # Autonomous Transaction ## Availability This feature is available since openGauss 1.1.0. ## Introduction An autonomous transaction is a type of transaction in which the commit of a sub-transaction is not affected by the commit or rollback of the main transaction. ## Benefits This feature meets diversified application scenarios. ## Description In an autonomous transaction, a specified type of SQL statements are executed in an independent transaction context during the execution of the main transaction. The commit and rollback operations of an autonomous transaction are not affected by the commit and rollback operations of the main transaction. User-defined functions and stored procedures support autonomous transactions. A typical application scenario is as follows: A table is used to record the operation information during the main transaction execution. When the main transaction fails to be rolled back, the operation information recorded in the table cannot be rolled back. ## Enhancements None. ## Constraints * A trigger function does not support autonomous transactions. * In the autonomous transaction block of a function or stored procedure, static SQL statements do not support variable transfer. * Autonomous transactions do not support nesting. * A function containing an autonomous transaction does not support the return value of parameter transfer. * A stored procedure or function that contains an autonomous transaction does not support exception handling. ## Dependencies None. --- --- url: /en/docs/latest-lite/sql_reference/autonomous_transaction.md --- # Autonomous Transaction An autonomous transaction is an independent transaction that is started during the execution of a primary transaction. Committing and rolling back an autonomous transaction does not affect the data that has been committed by the primary transaction. In addition, an autonomous transaction is not affected by the primary transaction. Autonomous transactions are defined in stored procedures, functions, and anonymous blocks, and are declared using the **PRAGMA AUTONOMOUS\_TRANSACTION** keyword. * **[Stored Procedure Supporting Autonomous Transaction](stored_procedure_supporting_autonomous_transaction.md)** * **[Anonymous Block Supporting Autonomous Transaction](anonymous_block_supporting_autonomous_transaction.md)** * **[Function Supporting Autonomous Transaction](function_supporting_autonomous_transaction.md)** * **[Restrictions](restrictions.md)** --- --- url: /en/docs/latest/characteristic_description/autonomous_transaction.md --- # Autonomous Transaction ## Availability This feature is available since openGauss 1.1.0. ## Introduction An autonomous transaction is a type of transaction in which the commit of a sub-transaction is not affected by the commit or rollback of the main transaction. ## Benefits This feature meets diversified application scenarios. ## Description In an autonomous transaction, a specified type of SQL statements are executed in an independent transaction context during the execution of the main transaction. The commit and rollback operations of an autonomous transaction are not affected by the commit and rollback operations of the main transaction. User-defined functions and stored procedures support autonomous transactions. A typical application scenario is as follows: A table is used to record the operation information during the main transaction execution. When the main transaction fails to be rolled back, the operation information recorded in the table cannot be rolled back. ## Enhancements None ## Constraints * A trigger function does not support autonomous transactions. * In the autonomous transaction block of a function or stored procedure, static SQL statements do not support variable transfer. * Autonomous transactions do not support nesting. * A function containing an autonomous transaction does not support the return value of parameter transfer. * A stored procedure or function that contains an autonomous transaction does not support exception handling. ## Dependencies None --- --- url: /en/docs/latest/sql_reference/autonomous_transaction.md --- # Autonomous Transaction An autonomous transaction is an independent transaction that is started during the execution of a primary transaction. Committing and rolling back an autonomous transaction does not affect the data that has been committed by the primary transaction. In addition, an autonomous transaction is not affected by the primary transaction. Autonomous transactions are defined in stored procedures, functions, and anonymous blocks, and are declared using the **PRAGMA AUTONOMOUS\_TRANSACTION** keyword. * **[Stored Procedure Supporting Autonomous Transaction](stored_procedure_supporting_autonomous_transaction.md)** * **[Anonymous Block Supporting Autonomous Transaction](anonymous_block_supporting_autonomous_transaction.md)** * **[Function Supporting Autonomous Transaction](function_supporting_autonomous_transaction.md)** * **[Restrictions](restrictions.md)** --- --- url: /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_lock.md --- # B-Compatible Database Lock To ensure database data consistency, you can execute the LOCK TABLES statement to prevent other users from modifying tables. For example, an application needs to ensure that data in a table is not modified during transaction running. For this purpose, table usage can be locked. This prevents data from being concurrently modified. After LOCK TABLES is used, the subsequent SQL statements are in the transaction state. Therefore, you need to run UNLOCK TABLES to manually release the lock and end the transaction. In addition, if you want to make the current session read-only, you can use FLUSH TABLES WITH READ LOCK to implement this function. Then, you need to use UNLOCK TABLES to manually disable this function. ## Syntax * Lock. ``` LOCK TABLES namelist READ/WRITE ``` * Make the current session read-only. ``` FLUSH TABLES WITH READ LOCK ``` * Unlock. ``` UNLOCK TABLES ``` ## Parameter Description * **namelist** Name of the table to be locked. Multiple tables are allowed. * **READ/WRITE** Lock mode. Values: * **READ** Tables can be read only. * **WRITE** The holder is the only transaction accessing the table in any way. ## Examples Obtains a **WRITE** lock on a table when going to perform a delete operation. ``` --Create an example table. openGauss=# CREATE TABLE graderecord ( number INTEGER, name CHAR(20), class CHAR(20), grade INTEGER ); --Insert data. openGauss=# insert into graderecord values('210101','Alan','21.01',92); --Provide the example table. openGauss=# LOCK TABLES graderecord WRITE; --Delete the example table. openGauss=# DELETE FROM graderecord WHERE name ='Alan'; openGauss=# UNLOCK TABLES; ``` --- --- url: /en/docs/latest-lite/database_om_guide/b_tree_index_faults.md --- # B-tree Index Faults ## Symptom The following error message is displayed, indicating that the index is lost occasionally. ``` ERROR: index 'xxxx_index' contains unexpected zero page Or ERROR: index 'pg_xxxx_index' contains unexpected zero page Or ERROR: compressed data is corrupt ``` ## Cause Analysis This type of error is caused by the index fault. The possible causes are as follows: * The index is unavailable due to software bugs or hardware faults. * The index contains many empty pages or almost empty pages. * During concurrent DDL execution, the network is intermittently disconnected. * The index failed to be created when indexes are concurrently created. * A network fault occurs when a DDL or DML operation is performed. ## Procedure Run the REINDEX command to rebuild the index. 1. Log in to the host as the OS user **omm**. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 -r ``` 3. Rebuild the index. * During DDL or DML operations, if index problems occur due to software or hardware faults, run the following command to rebuild the index: ``` REINDEX TABLE tablename; ``` * If the error message contains *xxxx***\_index**, the index of a user table is faulty. *xxxx* indicates the name of the user table. Run either of the following commands to rebuild the index: ``` REINDEX INDEX indexname; ``` Or ``` REINDEX TABLE tablename; ``` * If the error message contains **pg\_***xxxx***\_index**, the index of the system catalog is faulty. Run the following command to rebuild the index: ``` REINDEX SYSTEM databasename; ``` --- --- url: /en/docs/latest/resource_pooling/b_tree_index_faults.md --- # B-tree Index Faults ## Symptom The following error message is displayed, indicating that the index is lost occasionally. ``` ERROR: index 'xxxx_index' contains unexpected zero page Or ERROR: index 'pg_xxxx_index' contains unexpected zero page Or ERROR: compressed data is corrupt ``` ## Cause Analysis This type of error is caused by the index fault. The possible causes are as follows: * The index is unavailable due to software bugs or hardware faults. * The index contains many empty pages or almost empty pages. * During concurrent DDL execution, the network is intermittently disconnected. * The index failed to be created when indexes are concurrently created. * A network fault occurs when a DDL or DML operation is performed. ## Procedure Run the REINDEX command to rebuild the index. 1. Log in to the host as the OS user **omm**. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 -r ``` 3. Rebuild the index. * During DDL or DML operations, if index problems occur due to software or hardware faults, run the following command to rebuild the index: ``` REINDEX TABLE tablename; ``` * If the error message contains *xxxx***\_index**, the index of a user table is faulty. *xxxx* indicates the name of the user table. Run either of the following commands to rebuild the index: ``` REINDEX INDEX indexname; ``` Or ``` REINDEX TABLE tablename; ``` * If the error message contains **pg\_***xxxx***\_index**, the index of the system catalog is faulty. Run the following command to rebuild the index: ``` REINDEX SYSTEM databasename; ``` --- --- url: /en/docs/latest-lite/database_reference/background_writer.md --- # Background Writer This section describes background writer parameters. The background writer process is used to write dirty data (new or modified data) in shared buffers to disks. This mechanism ensures that database processes seldom or never need to wait for a write action to occur when handling user queries. It also mitigates performance deterioration caused by checkpoints because only a few of dirty pages need to be flushed to the disk when the checkpoints arrive. This mechanism, however, increases the overall net I/O load because while a repeatedly-dirtied page may otherwise be written only once per checkpoint interval, the background writer may write it several times as it is dirtied in the same interval. In most cases, continuous light loads are preferred, instead of periodical load peaks. The parameters discussed in this section can be set based on actual requirements. ## bgwriter\_delay **Parameter description**: Specifies the interval at which the background writer writes dirty shared buffers. Each time, the backend write process initiates write operations for some dirty buffers. In full checkpoint mode, the **bgwriter\_lru\_maxpages** parameter is used to control the amount of data to be written each time, and the process is restarted after *bgwriter\_delay* ms hibernation. In incremental checkpoint mode, the number of target idle buffer pages is calculated based on the value of **candidate\_buf\_percent\_target**. If the number of idle buffer pages is insufficient, a batch of pages is flushed to disks every *bgwriter\_delay* ms. The number of flushed pages is calculated based on the target difference percentage. The maximum number of flushed pages is limited by **max\_io\_capacity**. In many systems, the effective resolution of sleep delays is 10 milliseconds. Therefore, setting this parameter to a value that is not a multiple of 10 has the same effect as setting it to the next higher multiple of 10. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 10 to 10000. The unit is millisecond. **Default value**: **2s** **Setting suggestion:** Reduce this value in slow data writing scenarios to reduce the checkpoint load. ## candidate\_buf\_percent\_target **Parameter description**: Specifies the expected percentage of available buffers in the shared\_buffer memory buffer in the candidate buffer chain when the incremental checkpoint is enabled. If the number of available buffers in the current candidate chain is less than the target value, the bgwriter thread starts flushing dirty pages that meet the requirements. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** a double-precision floating point number ranging from 0.1 to 0.85 **Default value**: **0.3** ## bgwriter\_lru\_maxpages **Parameter description**: Specifies the number of dirty buffers the background writer can write in each round. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 1000 > \[!NOTE]NOTE > When this parameter is set to **0**, the background writer is disabled. This setting does not affect checkpoints. **Default value**: **100** ## bgwriter\_lru\_multiplier **Parameter description**: Specifies the coefficient used to estimate the number of dirty buffers the background writer can write in the next round. The number of dirty buffers written in each round depends on the number of buffers used by server processes during recent rounds. The estimated number of buffers required in the next round is calculated using the following formula: Average number of recently used buffers x **bgwriter\_lru\_multiplier**. The background writer writes dirty buffers until sufficient, clean and reusable buffers are available. The number of buffers the background writer writes in each round is always equal to or less than the value of **bgwriter\_lru\_maxpages**. Therefore, the value **1.0** of **bgwriter\_lru\_multiplier** represents a just-in-time policy of writing exactly the number of dirty buffers predicted to be required. Larger values provide some cushion against spikes in demand, whereas smaller values intentionally leave more writes to be done by server processes. Smaller values of **bgwriter\_lru\_maxpages** and **bgwriter\_lru\_multiplier** reduce the extra I/O load caused by the background writer, but make it more likely that server processes will have to issue writes for themselves, delaying interactive queries. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a floating point number ranging from 0 to 10 **Default value:** **2** ## pagewriter\_thread\_num **Parameter description**: Specifies the number of threads for background page flushing after the incremental checkpoint is enabled. Dirty pages are flushed in sequence to disks, promoting recovery points. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to 16 **Default value**: **4** ## dirty\_page\_percent\_max **Parameter description**: Specifies the percentage of dirty pages to **shared\_buffers** after the incremental checkpoint is enabled. When the value of this parameter is reached, the background page flush thread flushes dirty pages based on the maximum value of max\_io\_capacity. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a floating point number ranging from 0.1 to 1 **Default value**: **0.9** ## pagewriter\_sleep **Parameter description**: Specifies the interval for the pagewriter thread to flush dirty pages to disks after the incremental checkpoint is enabled. When the ratio of dirty pages to shared\_buffers reaches dirty\_page\_percent\_max, the number of pages in each batch is calculated based on the value of max\_io\_capacity. In other cases, the number of pages in each batch decreases proportionally. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 3600000. The unit is ms. **Default value**: **2000ms(2s)** ## max\_io\_capacity **Parameter description**: Specifies the maximum I/O per second for the backend write process to flush pages in batches. Set this parameter based on the service scenario and disk I/O capability of the host. If the RTO is short or the data volume is much larger than the shared memory, and the service access data volume is random, the value of this parameter cannot be too small. A small parameter value reduces the number of pages flushed by the backend write process. If a large number of pages are eliminated due to service triggering, the services are affected. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 30720 to 10485760. The unit is kB. **Default value**: **512000 kB** (500 MB) ## enable\_consider\_usecount **Parameter description**: Specifies whether the backend thread considers the page popularity during page replacement. You are advised to enable this parameter in large-capacity scenarios. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on**/**true**: The page popularity is considered. * **off**/**false**: The page popularity is not considered. **Default value**: **off** ## dw\_file\_num **Parameter description**: Specifies the number of doublewrite files to be written in batches. The value is related to **pagewriter\_thread\_num** and cannot be greater than **pagwriter\_thread\_num**. If the value is too large, it will be corrected to the value of **pagewriter\_thread\_num**. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to 16 **Default value**: **1** ## dw\_file\_size **Parameter description**: Specifies the size of each doulewrite file. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer, in the range \[32,256] **Default value**: **256** --- --- url: /en/docs/latest/database_reference/background_writer.md --- # Background Writer This section describes background writer parameters. The background writer process is used to write dirty data (new or modified data) in shared buffers to disks. This mechanism ensures that database processes seldom or never need to wait for a write action to occur when handling user queries. It also mitigates performance deterioration caused by checkpoints because only a few of dirty pages need to be flushed to the disk when the checkpoints arrive. This mechanism, however, increases the overall net I/O load because while a repeatedly-dirtied page may otherwise be written only once per checkpoint interval, the background writer may write it several times as it is dirtied in the same interval. In most cases, continuous light loads are preferred, instead of periodical load peaks. The parameters discussed in this section can be set based on actual requirements. ## bgwriter\_delay **Parameter description**: Specifies the interval at which the background writer writes dirty shared buffers. Each time, the backend write process initiates write operations for some dirty buffers. In full checkpoint mode, the **bgwriter\_lru\_maxpages** parameter is used to control the amount of data to be written each time, and the process is restarted after *bgwriter\_delay* ms hibernation. In incremental checkpoint mode, the number of target idle buffer pages is calculated based on the value of **candidate\_buf\_percent\_target**. If the number of idle buffer pages is insufficient, a batch of pages is flushed to disks every *bgwriter\_delay* ms. The number of flushed pages is calculated based on the target difference percentage. The maximum number of flushed pages is limited by **max\_io\_capacity**. In many systems, the effective resolution of sleep delays is 10 milliseconds. Therefore, setting this parameter to a value that is not a multiple of 10 has the same effect as setting it to the next higher multiple of 10. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 10 to 10000. The unit is millisecond. **Default value**: **2s** **Setting suggestion:** Reduce this value in slow data writing scenarios to reduce the checkpoint load. ## candidate\_buf\_percent\_target **Parameter description**: Specifies the expected percentage of available buffers in the shared\_buffer memory buffer in the candidate buffer chain when the incremental checkpoint is enabled. If the number of available buffers in the current candidate chain is less than the target value, the bgwriter thread starts flushing dirty pages that meet the requirements. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** a double-precision floating point number ranging from 0.1 to 0.85 **Default value**: **0.3** ## bgwriter\_lru\_maxpages **Parameter description**: Specifies the number of dirty buffers the background writer can write in each round. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 1000 > \[!NOTE]NOTE > When this parameter is set to **0**, the background writer is disabled. This setting does not affect checkpoints. **Default value**: **100** ## bgwriter\_lru\_multiplier **Parameter description**: Specifies the coefficient used to estimate the number of dirty buffers the background writer can write in the next round. The number of dirty buffers written in each round depends on the number of buffers used by server processes during recent rounds. The estimated number of buffers required in the next round is calculated using the following formula: Average number of recently used buffers x **bgwriter\_lru\_multiplier**. The background writer writes dirty buffers until sufficient, clean and reusable buffers are available. The number of buffers the background writer writes in each round is always equal to or less than the value of **bgwriter\_lru\_maxpages**. Therefore, the value **1.0** of **bgwriter\_lru\_multiplier** represents a just-in-time policy of writing exactly the number of dirty buffers predicted to be required. Larger values provide some cushion against spikes in demand, whereas smaller values intentionally leave more writes to be done by server processes. Smaller values of **bgwriter\_lru\_maxpages** and **bgwriter\_lru\_multiplier** reduce the extra I/O load caused by the background writer, but make it more likely that server processes will have to issue writes for themselves, delaying interactive queries. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a floating point number ranging from 0 to 10 **Default value:** **2** ## pagewriter\_thread\_num **Parameter description**: Specifies the number of threads for background page flushing after the incremental checkpoint is enabled. Dirty pages are flushed in sequence to disks, promoting recovery points. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to 16 **Default value**: **4** ## dirty\_page\_percent\_max **Parameter description**: Specifies the percentage of dirty pages to **shared\_buffers**after the incremental checkpoint is enabled. When the value of this parameter is reached, the background page flush thread flushes dirty pages based on the maximum value of max\_io\_capacity. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a floating point number ranging from 0.1 to 1 **Default value**: **0.9** ## pagewriter\_sleep **Parameter description**: Specifies the interval for the pagewriter thread to flush dirty pages to disks after the incremental checkpoint is enabled. When the ratio of dirty pages to shared\_buffers reaches dirty\_page\_percent\_max, the number of pages in each batch is calculated based on the value of max\_io\_capacity. In other cases, the number of pages in each batch decreases proportionally. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 3600000. The unit is ms. **Default value**: **2000ms(2s)** ## max\_io\_capacity **Parameter description**: Specifies the maximum I/O per second for the backend write process to flush pages in batches. Set this parameter based on the service scenario and disk I/O capability of the host. If the RTO is short or the data volume is much larger than the shared memory, and the service access data volume is random, the value of this parameter cannot be too small. A small parameter value reduces the number of pages flushed by the backend write process. If a large number of pages are eliminated due to service triggering, the services are affected. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 30720 to 10485760. The unit is kB. **Default value**: **512000 kB** (500 MB) ## enable\_consider\_usecount **Parameter description**: Specifies whether the backend thread considers the page popularity during page replacement. You are advised to enable this parameter in large-capacity scenarios. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on**/**true**: The page popularity is considered. * **off**/**false**: The page popularity is not considered. **Default value**: **off** ## dw\_file\_num **Parameter description**: Specifies the number of doublewrite files to be written in batches. The value is related to **pagewriter\_thread\_num** and cannot be greater than **pagwriter\_thread\_num**. If the value is too large, it will be corrected to the value of **pagewriter\_thread\_num**. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to 16 **Default value**: **1** ## dw\_file\_size **Parameter description**: Specifies the size of each doulewrite file. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer, in the range \[32,256] **Default value**: **256** --- --- url: /en/docs/latest-lite/database_reference/backup_and_restoration.md --- # Backup and Restoration ## operation\_mode **Parameter description**: Specifies whether the system enters the backup and restoration mode. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that the system is in the backup and restoration mode. * **off** indicates that the system is not in the backup and restoration mode. **Default value**: **off** ## enable\_cbm\_tracking **Parameter description:** This parameter must be enabled when Roach is used to perform full and incremental backups. If this parameter is disabled, the backup will fail. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on**: The cbm tracking is enabled. * **off**: The cbm tracking is disabled. **Default value**: **off** ## hadr\_max\_size\_for\_xlog\_receiver **Parameter description**: Specifies the maximum difference between the OBS logs obtained by instances in the DR database instance and the local playback logs. If the difference is greater than the value of this parameter, the instances stop obtaining OBS logs. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Handling suggestion**: The value of this parameter is related to the local disk size. You are advised to set this parameter to 50% of the local disk size. **Value range**: an integer ranging from 0 to 2147483647 **Default value**: **256 GB** --- --- url: /en/docs/latest/database_reference/backup_and_restoration.md --- # Backup and Restoration ## operation\_mode **Parameter description**: Specifies whether the system enters the backup and restoration mode. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that the system is in the backup and restoration mode. * **off** indicates that the system is not in the backup and restoration mode. **Default value**: **off** ## enable\_cbm\_tracking **Parameter description:** This parameter must be enabled when Roach is used to perform full and incremental backups. If this parameter is disabled, the backup will fail. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on**: The cbm tracking is enabled. * **off**: The cbm tracking is disabled. **Default value**: **off** ## hadr\_max\_size\_for\_xlog\_receiver **Parameter description**: Specifies the maximum difference between the OBS logs obtained by instances in the DR database instance and the local playback logs. If the difference is greater than the value of this parameter, the instances stop obtaining OBS logs. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Handling suggestion**: The value of this parameter is related to the local disk size. You are advised to set this parameter to 50% of the local disk size. **Value range**: an integer ranging from 0 to 2147483647 **Default value**: **256 GB** --- --- url: /en/docs/latest-lite/sql_reference/backup_and_restoration_control_functions.md --- # Backup and Restoration Control Functions ## Backup Control Functions Backup control functions help with online backup. * pg\_create\_restore\_point(name text) Description: Creates a named point for performing the restoration operation (restricted to the system administrator). Return type: text Note: **pg\_create\_restore\_point** creates a named transaction log record that can be used as a restoration target, and returns the corresponding transaction log location. The given name can then be used with **recovery\_target\_name** to specify the point up to which restoration will proceed. Avoid creating multiple restoration points with the same name, since restoration will stop at the first one whose name matches the restoration target. * pg\_current\_xlog\_location() Description: Obtains the write position of the current transaction log. Return type: text Note: **pg\_current\_xlog\_location** displays the write position of the current transaction log in the same format as those of the previous functions. Read-only operations do not require permissions of the system administrator. * pg\_current\_xlog\_insert\_location() Description: Obtains the insert position of the current transaction log. Return type: text Note: **pg\_current\_xlog\_insert\_location** displays the insert position of the current transaction log. The insertion point is the logical end of the transaction log at any instant, while the write location is the end of what has been written out from the server's internal buffers. The write position is the end that can be detected externally from the server. This operation can be performed to archive only some of completed transaction log files. The insert position is mainly used for commissioning the server. Read-only operations do not require permissions of the system administrator. * gs\_current\_xlog\_insert\_end\_location() Description: Obtains the insert position of the current transaction log. Return type: text Note: **gs\_current\_xlog\_insert\_end\_location** displays the insert position of the current transaction log. * pg\_start\_backup(label text \[, fast boolean ]) Description: Starts executing online backup (restricted to the system administrator or replication roles). Return type: text Note: **pg\_start\_backup** receives a user-defined backup label (usually the name of the position where the backup dump file is stored). This function writes a backup label file to the data directory of openGauss and then returns the start position of backed up transaction logs in text mode. ``` openGauss=# SELECT pg_start_backup('label_goes_here'); pg_start_backup ----------------- 0/3000020 (1 row) ``` * pg\_stop\_backup() Description: Completes online backup (restricted to the system administrator or replication roles). Return type: text Note: **pg\_stop\_backup** deletes the label file created by **pg\_start\_backup** and creates a backup history file in the transaction log archive area. The history file includes the label given to **pg\_start\_backup**, the start and end transaction log locations for the backup, and the start and end time of the backup. The return value is the backup's ending transaction log location. After the end position is calculated, the insert position of the current transaction log automatically goes ahead to the next transaction log file. In this way, the ended transaction log file can be immediately archived so that backup is complete. * pg\_switch\_xlog() Description: Switches to a new transaction log file (restricted to the system administrator). Return type: text Note: **pg\_switch\_xlog** moves to the next transaction log file so that the current log file can be archived (if continuous archive is used). The return value is the ending transaction log location + 1 within the just-completed transaction log file. If there has been no transaction log activity since the last transaction log switchover, **pg\_switch\_xlog** will do nothing but return the start location of the transaction log file currently in use. * pg\_xlogfile\_name(location text) Description: Converts the position string in a transaction log to a file name. Return type: text Note: **pg\_xlogfile\_name** extracts only the transaction log file name. If the given transaction log position is the transaction log file border, a transaction log file name will be returned for both the two functions. This is usually the desired behavior for managing transaction log archiving, since the preceding file is the last one that currently needs to be archived. * pg\_xlogfile\_name\_offset(location text) Description: Converts the position string in a transaction log to a file name and returns the byte offset in the file. Return type: text and integer Note: **pg\_xlogfile\_name\_offset** can extract transaction log file names and byte offsets from the returned results of the preceding functions. Example: ``` openGauss=# SELECT * FROM pg_xlogfile_name_offset(pg_stop_backup()); NOTICE: pg_stop_backup cleanup done, waiting for required WAL segments to be archived NOTICE: pg_stop_backup complete, all required WAL segments have been archived file_name | file_offset --------------------------+------------- 000000010000000000000003 | 272 (1 row) ``` * pg\_xlog\_location\_diff(location text, location text) Description: Calculates the difference in bytes between two transaction log locations. Return type: numeric * pg\_cbm\_tracked\_location() Description: Queries the LSN location parsed by CBM. Return type: text * pg\_cbm\_get\_merged\_file(startLSNArg text, endLSNArg text) Description: Combines CBM files within the specified LSN range into one and returns the name of the combined file. Return type: text Note: Only the system administrator or O\&M administrator can obtain the CBM combination file. * pg\_cbm\_get\_changed\_block(startLSNArg text, endLSNArg text) Description: Combines CBM files within the specified LSN range into a table and return records of this table. Return type: record Note: The table columns include the start LSN, end LSN, tablespace OID, database OID, table relfilenode, table fork number, whether the table is deleted, whether the table is created, whether the table is truncated, number of pages in the truncated table, number of modified pages, and list of modified page numbers. * pg\_cbm\_recycle\_file(targetLSNArg text) Description: Deletes the CBM files that are no longer used and returns the first LSN after the deletion. Return type: text * pg\_cbm\_force\_track(targetLSNArg text,timeOut int) Description: Forcibly executes the CBM trace to the specified Xlog position and returns the Xlog position of the actual trace end point. Return type: text * pg\_enable\_delay\_ddl\_recycle() Description: Enables DDL delay and returns the Xlog position of the enabling point. You need to enable **operate\_mode** as the administrator or O\&M administrator. Return type: text * pg\_disable\_delay\_ddl\_recycle(barrierLSNArg text, isForce bool) Description: Disables DDL delay and returns the Xlog range where DDL delay takes effect. You need to enable **operate\_mode** as the administrator or O\&M administrator. Return type: record * pg\_enable\_delay\_xlog\_recycle() Description: Enables Xlog recycle delay. This function is used in primary database node restoration. Return type: void * pg\_disable\_delay\_xlog\_recycle() Description: Disables Xlog recycle delay. This function is used in primary database node restoration. Return type: void * pg\_cbm\_rotate\_file(rotate\_lsn text) Description: Forcibly switches the file after the CBM parses **rotate\_lsn**. This function is called during the build process. Return type: void * gs\_roach\_stop\_backup(backupid text) Description: Stops a backup started by the internal backup tool GaussRoach. It is similar to the **pg\_stop\_backup system** function but is more lightweight. Return type: text. The content is the insertion position of the current log. > \[!NOTE]NOTE > > In the Lite scenario, openGauss provides this API, but the Roach-related functions are unavailable. * gs\_roach\_enable\_delay\_ddl\_recycle(backupid name) Description: Enables DDL delay and returns the log location of the enabling point. It is similar to the **pg\_enable\_delay\_ddl\_recycle** system function but is more lightweight. In addition, different **backupid** values can be used to concurrently open DDL statements with delay. Return type: text. The content is the log location of the start point. > \[!NOTE]NOTE > > In the Lite scenario, openGauss provides this API, but the Roach-related functions are unavailable. * gs\_roach\_disable\_delay\_ddl\_recycle(backupid text) Description: Disables DDL delay, returns the range of logs on which DDL delay takes effect, and deletes the physical files of column-store tables that are deleted by users within this range. It is similar to the **pg\_enable\_delay\_ddl\_recycle** system function but is more lightweight. In addition, the DDL delay function can be disabled concurrently by specifying different backupid values. Return type: record. The content is the range of logs for which DDL is delayed to take effect. > \[!NOTE]NOTE > > In the Lite scenario, openGauss provides this API, but the Roach-related functions are unavailable. * gs\_roach\_switch\_xlog(request\_ckpt bool) Description: Switches the currently used log segment file and triggers a full checkpoint if **request\_ckpt** is set to **true**. Return type: text. The content is the location of the segment log. > \[!NOTE]NOTE > > In the Lite scenario, openGauss provides this API, but the Roach-related functions are unavailable. ## Restoration Control Functions Restoration control functions provide information about the status of standby nodes. These functions may be executed both during restoration and in normal running. * pg\_is\_in\_recovery() Description: Returns **true** if restoration is still in progress. Return type: Boolean * pg\_last\_xlog\_receive\_location() Description: Obtains the last transaction log location received and synchronized to disk by streaming replication. While streaming replication is in progress, this will increase monotonically. If restoration has been completed, then this value will remain static at the value of the last WAL record received and synchronized to disk during restoration. If streaming replication is disabled or if it has not yet started, the function returns **NULL**. Return type: text * pg\_last\_xlog\_replay\_location() Description: Obtains last transaction log location replayed during restoration. If restoration is still in progress, this will increase monotonically. If restoration has been completed, then this value will remain static at the value of the last WAL record received during that restoration. When the server has been started normally without restoration, the function returns **NULL**. Return type: text * pg\_last\_xact\_replay\_timestamp() Description: Obtains the timestamp of last transaction replayed during restoration. This is the time to commit a transaction or abort a WAL record on the primary node. If no transactions have been replayed during restoration, this function will return **NULL**. If restoration is still in progress, this will increase monotonically. If restoration has been completed, then this value will remain static at the value of the last WAL record received during that restoration. If the server normally starts without manual intervention, this function will return **NULL**. Return type: timestamp with time zone Restoration control functions control restoration processes. These functions may be executed only during restoration. * pg\_is\_xlog\_replay\_paused() Description: Returns **true** if restoration is paused. Return type: Boolean * pg\_xlog\_replay\_pause() Description: Pauses restoration immediately. Return type: void * pg\_xlog\_replay\_resume() Description: Restarts restoration if it was paused. Return type: void While restoration is paused, no further database changes are applied. In hot standby mode, all new queries will see the same consistent snapshot of the database, and no further query conflicts will be generated until restoration is resumed. If streaming replication is disabled, the paused state may continue indefinitely without problem. While streaming replication is in progress, WAL records will continue to be received, which will eventually fill available disk space. This progress depends on the duration of the pause, the rate of WAL generation, and available disk space. --- --- url: /en/docs/latest/sql_reference/backup_and_restoration_control_functions.md --- # Backup and Restoration Control Functions ## Backup Control Functions Backup control functions help with online backup. * pg\_create\_restore\_point(name text) Description: Creates a named point for performing the restoration operation (restricted to the system administrator). Return type: text Note: **pg\_create\_restore\_point** creates a named transaction log record that can be used as a restoration target, and returns the corresponding transaction log location. The given name can then be used with **recovery\_target\_name** to specify the point up to which restoration will proceed. Avoid creating multiple restoration points with the same name, since restoration will stop at the first one whose name matches the restoration target. * pg\_current\_xlog\_location() Description: Obtains the write position of the current transaction log. Return type: text Note: **pg\_current\_xlog\_location** displays the write position of the current transaction log in the same format as those of the previous functions. Read-only operations do not require permissions of the system administrator. * pg\_current\_xlog\_insert\_location() Description: Obtains the insert position of the current transaction log. Return type: text Note: **pg\_current\_xlog\_insert\_location** displays the insert position of the current transaction log. The insertion point is the logical end of the transaction log at any instant, while the write location is the end of what has been written out from the server's internal buffers. The write position is the end that can be detected externally from the server. This operation can be performed to archive only some of completed transaction log files. The insert position is mainly used for commissioning the server. Read-only operations do not require permissions of the system administrator. * gs\_current\_xlog\_insert\_end\_location() Description: Obtains the insert position of the current transaction log. Return type: text Note: **gs\_current\_xlog\_insert\_end\_location** displays the insert position of the current transaction log. * pg\_start\_backup(label text \[, fast boolean ]) Description: Starts executing online backup (restricted to the system administrator or replication roles). Return type: text Note: **pg\_start\_backup** receives a user-defined backup label (usually the name of the position where the backup dump file is stored). This function writes a backup label file to the data directory of openGauss and then returns the start position of backed up transaction logs in text mode. ``` openGauss=# SELECT pg_start_backup('label_goes_here'); pg_start_backup ----------------- 0/3000020 (1 row) ``` * gs\_get\_recv\_locations() Description: Obtain the synchronization position of the current transaction log on the standby machine,even if the primary is down, it can still be queried. Return type: record **Table 1** Return value description Example: ``` openGauss=# SELECT * FROM gs_get_recv_locations(); received_lsn | write_lsn | flush_lsn | replay_lsn -------------+------------+------------+------------ 0/42CE1340 | 0/42CE1340 | 0/42CE1340 | 0/42CC9078 (1 row) ``` * pg\_stop\_backup() Description: Completes online backup (restricted to the system administrator or replication roles). Return type: text Note: **pg\_stop\_backup** deletes the label file created by **pg\_start\_backup** and creates a backup history file in the transaction log archive area. The history file includes the label given to **pg\_start\_backup**, the start and end transaction log locations for the backup, and the start and end time of the backup. The return value is the backup's ending transaction log location. After the end position is calculated, the insert position of the current transaction log automatically goes ahead to the next transaction log file. In this way, the ended transaction log file can be immediately archived so that backup is complete. * pg\_switch\_xlog() Description: Switches to a new transaction log file (restricted to the system administrator). Return type: text Note: **pg\_switch\_xlog** moves to the next transaction log file so that the current log file can be archived (if continuous archive is used). The return value is the ending transaction log location + 1 within the just-completed transaction log file. If there has been no transaction log activity since the last transaction log switchover, **pg\_switch\_xlog** will do nothing but return the start location of the transaction log file currently in use. * pg\_xlogfile\_name(location text) Description: Converts the position string in a transaction log to a file name. Return type: text Note: **pg\_xlogfile\_name** extracts only the transaction log file name. If the given transaction log position is the transaction log file border, a transaction log file name will be returned for both the two functions. This is usually the desired behavior for managing transaction log archiving, since the preceding file is the last one that currently needs to be archived. * pg\_xlogfile\_name\_offset(location text) Description: Converts the position string in a transaction log to a file name and returns the byte offset in the file. Return type: text and integer Note: **pg\_xlogfile\_name\_offset** can extract transaction log file names and byte offsets from the returned results of the preceding functions. Example: ``` openGauss=# SELECT * FROM pg_xlogfile_name_offset(pg_stop_backup()); NOTICE: pg_stop_backup cleanup done, waiting for required WAL segments to be archived NOTICE: pg_stop_backup complete, all required WAL segments have been archived file_name | file_offset --------------------------+------------- 000000010000000000000003 | 272 (1 row) ``` * pg\_xlog\_location\_diff(location text, location text) Description: Calculates the difference in bytes between two transaction log locations. Return type: numeric * pg\_cbm\_tracked\_location() Description: Queries the LSN location parsed by CBM. Return type: text * pg\_cbm\_get\_merged\_file(startLSNArg text, endLSNArg text) Description: Combines CBM files within the specified LSN range into one and returns the name of the combined file. Return type: text Note: Only the system administrator or O\&M administrator can obtain the CBM combination file. * pg\_cbm\_get\_changed\_block(startLSNArg text, endLSNArg text) Description: Combines CBM files within the specified LSN range into a table and return records of this table. Return type: record Note: The table columns include the start LSN, end LSN, tablespace OID, database OID, table relfilenode, table fork number, whether the table is deleted, whether the table is created, whether the table is truncated, number of pages in the truncated table, number of modified pages, and list of modified page numbers. * pg\_cbm\_recycle\_file(targetLSNArg text) Description: Deletes the CBM files that are no longer used and returns the first LSN after the deletion. Return type: text * pg\_cbm\_force\_track(targetLSNArg text,timeOut int) Description: Forcibly executes the CBM trace to the specified Xlog position and returns the Xlog position of the actual trace end point. Return type: text * pg\_enable\_delay\_ddl\_recycle() Description: Enables DDL delay and returns the Xlog position of the enabling point. You need to enable **operate\_mode** as the administrator or O\&M administrator. Return type: text * pg\_disable\_delay\_ddl\_recycle(barrierLSNArg text, isForce bool) Description: Disables DDL delay and returns the Xlog range where DDL delay takes effect. You need to enable **operate\_mode** as the administrator or O\&M administrator. Return type: record * pg\_enable\_delay\_xlog\_recycle() Description: Enables Xlog recycle delay. This function is used in primary database node restoration. Return type: void * pg\_disable\_delay\_xlog\_recycle() Description: Disables Xlog recycle delay. This function is used in primary database node restoration. Return type: void * pg\_cbm\_rotate\_file(rotate\_lsn text) Description: Forcibly switches the file after the CBM parses **rotate\_lsn**. This function is called during the build process. Return type: void * gs\_roach\_stop\_backup(backupid text) Description: Stops a backup started by the internal backup tool GaussRoach. It is similar to the **pg\_stop\_backup system** function but is more lightweight. Return type: text. The content is the insertion position of the current log. Note: Currently, openGauss does not support this function. * gs\_roach\_enable\_delay\_ddl\_recycle(backupid name) Description: Enables DDL delay and returns the log location of the enabling point. It is similar to the **pg\_enable\_delay\_ddl\_recycle** system function but is more lightweight. In addition, different **backupid** values can be used to concurrently open DDL statements with delay. Return type: text. The content is the log location of the start point. Note: Currently, openGauss does not support this function. * gs\_roach\_disable\_delay\_ddl\_recycle(backupid text) Description: Disables DDL delay, returns the range of logs on which DDL delay takes effect, and deletes the physical files of column-store tables that are deleted by users within this range. It is similar to the **pg\_enable\_delay\_ddl\_recycle** system function but is more lightweight. In addition, the DDL delay function can be disabled concurrently by specifying different backupid values. Return type: record. The content is the range of logs for which DDL is delayed to take effect. Note: Currently, openGauss does not support this function. * gs\_roach\_switch\_xlog(request\_ckpt bool) Description: Switches the currently used log segment file and triggers a full checkpoint if **request\_ckpt** is set to **true**. Return type: text. The content is the location of the segment log. Note: Currently, openGauss does not support this function. ## Restoration Control Functions Restoration control functions provide information about the status of standby nodes. These functions may be executed both during restoration and in normal running. * pg\_is\_in\_recovery() Description: Returns **true** if restoration is still in progress. Return type: Boolean * pg\_last\_xlog\_receive\_location() Description: Obtains the last transaction log location received and synchronized to disk by streaming replication. While streaming replication is in progress, this will increase monotonically. If restoration has been completed, then this value will remain static at the value of the last WAL record received and synchronized to disk during restoration. If streaming replication is disabled or if it has not yet started, the function returns **NULL**. Return type: text * pg\_last\_xlog\_replay\_location() Description: Obtains last transaction log location replayed during restoration. If restoration is still in progress, this will increase monotonically. If restoration has been completed, then this value will remain static at the value of the last WAL record received during that restoration. When the server has been started normally without restoration, the function returns **NULL**. Return type: text * pg\_last\_xact\_replay\_timestamp() Description: Obtains the timestamp of last transaction replayed during restoration. This is the time to commit a transaction or abort a WAL record on the primary node. If no transactions have been replayed during restoration, this function will return **NULL**. If restoration is still in progress, this will increase monotonically. If restoration has been completed, then this value will remain static at the value of the last WAL record received during that restoration. If the server normally starts without manual intervention, this function will return **NULL**. Return type: timestamp with time zone Restoration control functions control restoration processes. These functions may be executed only during restoration. * pg\_is\_xlog\_replay\_paused() Description: Returns **true** if restoration is paused. Return type: Boolean * pg\_xlog\_replay\_pause() Description: Pauses restoration immediately. Return type: void * pg\_xlog\_replay\_resume() Description: Restarts restoration if it was paused. Return type: void While restoration is paused, no further database changes are applied. In hot standby mode, all new queries will see the same consistent snapshot of the database, and no further query conflicts will be generated until restoration is resumed. If streaming replication is disabled, the paused state may continue indefinitely without problem. While streaming replication is in progress, WAL records will continue to be received, which will eventually fill available disk space. This progress depends on the duration of the pause, the rate of WAL generation, and available disk space. --- --- url: /en/docs/latest/database_om_guide/configuration_files_backup_and_recovery.md --- # Backup And Restoration For Configuration Files ## Background If a static configuration file is damaged while you use openGauss, openGauss cannot obtain information about the openGauss topology structure and primary/standby relationship, affecting the openGauss function. In this case, you can use the **gs\_om** tool to generate a new static configuration file to replace the damaged file, ensuring normal openGauss running. ## Prerequisites None ## Procedure 1. Log in as the OS user **omm** to the primary node of the database. 2. Run the following command to generate configuration files in a specified directory on the current host: ``` gs_om -t generateconf -X /opt/software/openGauss/clusterconfig.xml --distribute ``` **/opt/software/openGauss/clusterconfig.xml** is the XML configuration files during the openGauss installation. > \[!NOTE]NOTE > > * After the command is executed, the new configuration file storage directory is displayed in the log information. Take a one-primary two-standby environment as an example. This directory contains three configuration files named by host names. You need to replace the configuration files of corresponding hosts with the three files respectively. > > * If **--distribute** is not specified, perform [3](#en-us_topic_0237088792_en-us_topic_0059777801_lc1ce55d572e44beea3e47b1b427fae3e) to distribute static configuration files to their corresponding hosts. If **--distribute** is specified, the static configuration files are automatically distributed and you do not need to perform [3](#en-us_topic_0237088792_en-us_topic_0059777801_lc1ce55d572e44beea3e47b1b427fae3e). 3. (Optional) Replace the damaged static configuration files of the three hosts in the **/opt/gaussdb/app/bin** directory. Take one host as an example: ``` mv /opt/huawei/wisequery/script/static_config_files/cluster_static_config_SIA1000056771 /opt/gaussdb/app/bin/cluster_static_config ``` ## Examples Run the following commands on any of the hosts in openGauss to generate configuration files: ``` gs_om -t generateconf -X /opt/software/openGauss/clusterconfig.xml --distribute Generating static configuration files for all nodes. Creating temp directory to store static configuration files. Successfully created the temp directory. Generating static configuration files. Successfully generated static configuration files. Static configuration files for all nodes are saved in /opt/huawei/Bigdata/mppdb/wisequery/script/static_config_files. Distributing static configuration files to all nodes. Successfully distributed static configuration files. ``` Open the generated configuration file directory that contains three new files. ``` cd /opt/huawei/Bigdata/mppdb/wisequery/script/static_config_files ll total 456 -rwxr-xr-x 1 omm dbgrp 155648 2016-07-13 15:51 cluster_static_config_plat1 -rwxr-xr-x 1 omm dbgrp 155648 2016-07-13 15:51 cluster_static_config_plat2 -rwxr-xr-x 1 omm dbgrp 155648 2016-07-13 15:51 cluster_static_config_plat3 ``` --- --- url: /en/docs/latest-lite/brief_tutorial/basic_concepts.md --- # Basic Concepts openGauss is a relational database management system (RDBMS). A relational database organizes data using a relational model, that is, data is stored in rows and columns. openGauss database nodes store data on disks. Logically, objects on a database node include tablespaces, databases, datafile segments, tables, and blocks. [Figure 1](#en-us_topic_0283136742_en-us_topic_0237120245_en-us_topic_0059779316_fb2fa3b3cc8824dea95318504e0537913) shows the relationships between objects. **Figure 1** Database logical architecture\ ![](figures/database-logical-architecture.png) ## Database A collection of data that is stored together and can be accessed, managed, and updated. Databases manage various data objects and are isolated from each other. While creating a database, you can specify a tablespace. If you do not specify it, the object will be saved to the **PG\_DEFAULT** tablespace by default. Objects managed by a database can be distributed to multiple tablespaces. ## Block A block is the basic unit of database management. Its default size is 8 KB. ## Row A row (tuple or record) is a set of related data, for example, a piece of data subscribed by a user. ## Column Each column is referred to as a field. The value in each field (column) represents a data type. For example, if a table contains three fields **Name**, **City**, and **State**, it has three columns **Name**, **City**, and **State**. In every row of the table, the **Name** column contains a name, the **City** column contains a city, and the **State** column contains a state. ## Table A table consists of rows and columns. It is an object used to store data in a database and is the basis of the entire database system. Each table belongs to only one database and one tablespace. The datafile segments storing the data of the same table must be in the same tablespace. ## Datafile Segment Generally, each table corresponds to only one datafile segment. A table containing more than 1 GB of data is stored in multiple datafile segments. ## Tablespace In openGauss, a tablespace is a directory that provides an abstract layer between physical data and logical data. It allocates storage space for all database objects to store the physical files of the databases. Files are physically isolated using tablespaces and managed by a file system. Multiple tablespaces can exist. When you create an object, you can specify which tablespace it belongs to. ## Schema Collection of database objects, including logical structures, such as tables, views, sequences, stored procedures, synonyms, indexes, and database links. ## Transaction It is a logical unit of work performed within a DBMS, and treated in a coherent and reliable way independent of other transactions. In a relational database, a transaction can be a SQL statement, a set of SQL statements, or a program. In addition, a transaction is the basic unit for recovery and concurrency control. It must have the ACID feature. * Atomicity: Operations in a transaction must be either all performed or none performed because a transaction is an integral unit of work. * Consistency: A transaction must change a database from one consistent state to another consistent state. Consistency is closely related to atomicity. * Isolation: The execution of a transaction cannot be interfered by other transactions. It means that operations and data used in a transaction are isolated from those in other concurrent transactions. Concurrent transactions are independent of each other. * Durability or Permanence: Once a transaction is committed, the data in the database is changed permanently. Subsequent operations or faults should not have any impact on them. --- --- url: /en/docs/latest/sql_reference/brief_tutorial/basic_concepts.md --- # Basic Concepts openGauss is a relational database management system (RDBMS). A relational database organizes data using a relational model, that is, data is stored in rows and columns. openGauss database nodes store data on disks. Logically, objects on a database node include tablespaces, databases, datafile segments, tables, and blocks. [Figure 1](#en-us_topic_0283136742_en-us_topic_0237120245_en-us_topic_0059779316_fb2fa3b3cc8824dea95318504e0537913) shows the relationships between objects. **Figure 1** Database logical architecture\ ## Database A collection of data that is stored together and can be accessed, managed, and updated. Databases manage various data objects and are isolated from each other. While creating a database, you can specify a tablespace. If you do not specify it, the object will be saved to the **PG\_DEFAULT** tablespace by default. Objects managed by a database can be distributed to multiple tablespaces. ## Block A block is the basic unit of database management. Its default size is 8 KB. ## Row A row (tuple or record) is a set of related data, for example, a piece of data subscribed by a user. ## Column Each column is referred to as a field. The value in each field (column) represents a data type. For example, if a table contains three fields **Name**, **City**, and **State**, it has three columns **Name**, **City**, and **State**. In every row of the table, the **Name** column contains a name, the **City** column contains a city, and the **State** column contains a state. ## Table A table consists of rows and columns. It is an object used to store data in a database and is the basis of the entire database system. Each table belongs to only one database and one tablespace. The datafile segments storing the data of the same table must be in the same tablespace. ## Datafile Segment Generally, each table corresponds to only one datafile segment. A table containing more than 1 GB of data is stored in multiple datafile segments. ## Tablespace In openGauss, a tablespace is a directory that provides an abstract layer between physical data and logical data. It allocates storage space for all database objects to store the physical files of the databases. Files are physically isolated using tablespaces and managed by a file system. Multiple tablespaces can exist. When you create an object, you can specify which tablespace it belongs to. ## Schema Collection of database objects, including logical structures, such as tables, views, sequences, stored procedures, synonyms, indexes, and database links. ## Transaction It is a logical unit of work performed within a DBMS, and treated in a coherent and reliable way independent of other transactions. In a relational database, a transaction can be a SQL statement, a set of SQL statements, or a program. In addition, a transaction is the basic unit for recovery and concurrency control. It must have the ACID feature. * Atomicity: Operations in a transaction must be either all performed or none performed because a transaction is an integral unit of work. * Consistency: A transaction must change a database from one consistent state to another consistent state. Consistency is closely related to atomicity. * Isolation: The execution of a transaction cannot be interfered by other transactions. It means that operations and data used in a transaction are isolated from those in other concurrent transactions. Concurrent transactions are independent of each other. * Durability or Permanence: Once a transaction is committed, the data in the database is changed permanently. Subsequent operations or faults should not have any impact on them. --- --- url: /en/docs/latest-lite/about_opengauss/basic_features.md --- # Basic Features ## Basic Features ### Context openGauss is a standalone database. It has the basic features of relational databases as well as enhanced features. ### Features * Standard SQLs Supports SQL92, SQL99, SQL2003, and SQL2011 standards, GBK, GB18030, UTF-8, SQL ASCII, and Latin-1 character sets, SQL standard functions and analytic functions, and stored procedures. * Database storage management Supports tablespaces where different tables can be stored in different locations. * Primary/standby deployment Supports the ACID properties, single-node fault recoveries, primary/standby data synchronization, and primary/standby switchover. * APIs Supports standard JDBC 4.0 and ODBC 3.5. * Management tools Provides installation and deployment tools, instance start and stop tools, and backup and restoration tools. * Security management Supports SSL network connections, user permission management, password management, security auditing, and other functions, to ensure data security at the management, application, system, and network layers. ## Enhanced Features ### Data Partitioning Data partitioning is a general function for most database products. In the openGauss, data is partitioned horizontally with a user-specified policy. This operation splits a table into multiple partitions that are not overlapped. openGauss supports: * Range partitioning. It can divide a record, which is to be inserted into a table, into multiple ranges using one or more columns and create a partition for each range to store data. Partition ranges do not overlap. * List partitioning. It divides the key values in the records to be inserted into a table into multiple lists (the lists do not overlap in different partitions) based on a column of the table, and then creates a partition for each list to store the corresponding data. * Hash partitioning. It uses the internal hash algorithm to divide records to be inserted into a table into partitions based on a column of the table. If you specify the **PARTITION** parameter when running the **CREATE TABLE** statement, data in the table will be partitioned. For example, [Table 1](#en-us_topic_0283136537_en-us_topic_0237080621_en-us_topic_0231764089_en-us_topic_0059777656_t77b9e09809f742f1aaadea05d041bc23) uses an xDR scenario to describe the benefits provided after data is partitioned based on time fragments. **Table 1** Partitioning benefits Data partitioning provides the following benefits: * **Improve manageability:** Tables and indexes are divided into smaller and more manageable units. In this way, data management can be performed by partitions. Database administrators will perform maintenance in the designated area of the table. * **Improve deleting performance:** Delete an entire partition rather than delete data by row, which is very efficient. The **DROP TABLE** syntax can be used to delete both ordinary tables and partitioned tables. * **Improve query performance:** Restrict the volume of data to be checked or operated to facilitate query. With partition pruning, also known as partition elimination, openGauss filters out unexpected partitions and scans only the remaining partitions. Partition pruning greatly improves query performance. * **Partition-wise Join**: Partitioning can also improve the performance of multi-table joins by using a technique known as partition-wise join. Partition-wise joins can be applied when two tables are joined and at least one of these tables is partitioned using a join key. Partition-wise joins break a large join into smaller joins of "identical" datasets. "Identical" here is defined as covering the same set of partitioning key values on both sides of the join, ensuring that only a join of these 'identical' datasets will produce a result without considering other datasets. List partitions and hash partitions are not supported currently. ### Vectorized Executor and Hybrid Row-Column Storage Engine In a wide table containing a huge amount of data, a query usually only involves certain columns. In this case, the query performance of the row-store engine is poor. For example, a single table containing the data of a meteorological agency has 200 to 800 columns. Among these columns, only 10 are frequently accessed. In this case, the vectorized execution technology and column-store engine can significantly improve performance by saving storage space. * Vectorized execution [Figure 1](#en-us_topic_0283136537_en-us_topic_0237080624_en-us_topic_0231764690_en-us_topic_0059777898_f9d90aebe179a40759039d0263492489d) shows a standard iterator module. Control flow travels in the downlink direction (shown as solid lines in the following figure) and data flow in the uplink direction (shown as dotted lines in the following figure). The upper-layer node invokes the lower-layer node to request data and the lower-layer node only returns one tuple to the upper-layer node at a time. By contrast, the vectorized executor returns a batch of tuples at a time, which significantly improves performance using column store. **Figure 1** Vectorized executor ![](figures/向量化执行引擎.png) * Hybrid row-column storage engine openGauss supports both the row-store and column-store models. Users can choose a row-store or column-store table based on their needs. Generally, column store is applicable to OLAP service scenarios (The range statistics query and batch import operations are frequent. The update, deletion, point query, and point insertion operations are infrequent. The table contains many columns, that is, a wide table. Only a few columns are involved in the query.) The row store is applicable to OLTP service scenarios (The query, insert, delete, and update operations are frequent. The range statistics query and batch import operations are infrequent. The number of table columns is small. Most columns are queried.) The hybrid row-column storage engine achieves higher data compression ratio (column store), index performance (column store), and point update and point query (row store) performance, as shown in [Figure 2](#en-us_topic_0283136537_en-us_topic_0237080624_en-us_topic_0231764690_en-us_topic_0059777898_fbb2af39ce12a419cb437829aaf1cf4fb). **Figure 2** Hybrid row-column storage engine ![](figures/opengauss行列混存引擎.png) The restrictions of the column store engine are as follows: * For DDL statements, only CREATE TABLE, DROP TABLE, and TRUNCATE TABLE are supported. Partition management using DDL statements (such as **ADD PARTITION**, **DROP PARTITION**,**MERGE PARTITION**,**and EXCHANGE**) is supported. The **CREATE TABLE LIKE** statement is supported. The **ALTER TABLE** statement is partially supported. Other DDL statements are not supported. * For DML statements, UPDATE, COPY, BULKLOAD, and DELETE are supported. * Triggers and primary foreign keys are not supported. * Psort index, B-tree index, and GIN index are supported. For details, see [CREATE INDEX](../sql_reference/create_index.md). * Data compression in column store Inactive and earlier data can be compressed to free up space, reducing procurement and O\&M costs. In openGauss, data can be compressed using delta encoding, dictionary coder, RLE, LZ4, and ZLIB algorithms. The system automatically selects a compression algorithm based on data characteristics. The average compression ratio is 7:1. Compressed data can be directly accessed and is transparent to services. This greatly reduces the preparation time before accessing historical data. ### Fusion Storage Engine The fusion engine architecture supports the pluggable storage engine architecture. The in-place update storage engine is added. The indexing multiversion supports adding transaction information to indexes. The Xlog lockless update greatly improves the Xlog write efficiency. The parallel page playback improves the playback efficiency of the standby node, and the enterprise-level flashback provides a stable query state for users. * In-place update storage engine The in-place update storage engine solves the problems of space expansion and large tuples of the Append update storage engine. The design of efficient rollback segments is the basis of the in-place update storage engine. * Indexing multiversion **Figure 3** Comparison between UBTree and BTree searching and updating\ ![](figures/comparison-between-ubtree-and-btree-searching-and-updating.png) UBtree can check multiversion concurrency control (MVCC) visibility at the index layer by maintaining version information on tuples on the index page. In addition, the UBtree can independently determine whether the index tuple is dead based on the version information, so that the in-place update engine can implement page-level space cleanup for the data table and index table, and build an independent garbage collection mechanism independent of AutoVacuum. * Xlog lockless update **Figure 4** Xlog lockless design\ ![](figures/xlog-lockless-design.png) This feature optimizes the WalInsertLock mechanism by using log sequence numbers (LSNs) and log record counts (LRCs) to record the copy progress of each backend and canceling the WalInsertLock mechanism. The backend can directly copy logs to the WalBuffer without contending for the WalInsertLock. In addition, a dedicated WALWriter thread is used to write logs, and the backend thread does not need to ensure the Xlog flushing. After the preceding optimization, the WalInsertLock contention and WalWriter dedicated disk write threads are canceled. The system performance can be further improved while the original Xlog function remains unchanged. * Parallel page playback This feature optimizes the Ustore in-place update WALs and Ustore DML operation parallel playback and distribution. Prefixes and suffixes are used to reduce the update WALs. The playback thread is divided into multiple types to solve the problem that most Ustore DML WALs are replayed on multiple pages. In addition, the Ustore data page playback is distributed based on blkno to improve the degree of parallel playback. * Enterprise-class feature flashback Flashback is a part of the database recovery technology. It enables the DBA to selectively and efficiently cancel the impact of a committed transaction and restore data from incorrect manual operations. Before the flashback technology is used, the committed database modification can be retrieved only by means of restoring backup and PITR. The restoration takes several minutes or even hours. After the flashback technology is used, it takes only seconds to restore the submitted data before the database is modified. The restoration time is irrelevant to the database size. This feature supports the following flashback modes: * Flashback query: You can query a snapshot of a table at a certain time point in the past. This feature can be used to view and logically rebuild damaged data that is accidentally deleted or modified. The flashback query is based on the MVCC mechanism. You can retrieve and query the old version to obtain the data of the specified old version. * Flashback table: You can restore a table to a specific point in time. When only one table or a group of tables are logically damaged instead of the entire database, this feature can be used to quickly restore the table data. Based on the MVCC mechanism, the flashback table deletes incremental data at a specified time point and after the specified time point and retrieves the data deleted at the specified time point and the current time point to restore table-level data. * Flashback drop: You can restore tables that are deleted by mistake and their auxiliary structures, such as indexes and table constraints, from the recycle bin. Flashback drop is based on the recycle bin mechanism. You can restore physical table files recorded in the recycle bin to restore dropped tables. * Flashback truncate: You can restore tables that are truncated by mistake and restore the physical data of the truncated tables and indexes from the recycle bin. Flashback truncate is based on the recycle bin mechanism. You can restore physical table files recorded in the recycle bin to restore truncated tables. ### High Availability (HA) Transaction Processing openGauss manages transactions and guarantees the ACID properties. openGauss provides a primary/standby HA mechanism to reduce the service interruption time when the primary node is faulty. It protects key user programs and continuously provides external services, minimizing the impact of hardware, software, and human faults on services to ensure service continuity. **Fault recovery** Node faults can be recovered and the ACID properties still exist after the recovery. openGauss ensures zero data loss after a node is recovered from a fault or restarted. **Transaction management** * Support transaction blocks. The **Start Transaction** command can be used to start a transaction block explicitly. * Support single-statement transactions. If explicit startup is not performed, a single statement is processed as a transaction. ### High Concurrency and High Performance openGauss supports 10,000 concurrent connections through server thread pools. It supports thread nucleophilicity and millions of tpmC using the NUMA-based kernel data structure, manages TB-level large memory buffers through efficient hot and cold data elimination, achieves multi-version access without read/write blocks using CSN-based snapshots, and avoids performance fluctuation caused by full-page writes using incremental checkpoints. ### SQL Self-Diagnosis To locate performance issues of a query, you can use **EXPLAIN PERFORMANCE** to query its execution plan. However, this method produces many logs, requires to modify service logic, and depends on expertise to locate problems. SQL self-diagnosis enables users to locate performance issues more efficiently. Before running a job, set the GUC parameters **resource\_track\_level** and **resource\_track\_cost**, and obtain the possible performance issues after job execution by checking the related system view. The system view describes the possible causes of performance issues. To optimize low-performance jobs, see [Optimizing SQL Self-Diagnosis](https://docs.opengauss.org/en/docs/latest-lite/performance_tuning_guide/optimizing_sql_self_diagnosis.html). SQL self-diagnosis helps users locate and optimize performance issues without affecting operations or modifying service logic. ### Multiple Storage Engines openGauss is based on the unified transaction mechanism, log system, concurrency control system, metadata information, and cache management, provides Table Access Method API, and supports different storage engines. Currently, the Astore and Ustore storage engines are supported. ### Primary/Standby Deployment The primary/standby deployment mode supports synchronous and asynchronous replication. Applications are deployed based on service scenarios. For synchronous replication, one primary node and two standby nodes are deployed. This ensures reliability but affects performance. For asynchronous replication, one primary node and one standby node are deployed. This has little impact on performance, but data may be lost when exceptions occur. openGauss supports automatic recovery of damaged pages. When a page on the primary node is damaged, the damaged page can be automatically recovered on the standby node. Besides, openGauss supports concurrent log recovery on the standby node to minimize the service unavailability time when the primary node is down. In addition, in primary/standby deployment mode, if the read function of the standby node is enabled, the standby node supports read operations instead of write operations (such as table creation, data insertion, and data deletion), reducing the pressure on the primary node. > \[!NOTE]NOTE > In the current Lite scenario, openGauss does not support deployment with one primary and two standbys. ### Logical Log Replication In logical replication, the primary database is called the source database, and the standby database is called the target database. The source database parses the WAL file based on the specified logical parsing rules and parses the DML operations into certain logical change information (standard SQL statements). The source database sends standard SQL statements to the target database. After receiving the SQL statements, the target database applies them to implement data synchronization. Logical replication involves only DML operations. Logical replication can implement cross-version replication, heterogeneous database replication, dual-write database replication, and table-level replication. ### Automatic WDR Performance Analysis Report Periodically and proactively analyzes run logs and WDR reports (which are automatically generated in the background and can be triggered by key indicator thresholds such as the CPU usage, memory usage, and long SQL statement proportions) and generates reports in HTML and PDF formats. The performance report can be automatically generated. The WDR generates a performance report between two different time points based on the system performance snapshot data at two different time points. The report is used to diagnose database kernel performance faults. The WDR module consists of the following two components: * Snapshot: The performance snapshot can be configured to collect a certain amount of performance data from the kernel at a specified interval and store the data in the user tablespace. Any snapshot can be used as a performance baseline for comparison with other snapshots. * WDR Reporter: This tool analyzes the overall system performance based on two snapshots, calculates the changes of more specific performance indicators between the two time points, and generates summarized and detailed performance data. ### Incremental Backup and Restoration (beta) Supports full backup and incremental backup of the database, manages backup data, and views the backup status. Supports combination of incremental backups and deletion of expired backups. The database server dynamically tracks page changes, and when a relational page is updated, the page is marked for backup. The incremental backup function requires that the GUC parameter enable\_cbm\_tracking be enabled to allow the server to track the modification page. ### Point-In-Time Recovery (PITR) PITR uses basic hot backup, write-ahead logs (WALs), and archived WALs for backup and recovery. When replaying a WAL record, you can stop at any point in time, so that there is a snapshot of the consistent database at any point in time. That is, you can restore the database to the state at any time since the backup starts. During recovery, you can specify a recovery stop point with a terminal ID (TID), time, and license serial number (LSN). ### Generated Columns Generated columns are calculated based on other columns in the table. Column generation is a standard SQL feature. Columns generated by SQL statements are automatically calculated when data is inserted or updated. Similar to common columns, they also occupy storage space. ### Hash Index openGauss supports the hash index. The performance of long-index column equality query is better than that of B-tree. Lock management is optimized to provide higher concurrency. Xlog protection is provided to prevent data loss. ### State Cryptography Administration (SCA) Algorithms User authentication modes (gsql, JDBC, and ODBC) support the SM3 algorithm. APIs are provided for the SM4 algorithm to encrypt and decrypt data, hardening database security. ### Plug-in-based Architecture Based on gray upgrade, provides a kind of function which can upgrade specified nodes. Without interrupting services, upgrade specified nodes and then upgrade the remaining nodes. ### Rolling upgrade The syntax and semantics of the SQL engine are decoupled to implement plug-ins for the syntax and semantics layers of openGauss and decouple the syntax module of heterogeneous databases from the openGauss Kernel. Operator plug-ins are supported, implementing plug-ins for specific operators from plan creation, optimization, to execution. ### Others * UPSERT supports subqueries. A subquery expression can be used in the UPSERT statement to assign a value, and EXCLUDED can be used in the subquery expression to reference conflicting rows. * Column-store tables support unique indexes. You can create the unique indexes based on CBTree, the primary keys, and the unique key constraints in a column-store table, preventing duplicate data in a table and extending the application scenarios of column-store tables. * The jsonb data type is supported. The JSONB data type is supported to efficiently operate JSON data. Various operators and operation functions of JSON and JSONB types are supported. Indexes can be created on JSONB to meet the JSON application and search scenarios. * The UCE fault detection and response are supported. When a memory UCE error occurs, the SIGBUS signal sent by the system is detected, and the corresponding logs are displayed and the openGauss database state is changed according to the carried physical address. Then, the corresponding database process exits. * Monitoring and automatic elimination of unique SQL statements are supported. openGauss supports automatic elimination of unique SQL statements. It uses the LRU algorithm to automatically eliminate old unique SQL information based on the update time, ensuring that the latest statistics can be continuously recorded and improving database O\&M. * The gs\_cgroup load management is supported. gs\_cgroup is a load management tool. It creates and manages Cgroups in the database kernel and sets system resource quotas and resource limits to manage the resource usage and priorities of users and services, fully utilizing machine resources. --- --- url: /en/docs/latest/about_opengauss/basic_features.md --- # Basic Features ## Basic Features ### Context openGauss is a standalone database. It has the basic features of relational databases as well as enhanced features. ### Features * Standard SQLs Supports SQL92, SQL99, SQL2003, and SQL2011 standards, GBK, GB18030, UTF-8, SQL ASCII, and Latin-1 character sets, SQL standard functions and analytic functions, and stored procedures. * Database storage management Supports tablespaces where different tables can be stored in different locations. * Primary/standby deployment Supports the ACID properties, single-node fault recoveries, primary/standby data synchronization, and primary/standby switchover. * APIs Supports standard JDBC 4.0 and ODBC 3.5. * Management tools Provides installation and deployment tools, instance start and stop tools, and backup and restoration tools. * Security management Supports SSL network connections, user permission management, password management, security auditing, and other functions, to ensure data security at the management, application, system, and network layers. ## Enhanced Features ### Data Partitioning Data partitioning is a general function for most database products. In the openGauss, data is partitioned horizontally with a user-specified policy. This operation splits a table into multiple partitions that are not overlapped. openGauss supports: * Range partitioning. It can divide a record, which is to be inserted into a table, into multiple ranges using one or more columns and create a partition for each range to store data. Partition ranges do not overlap. * List partitioning. It divides the key values in the records to be inserted into a table into multiple lists (the lists do not overlap in different partitions) based on a column of the table, and then creates a partition for each list to store the corresponding data. * Hash partitioning. It uses the internal hash algorithm to divide records to be inserted into a table into partitions based on a column of the table. If you specify the **PARTITION** parameter when running the **CREATE TABLE** statement, data in the table will be partitioned. For example, [Table 1](#en-us_topic_0283136537_en-us_topic_0237080621_en-us_topic_0231764089_en-us_topic_0059777656_t77b9e09809f742f1aaadea05d041bc23) uses an xDR scenario to describe the benefits provided after data is partitioned based on time fragments. **Table 1** Partitioning benefits Data partitioning provides the following benefits: * **Improve manageability:** Tables and indexes are divided into smaller and more manageable units. In this way, data management can be performed by partitions. Database administrators will perform maintenance in the designated area of the table. * **Improve deleting performance:** Delete an entire partition rather than delete data by row, which is very efficient. The **DROP TABLE** syntax can be used to delete both ordinary tables and partitioned tables. * **Improve query performance:** Restrict the volume of data to be checked or operated to facilitate query. With partition pruning, also known as partition elimination, openGauss filters out unexpected partitions and scans only the remaining partitions. Partition pruning greatly improves query performance. * **Partition-wise Join**: Partitioning can also improve the performance of multi-table joins by using a technique known as partition-wise join. Partition-wise joins can be applied when two tables are joined and at least one of these tables is partitioned using a join key. Partition-wise joins break a large join into smaller joins of "identical" datasets. "Identical" here is defined as covering the same set of partitioning key values on both sides of the join, ensuring that only a join of these 'identical' datasets will produce a result without considering other datasets. List partitions and hash partitions are not supported currently. ### Vectorized Executor and Hybrid Row-Column Storage Engine In a wide table containing a huge amount of data, a query usually only involves certain columns. In this case, the query performance of the row-store engine is poor. For example, a single table containing the data of a meteorological agency has 200 to 800 columns. Among these columns, only 10 are frequently accessed. In this case, the vectorized execution technology and column-store engine can significantly improve performance by saving storage space. * Vectorized execution [Figure 1](#en-us_topic_0283136537_en-us_topic_0237080624_en-us_topic_0231764690_en-us_topic_0059777898_f9d90aebe179a40759039d0263492489d) shows a standard iterator module. Control flow travels in the downlink direction (shown as solid lines in the following figure) and data flow in the uplink direction (shown as dotted lines in the following figure). The upper-layer node invokes the lower-layer node to request data and the lower-layer node only returns one tuple to the upper-layer node at a time. By contrast, the vectorized executor returns a batch of tuples at a time, which significantly improves performance using column store. **Figure 1** Vectorized executor ![](figures/向量化执行引擎.png) * Hybrid row-column storage engine openGauss supports both the row-store and column-store models. Users can choose a row-store or column-store table based on their needs. Generally, column store is applicable to OLAP service scenarios (The range statistics query and batch import operations are frequent. The update, deletion, point query, and point insertion operations are infrequent. The table contains many columns, that is, a wide table. Only a few columns are involved in the query.) The row store is applicable to OLTP service scenarios (The query, insert, delete, and update operations are frequent. The range statistics query and batch import operations are infrequent. The number of table columns is small. Most columns are queried.) The hybrid row-column storage engine achieves higher data compression ratio (column store), index performance (column store), and point update and point query (row store) performance, as shown in [Figure 2](#en-us_topic_0283136537_en-us_topic_0237080624_en-us_topic_0231764690_en-us_topic_0059777898_fbb2af39ce12a419cb437829aaf1cf4fb). **Figure 2** Hybrid row-column storage engine ![](figures/opengauss行列混存引擎.png) The restrictions of the column store engine are as follows: * For DDL statements, only CREATE TABLE, DROP TABLE, and TRUNCATE TABLE are supported. Partition management using DDL statements (such as **ADD PARTITION**, **DROP PARTITION** , **MERGE PARTITION** ,and **EXCHANGE** ) is supported. The **CREATE TABLE LIKE** statement is supported. The **ALTER TABLE** statement is partially supported. Other DDL statements are not supported. * For DML statements, UPDATE, COPY, BULKLOAD, and DELETE are supported. * Triggers and primary foreign keys are not supported. * Psort index, B-tree index, and GIN index are supported. For details, see [Optimizing SQL Self-Diagnosis](https://docs.opengauss.org/en/docs/latest/performance_tuning_guide/optimizing_sql_self_diagnosis.html). * Data compression in column store Inactive and earlier data can be compressed to free up space, reducing procurement and O\&M costs. In openGauss, data can be compressed using delta encoding, dictionary coder, RLE, LZ4, and ZLIB algorithms. The system automatically selects a compression algorithm based on data characteristics. The average compression ratio is 7:1. Compressed data can be directly accessed and is transparent to services. This greatly reduces the preparation time before accessing historical data. ### Fusion Storage Engine The fusion engine architecture supports the pluggable storage engine architecture. The in-place update storage engine is added. The indexing multiversion supports adding transaction information to indexes. The Xlog lockless update greatly improves the Xlog write efficiency. The parallel page playback improves the playback efficiency of the standby node, and the enterprise-level flashback provides a stable query state for users. * In-place update storage engine The in-place update storage engine solves the problems of space expansion and large tuples of the Append update storage engine. The design of efficient rollback segments is the basis of the in-place update storage engine. * Indexing multiversion **Figure 3** Comparison between UBTree and BTree searching and updating\ ![](figures/comparison-between-ubtree-and-btree-searching-and-updating.png) UBtree can check multiversion concurrency control (MVCC) visibility at the index layer by maintaining version information on tuples on the index page. In addition, the UBtree can independently determine whether the index tuple is dead based on the version information, so that the in-place update engine can implement page-level space cleanup for the data table and index table, and build an independent garbage collection mechanism independent of AutoVacuum. * Xlog lockless update **Figure 4** Xlog lockless design\ ![](figures/xlog-lockless-design.png) This feature optimizes the WalInsertLock mechanism by using log sequence numbers (LSNs) and log record counts (LRCs) to record the copy progress of each backend and canceling the WalInsertLock mechanism. The backend can directly copy logs to the WalBuffer without contending for the WalInsertLock. In addition, a dedicated WALWriter thread is used to write logs, and the backend thread does not need to ensure the Xlog flushing. After the preceding optimization, the WalInsertLock contention and WalWriter dedicated disk write threads are canceled. The system performance can be further improved while the original Xlog function remains unchanged. * Parallel page playback This feature optimizes the Ustore in-place update WALs and Ustore DML operation parallel playback and distribution. Prefixes and suffixes are used to reduce the update WALs. The playback thread is divided into multiple types to solve the problem that most Ustore DML WALs are replayed on multiple pages. In addition, the Ustore data page playback is distributed based on blkno to improve the degree of parallel playback. * Enterprise-class feature flashback Flashback is a part of the database recovery technology. It enables the DBA to selectively and efficiently cancel the impact of a committed transaction and restore data from incorrect manual operations. Before the flashback technology is used, the committed database modification can be retrieved only by means of restoring backup and PITR. The restoration takes several minutes or even hours. After the flashback technology is used, it takes only seconds to restore the submitted data before the database is modified. The restoration time is irrelevant to the database size. This feature supports the following flashback modes: * Flashback query: You can query a snapshot of a table at a certain time point in the past. This feature can be used to view and logically rebuild damaged data that is accidentally deleted or modified. The flashback query is based on the MVCC mechanism. You can retrieve and query the old version to obtain the data of the specified old version. * Flashback table: You can restore a table to a specific point in time. When only one table or a group of tables are logically damaged instead of the entire database, this feature can be used to quickly restore the table data. Based on the MVCC mechanism, the flashback table deletes incremental data at a specified time point and after the specified time point and retrieves the data deleted at the specified time point and the current time point to restore table-level data. * Flashback drop: You can restore tables that are deleted by mistake and their auxiliary structures, such as indexes and table constraints, from the recycle bin. Flashback drop is based on the recycle bin mechanism. You can restore physical table files recorded in the recycle bin to restore dropped tables. * Flashback truncate: You can restore tables that are truncated by mistake and restore the physical data of the truncated tables and indexes from the recycle bin. Flashback truncate is based on the recycle bin mechanism. You can restore physical table files recorded in the recycle bin to restore truncated tables. ### High Availability (HA) Transaction Processing openGauss manages transactions and guarantees the ACID properties. openGauss provides a primary/standby HA mechanism to reduce the service interruption time when the primary node is faulty. It protects key user programs and continuously provides external services, minimizing the impact of hardware, software, and human faults on services to ensure service continuity. **Fault recovery** Node faults can be recovered and the ACID properties still exist after the recovery. openGauss ensures zero data loss after a node is recovered from a fault or restarted. **Transaction management** * Support transaction blocks. The **Start Transaction** command can be used to start a transaction block explicitly. * Support single-statement transactions. If explicit startup is not performed, a single statement is processed as a transaction. ### High Concurrency and High Performance openGauss supports 10,000 concurrent connections through server thread pools. It supports thread nucleophilicity and millions of tpmC using the NUMA-based kernel data structure, manages TB-level large memory buffers through efficient hot and cold data elimination, achieves multi-version access without read/write blocks using CSN-based snapshots, and avoids performance fluctuation caused by full-page writes using incremental checkpoints. ### SQL Self-Diagnosis To locate performance issues of a query, you can use **EXPLAIN PERFORMANCE** to query its execution plan. However, this method produces many logs, requires to modify service logic, and depends on expertise to locate problems. SQL self-diagnosis enables users to locate performance issues more efficiently. Before running a job, set the GUC parameters **resource\_track\_level** and **resource\_track\_cost**, and obtain the possible performance issues after job execution by checking the related system view. The system view describes the possible causes of performance issues. To optimize low-performance jobs, see [Optimizing SQL Self-Diagnosis](https://docs.opengauss.org/en/docs/latest/performance_tuning_guide/optimizing_sql_self_diagnosis.html). SQL self-diagnosis helps users locate and optimize performance issues without affecting operations or modifying service logic. ### Equality Query in a Fully-encrypted Database With the rapid growth and maturity of cloud infrastructure, cloud database services are emerging one after another. Cloud databases have become an important growth point of database services in the future. Most traditional database service vendors are accelerating the provision of high-quality cloud database services. Regardless of offline or cloud database services, the core task of databases is to help users store and manage data and ensure that data is not lost, privacy is not disclosed, data is not tampered with, and services are not interrupted in complex and diversified environments. This requires a multi-level security defense mechanism of the database to defend against malicious attacks from multiple aspects. Mature security technologies are used to build a multi-level database security defense system, ensuring database security in applications. Therefore, to better protect sensitive and privacy data, especially for cloud database services, a systematic solution that can completely protect data privacy throughout the entire lifecycle on the server is urgently needed. This solution is referred to as an encrypted database solution. * Overall encrypted database solution The encrypted equality query belongs to the first phase of the encrypted database solution, but complies with the overall architecture of the encrypted database. [Figure 5](#en-us_topic_0231763017_fig141362033122319) shows the overall architecture of the encrypted database. The complete form of the encrypted database includes the cryptology solution and the combination solution of software and hardware. **Figure 5** Overall encrypted database architecture ![](figures/向量化执行引擎png-0.png) Only the software part of the overall encrypted database architecture needs to be integrated because only the software part is involved in the encrypted equality query. [Figure 6](#fig18836194875513) shows the overall implementation solution. **Figure 6** Overall encrypted equality query solution ![](figures/向量化执行引擎png-1.png) In the overall process, data is encrypted on the client and sent to the openGauss server in ciphertext. That is, an encryption and decryption module needs to be constructed on the client. The encryption and decryption module depends on the key management module which generates the root key (RK) and client master key (CMK). With the CMK, a column encryption key (CEK) can be defined through the SQL syntax. A CMK is encrypted by an RK and then saved in the key store file (KSF). Both CMK and RK are managed by the KeyTool. The CMK encrypts a CEK (using the symmetric encryption algorithm AES256 and the SM2 algorithm) and then stores it on the server. The client uses the symmetric encryption algorithms AES (including AES128 and AES256) and the SM4 algorithm to encrypt data based on the generated CEK. The encrypted data is stored on the database server. After the ciphertext calculation, the server returns the ciphertext result set, and the client decrypts the data to obtain the final result. Users can define encryption attributes for data based on service requirements. Data that does not need to be encrypted is sent to the server in the original plaintext format. After a query task is initiated, the client needs to parse the current query. If the query statement involves encrypted columns, the parameters related to encrypted columns need to be encrypted. (The encryption must be deterministic encryption. Otherwise, the corresponding query cannot be supported.) If no encrypted column is involved in the query statement, the query statement is directly sent to the server, and no additional operation is required. On the database server, data in the encrypted column is always stored in ciphertext, and the entire query is also implemented in ciphertext. In the first phase of the solution, deterministic encryption is required so that the same plaintext data can obtain the same ciphertext. In this way, equality calculation is supported. * Encrypted database flowchart **Figure 7** Encrypted database flowchart\ ![](figures/encrypted-database-flowchart.png) In the flowchart, the encrypted database allows the client to encrypt sensitive data within the client application. During the query period, the entire service data flow exists in the form of ciphertext during data processing. It has the following advantages: * Protects data privacy and security throughout the lifecycle on the cloud. * Resolves trust issues by making the public cloud, consumer cloud, and development users keep their own keys. * Enables partners to better comply with personal privacy protection laws and regulations with the help of the full encryption capability. * Usage scenarios Hybrid cloud scenario: The database client and server are deployed on the user's private network, and the client uses Huawei management and control interface. Public cloud scenario: The database client is on user's local PC, and the database server is on HUAWEI CLOUD. Public cloud services: Both the database client and server are deployed on HUAWEI CLOUD. ### Memory Table With memory tables, all data access is lockless and concurrent, optimizing data processing and meeting real-time requirements. ### Multiple Storage Engines openGauss is based on the unified transaction mechanism, log system, concurrency control system, metadata information, and cache management, provides Table Access Method API, and supports different storage engines. Currently, the Astore and Ustore storage engines are supported. ### Primary/Standby Deployment The primary/standby deployment mode supports synchronous and asynchronous replication. Applications are deployed based on service scenarios. For synchronous replication, one primary node and two standby nodes are deployed. This ensures reliability but affects performance. For asynchronous replication, one primary node and one standby node are deployed. This has little impact on performance, but data may be lost when exceptions occur. openGauss supports automatic recovery of damaged pages. When a page on the primary node is damaged, the damaged page can be automatically recovered on the standby node. Besides, openGauss supports concurrent log recovery on the standby node to minimize the service unavailability time when the primary node is down. In addition, in primary/standby deployment mode, if the read function of the standby node is enabled, the standby node supports read operations instead of write operations (such as table creation, data insertion, and data deletion), reducing the pressure on the primary node. ### AI Capabilities * Automatic parameter optimization In database scenarios, the optimal parameter value combinations of different types of jobs are different from each other. To achieve better running performance, users want to quickly optimize database parameters. People learning to adjust parameters is not cost-effective, real-time or widely available. Automatic adjustment of database parameters through machine learning helps improve the parameter adjustment efficiency and reduce the cost of parameter adjustment. Automatic parameter optimization can be performed in online or offline mode, and supports multiple algorithms, including reinforcement learning and global search. When the model is in the training phase, a new parameter value combination is obtained by using the reinforcement learning and heuristic algorithm based on an input database parameter value (including a current parameter value and a current performance parameter value of the database). The parameter adjustment of the database is obtained by mixing output results of two parts: reinforcement learning and heuristic algorithm. The output of the model is de-normalized to obtain a new parameter value. The new value is inserted into the database and the testing job is run to obtain the database performance under the current value combination, such as the execution duration and throughput. Finally, the performance is fed back to the learning model and iterated. When the model is in the testing phase, the parameter values of the current database are used as the input, including the current parameter value and current performance parameter value of the database. The optimal parameter adjustment solution in the current situation is obtained through the model. When the model is in recommendation mode, second-level parameter recommendation is directly performed based on the current workload characteristics of the user. * Index recommendation Single-query index recommendation and workload-level index recommendation are supported. During workload-level index recommendation, typical SQL statements are filtered based on the AI algorithm. For typical SQL statements, the optimal index is recommended and generated based on the semantic information of the statements and the statistics information of the database. Use the recommended indexes of all statements as the candidate index set, calculate the workload benefit of each candidate index, and recommend the index combination with the maximum benefit. * Time series prediction and exception detection Time series characteristics information on the host where the database is deployed can be collected and stored. This data can be used for time series prediction, for example, storage space prediction. In addition, exceptions can be detected based on the preceding data. In this way, potential problems can be detected in advance so as to take countermeasures. * Other autonomous O\&M services The services can be used to comprehensively monitor databases, detect exceptions, and analyze root causes of slow SQL statements in the system. * DB4AI function The function supports the native DB4AI engine and uses databases to implement SQL statements to drive AI tasks. * SQL execution time prediction In scenarios such as query performance optimization and service load analysis, users often need to predict the execution time of SQL statements. Currently, the database optimizer is based on the cost model and cannot accurately predict the execution time. This feature uses AI models to predict the execution time of historical or similar queries, meeting the SQL execution time prediction requirements. SQL execution time prediction: Coding and deep learning-based training and prediction are performed based on the collected historical performance data. Historical data is collected by the database kernel process. The kernel process sends HTTPS requests to the Python AI engine through curl to (1) configure the machine learning model (2) send training data (3) trigger model training (4) request the training process monitoring service port (5) load the model used for training (6) and use the loaded model for prediction. The data encoding phase is completed in the database to ensure that the exported data has been anonymized. In the prediction phase, after the query plan is generated, the entire plan needs to be encoded and written into a file and then sent to the Python end. The TensorFlow computational graph on the Python end needs to be loaded only once to perform highly parallel batch prediction. * Database monitoring During routine O\&M, users need to continuously monitor the database running status. However, due to the complexity of the database, it is difficult for users to efficiently extract key data. Database self-monitoring improves O\&M efficiency. You only need to pay attention to core metrics and abnormal data. 1. The transaction summary information includes the transaction numbers of Submit (commit\_counter) and Rollback (rollback\_counter) and the transaction response time. The above transactions are accumulated values since the last restart. 2. The workload SQL summary information includes the distribution of DDL, DCL, and DML in a workload and the number of SELECT, UPDATE, INSERT, and DELETE in DML. The SQL type distribution is the accumulated value since the last restart. 3. The workload SUID time summary information includes the total, average, maximum, and minimum time consumptions of SELECT, UPDATE, INSERT, and DELETE operations in a workload. 4. The SQL response time percentile information includes 80% and 95% of the SQL response time in the system in a past period of time. 5. The Waitevents summary information contains only the event waiting information on a single node and does not contain the global aggregation information. It includes the waiting status (STATUS), I/O event (IO\_EVENT), lock event (LOCK\_EVENT), Lwlock event (LWLOCK\_EVENT), successful waiting times, failed waiting times, total event waiting time on the node, minimum event waiting time, maximum event waiting time, and average event waiting time. 6. For the SQL statements that are sent to the Parser, the Parser generates the normalized Unique SQL ID and the corresponding SQL text strings, collects statistics on the time consumed by unique SQL statements in each execution phase to analyze, optimizes SQL performance based on the time distribution, and collects statistics on the time consumed by instances and sessions in each phase to help optimize the overall system performance. It also queries the number of SQL execution times, SQL kernel response time, I/O time, CPU time, network transmission time, numbers of physical and logical reads, result sets returned by Select, scanned tuples, updated rows, deleted rows, inserted rows, and newly generated (hard) reuse (soft) plans. ### Logical Log Replication In logical replication, the primary database is called the source database, and the standby database is called the target database. The source database parses the WAL file based on the specified logical parsing rules and parses the DML operations into certain logical change information (standard SQL statements). The source database sends standard SQL statements to the target database. After receiving the SQL statements, the target database applies them to implement data synchronization. Logical replication involves only DML operations. Logical replication can implement cross-version replication, heterogeneous database replication, dual-write database replication, and table-level replication. ### Automatic WDR Performance Analysis Report Periodically and proactively analyzes run logs and WDR reports (which are automatically generated in the background and can be triggered by key indicator thresholds such as the CPU usage, memory usage, and long SQL statement proportions) and generates reports in HTML and PDF formats. The performance report can be automatically generated. The WDR generates a performance report between two different time points based on the system performance snapshot data at two different time points. The report is used to diagnose database kernel performance faults. The WDR module consists of the following two components: * Snapshot: The performance snapshot can be configured to collect a certain amount of performance data from the kernel at a specified interval and store the data in the user tablespace. Any snapshot can be used as a performance baseline for comparison with other snapshots. * WDR Reporter: This tool analyzes the overall system performance based on two snapshots, calculates the changes of more specific performance indicators between the two time points, and generates summarized and detailed performance data. ### Incremental Backup and Restoration (beta) Supports full backup and incremental backup of the database, manages backup data, and views the backup status. Supports combination of incremental backups and deletion of expired backups. The database server dynamically tracks page changes, and when a relational page is updated, the page is marked for backup. The incremental backup function requires that the GUC parameter enable\_cbm\_tracking be enabled to allow the server to track the modification page. ### Point-In-Time Recovery (PITR) PITR uses basic hot backup, write-ahead logs (WALs), and archived WALs for backup and recovery. When replaying a WAL record, you can stop at any point in time, so that there is a snapshot of the consistent database at any point in time. That is, you can restore the database to the state at any time since the backup starts. During recovery, you can specify a recovery stop point with a terminal ID (TID), time, and license serial number (LSN). ### Two-City Three-DC DR Two-city three-DC indicates that the three DCs (production center, intra-city DR center, and remote DR center) are deployed in two cities. In recent years, natural disasters have occurred frequently at home and abroad. The two-city three-DC DR solution comes into being with the combination of two intra-city DCs and remote DR DCs. This solution features high availability and disaster backup capabilities. The two intra-city DCs are two data centers that can carry critical applications independently. They have similar data processing capabilities and can synchronize data in real time through high-speed links. Under normal circumstances, the two DCs manage services and system operation together and can be switched over. When disaster occurs, services can be switched over to the DR DC with almost no data loss, ensuring service continuity. Compared with the remote DR DC, two intra-city DCs have lower investment cost, faster building speed, easier operation and maintenance, and higher reliability. A remote DR DC is deployed in a different city and is used to back up data of the two DCs. When faults occur in the two DCs, the remote DR DC can recover services from backup data. [Figure 8](#fig104604146484) shows the openGauss two-city three-DC DR architecture. Two-city three-DC DR includes the OBS-based remote DR solution and streaming replication-based remote DR solution. openGauss 3.1.0 and later versions provide the streaming replication-based remote DR solution. After DR is enabled, the following functions can be implemented: * Full replication: Configure the DR database instance information for the primary database instance and wait for the DR database instance to be connected for full replication. * Incremental replication: After the DR database instance is fully built, streaming replication is established between the DR database instance and the primary database instance for incremental log replication. **Figure 8** openGauss two-city three-DC DR architecture ![](figures/openGauss两地三中心容灾架构示意图.png) ### Generated Columns Generated columns are calculated based on other columns in the table. Column generation is a standard SQL feature. Columns generated by SQL statements are automatically calculated when data is inserted or updated. Similar to common columns, they also occupy storage space. ### Hash Index openGauss supports the hash index. The performance of long-index column equality query is better than that of B-tree. Lock management is optimized to provide higher concurrency. Xlog protection is provided to prevent data loss. ### State Cryptography Administration (SCA) Algorithms User authentication modes (gsql, JDBC, and ODBC) support the SM3 algorithm. APIs are provided for the SM4 algorithm to encrypt and decrypt data, hardening database security. ### Plug-in-based Architecture The syntax and semantics of the SQL engine are decoupled to implement plug-ins for the syntax and semantics layers of openGauss and decouple the syntax module of heterogeneous databases from the openGauss Kernel. Operator plug-ins are supported, implementing plug-ins for specific operators from plan creation, optimization, to execution. ### UWAL This feature combines the database and a Huawei-developed Unified Write-Ahead Log (UWAL) component to improve the performance of active/standby transaction submission as well as stream replication and transmission, accelerating the Write-Ahead Log (WAL) performance of the database. ### SCRLock When resource pooling is enabled, Smart Cached Remote Lock (SCRLock) can be used to provide the distributed lock capability, improving distributed lock performance. ### Others * UPSERT supports subqueries. A subquery expression can be used in the UPSERT statement to assign a value, and EXCLUDED can be used in the subquery expression to reference conflicting rows. * Column-store tables support unique indexes. You can create the unique indexes based on CBTree, the primary keys, and the unique key constraints in a column-store table, preventing duplicate data in a table and extending the application scenarios of column-store tables. * The jsonb data type is supported. The JSONB data type is supported to efficiently operate JSON data. Various operators and operation functions of JSON and JSONB types are supported. Indexes can be created on JSONB to meet the JSON application and search scenarios. * The UCE fault detection and response are supported. When a memory UCE error occurs, the SIGBUS signal sent by the system is detected, and the corresponding logs are displayed and the openGauss database state is changed according to the carried physical address. Then, the corresponding database process exits. * Monitoring and automatic elimination of unique SQL statements are supported. openGauss supports automatic elimination of unique SQL statements. It uses the LRU algorithm to automatically eliminate old unique SQL information based on the update time, ensuring that the latest statistics can be continuously recorded and improving database O\&M. * The gs\_cgroup load management is supported. gs\_cgroup is a load management tool. It creates and manages Cgroups in the database kernel and sets system resource quotas and resource limits to manage the resource usage and priorities of users and services, fully utilizing machine resources. * The standby node supports slow SQL performance diagnosis. The slow SQL diagnosis capability can also be enabled on the standby node. Similar to the primary node, the standby node can record SQL performance details in multiple dimensions and granularities, such as events and wait events. --- --- url: /en/docs/latest-lite/sql_reference/basic_statements.md --- # Basic Statements During PL/SQL programming, you may define some variables, assign values to variables, and call other stored procedures. This chapter describes basic PL/SQL statements, including variable definition statements, value assignment statements, call statements, and return statements. > \[!NOTE]NOTE > > You are advised not to call the SQL statements containing passwords in the stored procedures because authorized users may view the stored procedure file in the database and password information is leaked. If a stored procedure contains other sensitive information, permission to access this procedure must be configured, preventing information leakage. * **[Variable Definition Statements](variable_definition_statements.md)** * **[Assignment Statements](assignment_statements.md)** * **[Call Statements](call_statements.md)** --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_basic_statements.md --- # Basic Statements * **[Assignment Statements](dolphin_assignment_statements.md)** --- --- url: /en/docs/latest/sql_reference/basic_statements.md --- # Basic Statements During PL/SQL programming, you may define some variables, assign values to variables, and call other stored procedures. This chapter describes basic PL/SQL statements, including variable definition statements, value assignment statements, call statements, and return statements. > \[!NOTE]NOTE\ > You are advised not to call the SQL statements containing passwords in the stored procedures because authorized users may view the stored procedure file in the database and password information is leaked. If a stored procedure contains other sensitive information, permission to access this procedure must be configured, preventing information leakage. * **[Define Variable](variable_definition_statements.md)** * **[Assignment Statements](assignment_statements.md)** * **[Call Statement](call_statement.md)** --- --- url: /en/docs/latest-lite/sql_reference/basic_structure.md --- # Basic Structure ## Structure A PL/SQL block can contain a sub-block which can be placed in any section. The following describes the architecture of a PL/SQL block: * **DECLARE**: declares variables, types, cursors, and regional stored procedures and functions used in the PL/SQL block. ``` DECLARE ``` > \[!NOTE]NOTE > > This part is optional if no variable needs to be declared. > > * An anonymous block may omit the **DECLARE** keyword if no variable needs to be declared. > * For a stored procedure, **AS** is used, which is equivalent to **DECLARE**. The **AS** keyword must be reserved even if there is no variable declaration part. * **EXECUTION**: specifies procedure and SQL statements. It is the main part of a program. Mandatory. ``` BEGIN ``` * Exception part: processes errors. Optional. ``` EXCEPTION ``` * End ``` END; / ``` > \[!TIP]NOTICE > > You are not allowed to use consecutive tabs in the PL/SQL block because they may result in an exception when the **gsql** tool is executed with the **-r** parameter specified. ## Category PL/SQL blocks are classified into the following types: * Anonymous block: a dynamic block that can be executed only for once. For details about the syntax, see [Figure 1](anonymous_blocks.md#en-us_topic_0283137481_en-us_topic_0237122218_en-us_topic_0059779171_f19ed9f384e0646f29744951d7eec8c3b). * Subprogram: a stored procedure, function, operator, or packages stored in a database. A subprogram created in a database can be called by other programs. --- --- url: /en/docs/latest/sql_reference/basic_structure.md --- # Basic Structure ## Structure A PL/SQL block can contain a sub-block which can be placed in any section. The following describes the architecture of a PL/SQL block: * **DECLARE**: declares variables, types, cursors, and regional stored procedures and functions used in the PL/SQL block. ``` DECLARE ``` > \[!NOTE]NOTE\ > This part is optional if no variable needs to be declared. > > * An anonymous block may omit the **DECLARE** keyword if no variable needs to be declared. > * For a stored procedure, **AS** is used, which is equivalent to **DECLARE**. The **AS** keyword must be reserved even if there is no variable declaration part. * **EXECUTION**: specifies procedure and SQL statements. It is the main part of a program. Mandatory. ``` BEGIN ``` * Exception part: processes errors. Optional. ``` EXCEPTION ``` * End ``` END; / ``` > \[!TIP]NOTICE\ > You are not allowed to use consecutive tabs in the PL/SQL block because they may result in an exception when the **gsql** tool is executed with the **-r** parameter specified. ## Category PL/SQL blocks are classified into the following types: * Anonymous block: a dynamic block that can be executed only for once. For details about the syntax, see [Figure 1](./brief_tutorial/anonymous_blocks.md#en-us_topic_0283137481_en-us_topic_0237122218_en-us_topic_0059779171_f19ed9f384e0646f29744951d7eec8c3b). * Subprogram: a stored procedure, function, operator, or packages stored in a database. A subprogram created in a database can be called by other programs. --- --- url: /en/docs/latest-lite/sql_reference/basic_text_matching.md --- # Basic Text Matching Full text search in openGauss is based on the match operator **@@**, which returns **true** if a **tsvector** (document) matches a **tsquery** (query). It does not matter which data type is written first: ``` openGauss=# SELECT 'a fat cat sat on a mat and ate a fat rat'::tsvector @@ 'cat & rat'::tsquery AS RESULT; result ---------- t (1 row) ``` ``` openGauss=# SELECT 'fat & cow'::tsquery @@ 'a fat cat sat on a mat and ate a fat rat'::tsvector AS RESULT; result ---------- f (1 row) ``` As the above example suggests, a **tsquery** is not raw text, any more than a **tsvector** is. A tsquery contains search terms, which must be already-normalized lexemes, and may combine multiple terms using **AND**, **OR**, and **NOT** operators. For details, see [Text Search Types](text_search_types.md). There are functions **to\_tsquery** and **plainto\_tsquery** that are helpful in converting user-written text into a proper tsquery, for example by normalizing words appearing in the text. Similarly, **to\_tsvector** is used to parse and normalize a document string. So in practice a text search match would look more like this: ``` openGauss=# SELECT to_tsvector('fat cats ate fat rats') @@ to_tsquery('fat & rat') AS RESULT; result ---------- t (1 row) ``` Observe that this match would not succeed if written as follows: ``` openGauss=# SELECT 'fat cats ate fat rats'::tsvector @@ to_tsquery('fat & rat')AS RESULT; result ---------- f (1 row) ``` In the preceding match, no normalization of the word **rats** will occur. Therefore, **rats** does not match **rat**. The **@@** operator also supports text input, allowing explicit conversion of a text string to **tsvector** or **tsquery** to be skipped in simple cases. The variants available are: ``` tsvector @@ tsquery tsquery @@ tsvector text @@ tsquery text @@ text ``` We already saw the first two of these. The form **text @@ tsquery** is equivalent to **to\_tsvector(text) @@ tsquery**. The form **text @@ text** is equivalent to **to\_tsvector(text) @@ plainto\_tsquery(text)**. --- --- url: /en/docs/latest/sql_reference/basic_text_matching.md --- # Basic Text Matching Full text search in openGauss is based on the match operator **@@**, which returns **true** if a **tsvector** (document) matches a **tsquery** (query). It does not matter which data type is written first: ``` openGauss=# SELECT 'a fat cat sat on a mat and ate a fat rat'::tsvector @@ 'cat & rat'::tsquery AS RESULT; result ---------- t (1 row) ``` ``` openGauss=# SELECT 'fat & cow'::tsquery @@ 'a fat cat sat on a mat and ate a fat rat'::tsvector AS RESULT; result ---------- f (1 row) ``` As the above example suggests, a **tsquery** is not raw text, any more than a **tsvector** is. A tsquery contains search terms, which must be already-normalized lexemes, and may combine multiple terms using **AND**, **OR**, and **NOT** operators. For details, see [Text Search Types](text_search_types.md). There are functions **to\_tsquery** and **plainto\_tsquery** that are helpful in converting user-written text into a proper tsquery, for example by normalizing words appearing in the text. Similarly, **to\_tsvector** is used to parse and normalize a document string. So in practice a text search match would look more like this: ``` openGauss=# SELECT to_tsvector('fat cats ate fat rats') @@ to_tsquery('fat & rat') AS RESULT; result ---------- t (1 row) ``` Observe that this match would not succeed if written as follows: ``` openGauss=# SELECT 'fat cats ate fat rats'::tsvector @@ to_tsquery('fat & rat')AS RESULT; result ---------- f (1 row) ``` In the preceding match, no normalization of the word **rats** will occur. Therefore, **rats** does not match **rat**. The **@@** operator also supports text input, allowing explicit conversion of a text string to **tsvector** or **tsquery** to be skipped in simple cases. The variants available are: ``` tsvector @@ tsquery tsquery @@ tsvector text @@ tsquery text @@ text ``` We already saw the first two of these. The form **text @@ tsquery** is equivalent to **to\_tsvector(text) @@ tsquery**. The form **text @@ text** is equivalent to **to\_tsvector(text) @@ plainto\_tsquery(text)**. --- --- url: /en/docs/latest-lite/brief_tutorial/batch_processing_mode.md --- # Batch Processing Mode openGauss supports the execution of SQL statements from text files and provides the gsql tool to process SQL statements in batches. Batch processing is recommended in the following scenarios: * If you run a query repeatedly (for example, daily or weekly), you can set it as a script to avoid repeated input. * You can generate a new query from an existing similar query by copying and editing the script file. * For multi-line statements or multi-statement sequences, if an error occurs, you do not need to input all the content again. You only need to edit the script to correct the error, and then execute it again. * You can distribute the script to others so that they can also execute the statements. * When interactive use is not allowed in some cases, you must use the batch processing mode. ## Syntax ``` gsql -d dbname -p port -f filename ``` ## Parameter Description * **dbname** Specifies the name of the database to connect to. * **port** Specifies the port number of the database server. * **-f filename** Specifies that files are used as the command source instead of interactively-entered commands. This parameter specifies the path and name of the text file to be read. ## Examples 1. Create the **sql.txt** file locally. The file content is as follows: ``` CREATE TABLE customer ( c_customer_sk integer, c_customer_id char(5), c_first_name char(6), c_last_name char(8), Amount integer ); INSERT INTO customer(c_customer_sk, c_customer_id, c_first_name,Amount) VALUES (3769, 'hello', 'Grace', 1000); INSERT INTO customer (c_customer_sk, c_first_name) VALUES (3769, 'Grace'); INSERT INTO customer (c_customer_sk, c_customer_id, c_first_name) VALUES (3769, 'hello', DEFAULT); INSERT INTO customer (c_customer_sk, c_customer_id, c_first_name,Amount) VALUES (6885, 'maps', 'Joes',2200), (4321, 'tpcds', 'Lily',3000), (9527, 'world', 'James',5000); ``` 2. Execute the SQL statements in the **sql.txt** file. ``` gsql -d postgres -p 21013 -f /home/user/sql.txt ``` The result is as follows: ``` CREATE TABLE INSERT 0 1 INSERT 0 1 INSERT 0 1 INSERT 0 3 ``` --- --- url: /en/docs/latest/sql_reference/brief_tutorial/batch-processing-mode.md --- # Batch Processing Mode openGauss supports the execution of SQL statements from text files and provides the gsql tool to process SQL statements in batches. Batch processing is recommended in the following scenarios: * If you run a query repeatedly (for example, daily or weekly), you can set it as a script to avoid repeated input. * You can generate a new query from an existing similar query by copying and editing the script file. * For multi-line statements or multi-statement sequences, if an error occurs, you do not need to input all the content again. You only need to edit the script to correct the error, and then execute it again. * You can distribute the script to others so that they can also execute the statements. * When interactive use is not allowed in some cases, you must use the batch processing mode. ## Syntax ``` gsql -d dbname -p port -f filename ``` ## Parameter Description * **dbname** Specifies the name of the database to connect to. * **port** Specifies the port number of the database server. * **-f filename** Specifies that files are used as the command source instead of interactively-entered commands. This parameter specifies the path and name of the text file to be read. ## Examples 1. Create the **sql.txt** file locally. The file content is as follows: ``` CREATE TABLE customer ( c_customer_sk integer, c_customer_id char(5), c_first_name char(6), c_last_name char(8), Amount integer ); INSERT INTO customer(c_customer_sk, c_customer_id, c_first_name,Amount) VALUES (3769, 'hello', 'Grace', 1000); INSERT INTO customer (c_customer_sk, c_first_name) VALUES (3769, 'Grace'); INSERT INTO customer (c_customer_sk, c_customer_id, c_first_name) VALUES (3769, 'hello', DEFAULT); INSERT INTO customer (c_customer_sk, c_customer_id, c_first_name,Amount) VALUES (6885, 'maps', 'Joes',2200), (4321, 'tpcds', 'Lily',3000), (9527, 'world', 'James',5000); ``` 2. Execute the SQL statements in the **sql.txt** file. ``` gsql -d postgres -p 21013 -f /home/user/sql.txt ``` The result is as follows: ``` CREATE TABLE INSERT 0 1 INSERT 0 1 INSERT 0 1 INSERT 0 3 ``` --- --- url: /en/docs/latest/database_om_guide/before_you_start.md --- # Before You Start ## Overview This document describes how to upgrade and roll back, and provides frequently asked questions (FAQs) and troubleshooting methods. ## Intended Audience This document is intended for upgrade personnel, who must: * Understand version information about the current device and related NEs. * Have experience in maintaining and operating these devices. * **[Upgrade Solution](#upgrade-solution)** * **[Version Requirements Before the Upgrade](#version-requirements-before-the-upgrade)** * **[Upgrade Impact and Constraints](#upgrade-impact-and-constraints)** ## Upgrade Solution This section describes how to select an upgrade mode. You can determine whether to upgrade the existing system based on the new features provided by the openGauss and the current database status. Currently, gray upgrade are supported. The upgrade modes are classified into major version upgrade and minor version upgrade. A minor version upgrade is one during which the version number remains unchanged. Otherwise, the upgrade is a major version upgrade. View the version number of the upgrade software package in the second line of the **version.cfg** file in the upgrade package. You can view the version of the current version in the second line of the **upgrade\_version** file in *$GAUSSHOME*\*\*/bin\*\*. After you select an upgrade mode, the system automatically determines and selects a proper upgrade policy. In-place upgrade: During the upgrade, services must be stopped and all nodes must be upgraded at a time. (Starting from version 6.0.0, the In-place upgrade function will no longer be maintained, and gray upgrade will be used by default.) Gray upgrade: supports operations on all service during the upgrade and upgrades all nodes at a time. (This function is supported in versions later than openGauss 1.1.0.) Gray upgrade: based on gray upgrade, supports to upgrade the specified nodes, supports to upgrade the part of all nodes. (This function is supported in versions later than openGauss 3.1.0.) ## Version Requirements Before the Upgrade [Table 1](#table7961729) lists the version requirements for upgrading openGauss. **Table 1** Version requirements before the upgrade > \[!NOTE]NOTE > To view the current version, run the following command: > > ``` > gsql -V | --version > ``` ## Upgrade Impact and Constraints Note the following during the upgrade: * Do not perform the upgrade, scale-out, and scale-in at the same time. * Virtual IP addresses are not supported. * During the upgrade, do not change the values of **wal\_level**, **max\_connections**, **max\_prepared\_transactions**, and **max\_locks\_per\_transaction**. If the value is changed, the instance fails to be started after the rollback. * You are advised to perform upgrade when the database system is idle. You can determine the time (for example, holidays) based on experience. * Before the upgrade, ensure that the database is normal. You can run the **gs\_om -t status** command to query the database status. If the value of **cluster\_state** in the query result is **Normal**, the database is normal. * Ensure that the database mutual trust is normal before the upgrade. You can run the **ssh hostname** command on any node to connect to another node for verification. If no password is required for the interconnection between hosts, the mutual trust relationship is normal. (Generally, the mutual trust relationship is normal when the database is running properly.) * The database deployment mode (configuration files) cannot be changed before and after the upgrade. Before the upgrade, the deployment mode is verified. If the deployment mode is changed, an error is reported. * Ensure that the OS is healthy before the upgrade. You can use the **gs\_checkos** tool to check the OS status. * Services need to be stopped during in-place upgrade. Online upgrade supports all service operations. * The database is running properly and data on the primary DN has been fully synchronized to standby DNs. * Do not enable Kerberos during the upgrade. * Do not modify the **version.cfg** file decompressed from the installation package. * If the upgrade fails due to an exception, you need to manually roll back the upgrade. The next upgrade can be performed only after the rollback is successful. * If the second upgrade is successful after the rollback, the GUC parameters that are set at the uncommitted stage become invalid. * Do not manually set GUC parameters during the upgrade. * In gray upgrade, services are interrupted for less than 10s during the upgrade. * During the upgrade, ensure that the kernel version is the same as the OM version before OM operations. That is, the kernel code and OM code are from the same software package. If the preinstallation script of an upgrade package is executed but the upgrade fails or the preinstallation script of a baseline package is not executed after the upgrade rollback, the kernel code is inconsistent with the OM code. * If new fields are added to the system catalog during the upgrade, you cannot view these new fields by running the **\d** command after the upgrade. In this case, you can run the **select** command to query the new fields. * The GUC parameter **enable\_stream\_replication** must be set to **on** for the upgrade. If this parameter is set to **off**, the upgrade is not allowed. * In gray upgrade, ensure that there are less than 200 concurrent reads and 200 concurrent writes. * If the MOT is used in a version earlier than openGauss 2.0.0, the version cannot be upgraded to openGauss 2.0.0. * During the upgrade, do not install other openGauss database clusters on the current host. * During the upgrade, the template0 database is connected. An error is reported when CREATE DATABASE is executed. * The openGauss shared storage mode does not support version upgrade. * PL/Java Upgrade Constraints During the upgrade from 3.0.0 or an earlier version to 3.1.0 or a later version, if the service uses the PL/Java function and the Java environment does not exist on the host where the database instance is located, the pre-upgrade check fails. Therefore, you need to check whether the PL/Java function is used and check the current Java version in advance. The check method is as follows: 1. Run the **select count(1) from pg\_proc where prolang = 15** command as the initialized user in the database. * If the result is greater than 0, the database uses PL/Java. Check whether the Java environment exists by referring to [2](#li1343863405415). * If the result is 0, the database does not use PL/Java. The verification ends, and another verification process is performed. 2. Run the **java -version** command as the **root** user in the operating system. ``` java -version ``` * If Java exists and the version is JDK1.8 or later, the verification ends and another verification process is performed. * If Java does not exist or its version is earlier than JDK1.8, download JDK and configure Java environment variables by referring to [3](#li243351914413). 3. Download the JDK and configure Java environment variables. You can download it from the official website or visit: and configure environment variables as follows: ``` export JAVA_HOME=/xxx/jdk1.xxx export PATH=$JAVA_HOME/bin:$PATH export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar ``` > \[!NOTE]NOTE > > * Replace the JDK directory and version number with the actual ones. > * The upgrade check verifies only the Java environment variables of the node where the upgrade command is executed. If other nodes also need to use the PL/Java, download the JDK and configure the Java environment variables. Otherwise, the PL/Java cannot be used. --- --- url: /en/docs/latest/getting_started/before_you_start.md --- # Before You Start This section explains how to use databases, including creating databases and tables, inserting data to tables, and querying data in tables. ## Prerequisites openGauss is running properly. ## Procedure 1. Log in as the OS user **omm** to the primary node of the database. If you are not sure which server the primary node of the database is deployed on, see [Confirming Connection Information](confirming_connection_information.md). 2. Connect to a database. ``` gsql -d postgres -p 8000 ``` If the following information is displayed, the connection has been established: ``` gsql ((openGauss x.x.x build 50dc16a6) compiled at 2020-11-29 05:49:21 commit 1071 last mr 1373) Non-SSL connection (SSL connection is recommended when requiring high-security) Type "help" for help. openGauss=# ``` **postgres** is the database generated by default after openGauss installation is complete. You can connect to this database to create a database. **8000** is the port number of the database primary node, and you can change it as needed. You can obtain the port number by following the instructions provided in [Confirming Connection Information](confirming_connection_information.md). **Note:** * You need to use a client program or tool to connect to the database and to deliver SQL statements * **gsql** is a command-line interface (CLI) tool provided for connecting to a database. For more database connection methods, see [Connecting to a Database](odbc.md). 3. Create a database user. Only administrators that are created during openGauss installation can access the initial database by default. You can also create other database users. ``` CREATE USER joe WITH PASSWORD "xxxxxxxxx"; ``` If the following information is displayed, the user has been created: ``` CREATE ROLE ``` In this case, you have created a user named **joe**, and the user password is **xxxxxxxxx**. The following command sets the joe user as the system administrator. ``` openGauss=# GRANT ALL PRIVILEGES TO joe; ``` Use GRANT command to set related permissions. For specific operations, please refer to [GRANT](../sql_reference/grant.md). **Note**: For details about how to create users, see [Managing Users and Their Permissions](../database_administration_guide/default_permission_mechanism.md). 4. Create a database. ``` CREATE DATABASE db_tpcc OWNER joe; ``` If the following information is displayed, the database has been created: ``` CREATE DATABASE ``` After creating the **db\_tpcc** database, you can run the following command to exit the **postgres** database and log in to the **db\_tpcc** database as the user you created for more operations. You can also continue using the default **postgres** database. ``` openGauss=# \q gsql -d db_tpcc -p 8000 -U joe -W Bigdata@123 gsql ((openGauss x.x.x build 50dc16a6) compiled at 2020-11-29 05:49:21 commit 1071 last mr 1373) Non-SSL connection (SSL connection is recommended when requiring high-security) Type "help" for help. db_tpcc=> ``` Create a schema. ``` db_tpcc=> CREATE SCHEMA joe AUTHORIZATION joe; ``` If the following information is displayed, the schema has been created: ``` CREATE SCHEMA ``` **Note:** New databases are created in the **pg\_default** tablespace by default. To specify another tablespace, run the following statement: ``` openGauss=# CREATE DATABASE db_tpcc WITH TABLESPACE = hr_local; CREATE DATABASE ``` *hr\_local* indicates the tablespace name. For details about how to create a tablespace, see [Creating and Managing Tablespaces](../database_administration_guide/creating_and_managing_tablespaces.md). 5. Create a table. * Create a table named **mytable** that has only one column. The column name is **firstcol** and the column type is **integer**. ``` db_tpcc=> CREATE TABLE mytable (firstcol int); ``` ``` CREATE TABLE ``` * Run the following command to insert data to the table: ``` db_tpcc=> INSERT INTO mytable values (100); ``` If the following information is displayed, the data has been inserted: ``` INSERT 0 1 ``` * Run the following command to view data in the table: ``` db_tpcc=> SELECT * from mytable; firstcol ---------- 100 (1 row) ``` **Note:** * By default, new database objects, such as the **mytable** table, are created in the *$user* schema. For more details about schemas, see [Creating and Managing Schemas](../database_administration_guide/creating_tables.md). * For more details about how to create a table, see [Creating and Managing Tables](../database_administration_guide/creating_tables.md). * In addition to the created tables, a database contains many system catalogs. These system catalogs contain openGauss installation information and information about various queries and processes in openGauss. You can collect information about the database by querying system catalogs. For details, see [Querying System Catalogs](../database_reference/querying_a_system_catalog.md). openGauss supports row and column storage, providing high query performance for interaction analysis in complex scenarios. For details about how to select a storage model, see [Planning a Storage Model](../developer_guide/planning_a_storage_model.md). --- --- url: /en/docs/latest-lite/sql_reference/begin.md --- # BEGIN ## Function **BEGIN** may be used to initiate an anonymous block or a single transaction. This section describes the syntax of **BEGIN** used to initiate an anonymous block. For details about the **BEGIN** syntax that initiates transactions, see [START TRANSACTION](start_transaction.md). An anonymous block is a structure that can dynamically create and execute stored procedure code instead of permanently storing code as a database object in the database. ## Precautions None ## Syntax * Enable an anonymous block. ``` [DECLARE [declare_statements]] BEGIN execution_statements END; / ``` * Start a transaction. ``` BEGIN [ WORK | TRANSACTION ] [ { ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE | REPEATABLE READ } | { READ WRITE | READ ONLY } } [, ...] ]; ``` ## Parameter Description * **declare\_statements** Declares a variable, including its name and type, for example, **sales\_cnt int**. * **execution\_statements** Specifies the statement to be executed in an anonymous block. Value range: DML operations (such as select, insert, delete, and update) or registered functions in the system catalog. ## Examples None ## Helpful Links [START TRANSACTION](start_transaction.md) --- --- url: /en/docs/latest/sql_reference/begin.md --- # BEGIN ## Function **BEGIN** may be used to initiate an anonymous block or a single transaction. This section describes the syntax of **BEGIN** used to initiate an anonymous block. For details about the **BEGIN** syntax that initiates transactions, see [START TRANSACTION](start_transaction.md). An anonymous block is a structure that can dynamically create and execute stored procedure code instead of permanently storing code as a database object in the database. ## Precautions None ## Syntax * Enable an anonymous block. ``` [DECLARE [declare_statements]] BEGIN execution_statements END; / ``` * Start a transaction. ``` BEGIN [ WORK | TRANSACTION ] [ { ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE | REPEATABLE READ } | { READ WRITE | READ ONLY } } [, ...] ]; ``` ## Parameter Description * **declare\_statements** Declares a variable, including its name and type, for example, **sales\_cnt int**. * **execution\_statements** Specifies the statement to be executed in an anonymous block. Value range: DML operations (such as select, insert, delete, and update) or registered functions in the system catalog. ## Examples None ## Helpful Links [START TRANSACTION](start_transaction.md) --- --- url: /zh/docs/latest-lite/sql_reference/begin.md --- # BEGIN ## 功能描述 BEGIN可以用于开始一个匿名块,也可以用于开始一个事务。本节描述用BEGIN开始匿名块的语法,以BEGIN开始事务的语法见[START TRANSACTION](start_transaction.md)。 匿名块是能够动态地创建和执行过程代码的结构,而不需要以持久化的方式将代码作为数据库对象储存在数据库中。 ## 注意事项 * 在gsql中使用BEGIN开启事务执行SQL语句时,请勿将BEGIN与需要执行的SQL语句写在一行,因为与存储过程、匿名块等语法相关,可能会出现获取结果次数异常的情况。 ## 语法格式 * 开启匿名块 ``` [DECLARE [declare_statements]] BEGIN execution_statements END; / ``` * 开启事务 ``` BEGIN [ WORK | TRANSACTION ] [ { ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE | REPEATABLE READ } | { READ WRITE | READ ONLY } } [, ...] ]; ``` ## 参数说明 * **declare\_statements** 声明变量,包括变量名和变量类型,如“sales\_cnt int”。 * **execution\_statements** 匿名块中要执行的语句。 取值范围:DML操作(数据操纵操作:select、insert、delete、update)或系统表中已注册的函数名称。 ## 示例 无 ## 相关链接 [START TRANSACTION](start_transaction.md) --- --- url: /zh/docs/latest/sql_reference/begin.md --- # BEGIN ## 功能描述 BEGIN可以用于开始一个匿名块,也可以用于开始一个事务。本节描述用BEGIN开始匿名块的语法,以BEGIN开始事务的语法见[START TRANSACTION](start_transaction.md)。 匿名块是能够动态地创建和执行过程代码的结构,而不需要以持久化的方式将代码作为数据库对象储存在数据库中。 ## 注意事项 * 在gsql中使用BEGIN开启事务执行SQL语句时,请勿将BEGIN与需要执行的SQL语句写在一行,因为与存储过程、匿名块等语法相关,可能会出现获取结果次数异常的情况。 ## 语法格式 * 开启匿名块 ``` [DECLARE [declare_statements]] BEGIN execution_statements END; / ``` * 开启事务 ``` BEGIN [ WORK | TRANSACTION ] [ { ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE | REPEATABLE READ } | { READ WRITE | READ ONLY } } [, ...] ]; ``` ## 参数说明 * **declare\_statements** 声明变量,包括变量名和变量类型,如“sales\_cnt int”。 * **execution\_statements** 匿名块中要执行的语句。 取值范围:DML操作(数据操纵操作:select、insert、delete、update)或系统表中已注册的函数名称。 ## 示例 无。 ## 相关链接 [START TRANSACTION](start_transaction.md) --- --- url: /zh/docs/latest-lite/sql_reference/bfile_type.md --- # BFILE类型 BFILE数据类型用于存储指向外部二进制大对象(LOB)文件的指针。这些文件通常存储在数据库服务器的文件系统中,而不是直接存储在数据库内。BFILE数据类型适用于处理大型二进制文件,如图像、音频、视频等。 存储方式: bfile 不存储实际数据,仅存储指向外部文件的指针。 文件存储在数据库服务器的文件系统中,路径由 DIRECTORY 对象指定。 DIRECTORY 对象: DIRECTORY对象用于映射文件系统路径到数据库内的逻辑名称,详情[CREATE DIRECTORY](create_directory.md)。 创建 DIRECTORY 对象需要 CREATE ANY DIRECTORY 权限,普通用户需要由超级用户或具有相应管理权限的角色可以通过GRANT CREATE ANY DIRECTORY TO user 授予权限。 访问控制: 访问 bfile 数据需要适当的文件系统权限和数据库权限。 数据库用户需有 READ 权限才能访问 DIRECTORY 对象。 示例: ``` create extension gms_lob; create extension gms_output; CREATE or REPLACE DIRECTORY bfile_test_dir AS '/tmp'; create table falt_bfile (id number, bfile_name bfile); insert into falt_bfile values(1, bfilename('bfile_test_dir','regress_bfile.txt')); copy (select * from falt_bfile) to '/tmp/regress_bfile.txt'; select gms_output.enable; enable -------- (1 row) DECLARE buff raw(2000); my_bfile bfile; amount integer; f_offset integer := 1; BEGIN my_bfile := bfilename('bfile_test_dir','regress_bfile.txt'); RAISE notice 'bfile %',my_bfile; gms_lob.fileopen(my_bfile, 0); amount := gms_lob.getlength(my_bfile); RAISE notice 'amount %',amount; gms_lob.read(my_bfile, amount, f_offset, buff); RAISE notice 'buff %',buff; gms_lob.fileclose(my_bfile); RAISE notice 'bfile %',my_bfile; gms_output.put_line(CONVERT_FROM(decode(buff,'hex'), 'SQL_ASCII')); END; / NOTICE: bfile bfilename('bfile_test_dir', 'regress_bfile.txt') NOTICE: amount 51 NOTICE: buff 31096266696C656E616D6528276266696C655F746573745F646972272C2027726567726573735F6266696C652E74787427290A NOTICE: bfile bfilename('bfile_test_dir', 'regress_bfile.txt') 1 bfilename('bfile_test_dir', 'regress_bfile.txt') ``` --- --- url: /zh/docs/latest/sql_reference/bfile_type.md --- # BFILE类型 BFILE数据类型用于存储指向外部二进制大对象(LOB)文件的指针。这些文件通常存储在数据库服务器的文件系统中,而不是直接存储在数据库内。BFILE数据类型适用于处理大型二进制文件,如图像、音频、视频等。 存储方式: bfile 不存储实际数据,仅存储指向外部文件的指针。 文件存储在数据库服务器的文件系统中,路径由 DIRECTORY 对象指定。 DIRECTORY 对象: DIRECTORY对象用于映射文件系统路径到数据库内的逻辑名称,详情[CREATE DIRECTORY](create_directory.md)。 创建 DIRECTORY 对象需要 CREATE ANY DIRECTORY 权限,普通用户需要由超级用户或具有相应管理权限的角色可以通过GRANT CREATE ANY DIRECTORY TO user 授予权限。 访问控制: 访问 bfile 数据需要适当的文件系统权限和数据库权限。 数据库用户需有 READ 权限才能访问 DIRECTORY 对象。 示例: ``` create extension gms_lob; create extension gms_output; CREATE or REPLACE DIRECTORY bfile_test_dir AS '/tmp'; create table falt_bfile (id number, bfile_name bfile); insert into falt_bfile values(1, bfilename('bfile_test_dir','regress_bfile.txt')); copy (select * from falt_bfile) to '/tmp/regress_bfile.txt'; select gms_output.enable; enable -------- (1 row) DECLARE buff raw(2000); my_bfile bfile; amount integer; f_offset integer := 1; BEGIN my_bfile := bfilename('bfile_test_dir','regress_bfile.txt'); RAISE notice 'bfile %',my_bfile; gms_lob.fileopen(my_bfile, 0); amount := gms_lob.getlength(my_bfile); RAISE notice 'amount %',amount; gms_lob.read(my_bfile, amount, f_offset, buff); RAISE notice 'buff %',buff; gms_lob.fileclose(my_bfile); RAISE notice 'bfile %',my_bfile; gms_output.put_line(CONVERT_FROM(decode(buff,'hex'), 'SQL_ASCII')); END; / NOTICE: bfile bfilename('bfile_test_dir', 'regress_bfile.txt') NOTICE: amount 51 NOTICE: buff 31096266696C656E616D6528276266696C655F746573745F646972272C2027726567726573735F6266696C652E74787427290A NOTICE: bfile bfilename('bfile_test_dir', 'regress_bfile.txt') 1 bfilename('bfile_test_dir', 'regress_bfile.txt') ``` --- --- url: /zh/docs/latest-lite/sql_reference/bfile_type_function.md --- # BFILE类型函数 * bfilename(location text, filename text) 描述:根据目录对象名和文件名生成一个bfile类型对象。location的值必须是DIRECTORY对象名,filename的值为文件名。 参数类型:text 返回值类型:bfile 示例: ``` CREATE or REPLACE DIRECTORY "sdf sfa" AS '/tmp'; select bfilename('sdf sfa', 'as df .txt'); bfilename ------------------------------------ bfilename('sdf sfa', 'as df .txt') (1 row) ``` * bfilein(cstring) 描述:解析传入的字符串,生成一个bfile类型对象。传入的字符串有固定格式要求,必须是'bfilename(str1, str2)'。 参数类型:cstring 返回值类型:bfile 示例: ``` --参数格式不对 select bfilein('bfilenamell(sdf,asdf)'); ERROR: invalid input syntax for bfile: "bfilenamell(sdf,asdf)" CONTEXT: referenced column: bfilein --参数格式正确 CREATE or REPLACE DIRECTORY "bfile_test_dir" AS '/tmp'; select bfilein('bfilename(bfile_test_dir,regress_bfile.txt)'); bfilein -------------------------------------------------- bfilename('bfile_test_dir', 'regress_bfile.txt') (1 row) ``` * bfileout(bfile) 描述:将传入的bfile类型对象转换成一个cstring类型的字符串。 参数类型:bfile 返回值类型:cstring 示例: ``` CREATE or REPLACE DIRECTORY "bfile_test_dir" AS '/tmp'; select bfileout(bfilename('bfile_test_dir','regress_bfile.txt')); bfileout -------------------------------------------------- bfilename('bfile_test_dir', 'regress_bfile.txt') (1 row) ``` * bfilerecv(internal) 描述:将内部类型internal转换成一个bfile类型对象。因为internal类型是一个内部类型,无法通过外部传值,所以bfilerecv函数无法通过外部调用。 参数类型:internal 返回值类型:bfile 示例: ``` select bfilerecv(' '); ERROR: cannot accept a value of type internal LINE 1: select bfilerecv(' '); ^ ``` * bfilesend(bfile) 描述:将传入的bfile类型对象一个internal类型对象。 参数类型:bfile 返回值类型:internal 示例: ``` CREATE or REPLACE DIRECTORY "bfile_test_dir" AS '/tmp'; select bfilesend(bfilename('bfile_test_dir','regress_bfile.txt')); bfilesend -------------------------------------------------------------------------------------- \x0000000f000000126266696c655f746573745f64697200726567726573735f6266696c652e74787400 (1 row) ``` --- --- url: /zh/docs/latest/sql_reference/bfile_type_function.md --- # BFILE类型函数 * bfilename(location text, filename text) 描述:根据目录对象名和文件名生成一个bfile类型对象。location的值必须是DIRECTORY对象名,filename的值为文件名。 参数类型:text 返回值类型:bfile 示例: ``` CREATE or REPLACE DIRECTORY "sdf sfa" AS '/tmp'; select bfilename('sdf sfa', 'as df .txt'); bfilename ------------------------------------ bfilename('sdf sfa', 'as df .txt') (1 row) ``` * bfilein(cstring) 描述:解析传入的字符串,生成一个bfile类型对象。传入的字符串有固定格式要求,必须是'bfilename(str1, str2)'。 参数类型:cstring 返回值类型:bfile 示例: ``` --参数格式不对 select bfilein('bfilenamell(sdf,asdf)'); ERROR: invalid input syntax for bfile: "bfilenamell(sdf,asdf)" CONTEXT: referenced column: bfilein --参数格式正确 CREATE or REPLACE DIRECTORY "bfile_test_dir" AS '/tmp'; select bfilein('bfilename(bfile_test_dir,regress_bfile.txt)'); bfilein -------------------------------------------------- bfilename('bfile_test_dir', 'regress_bfile.txt') (1 row) ``` * bfileout(bfile) 描述:将传入的bfile类型对象转换成一个cstring类型的字符串。 参数类型:bfile 返回值类型:cstring 示例: ``` CREATE or REPLACE DIRECTORY "bfile_test_dir" AS '/tmp'; select bfileout(bfilename('bfile_test_dir','regress_bfile.txt')); bfileout -------------------------------------------------- bfilename('bfile_test_dir', 'regress_bfile.txt') (1 row) ``` * bfilerecv(internal) 描述:将内部类型internal转换成一个bfile类型对象。因为internal类型是一个内部类型,无法通过外部传值,所以bfilerecv函数无法通过外部调用。 参数类型:internal 返回值类型:bfile 示例: ``` select bfilerecv(' '); ERROR: cannot accept a value of type internal LINE 1: select bfilerecv(' '); ^ ``` * bfilesend(bfile) 描述:将传入的bfile类型对象一个internal类型对象。 参数类型:bfile 返回值类型:internal 示例: ``` CREATE or REPLACE DIRECTORY "bfile_test_dir" AS '/tmp'; select bfilesend(bfilename('bfile_test_dir','regress_bfile.txt')); bfilesend -------------------------------------------------------------------------------------- \x0000000f000000126266696c655f746573745f64697200726567726573735f6266696c652e74787400 (1 row) ``` --- --- url: /en/docs/latest-lite/sql_reference/bgwriter_stat.md --- # BGWRITER\_STAT **BGWRITER\_STAT** displays statistics about the background writer process's activities. **Table 1** BGWRITER\_STAT columns --- --- url: /en/docs/latest/sql_reference/bgwriter_stat.md --- # BGWRITER\_STAT **BGWRITER\_STAT** displays statistics about the background writer process's activities. **Table 1** BGWRITER\_STAT columns --- --- url: /zh/docs/latest-lite/sql_reference/bgwriter_stat.md --- # BGWRITER\_STAT BGWRITER\_STAT视图显示关于后端写线程活动的统计信息。 **表 1** BGWRITER\_STAT字段 --- --- url: /zh/docs/latest/sql_reference/bgwriter_stat.md --- # BGWRITER\_STAT BGWRITER\_STAT视图显示关于后端写线程活动的统计信息。 **表 1** BGWRITER\_STAT字段 --- --- url: /en/docs/latest-lite/sql_reference/binary_string_functions_and_operators.md --- # Binary String Functions and Operators ## String Operators SQL defines some string functions that use keywords, rather than commas, to separate arguments. * octet\_length(string) Description: Specifies the number of bytes in a binary string. Return type: int Example: ``` openGauss=# SELECT octet_length(E'jo\\000se'::bytea) AS RESULT; result -------- 5 (1 row) ``` * overlay(string placing string from int \[for int]) Description: Replaces substrings. Return type: bytea Example: ``` openGauss=# SELECT overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 2 for 3) AS RESULT; result ---------------- \x5402036d6173 (1 row) ``` * position(substring in string) Description: Specifies the location of a specified substring. Return type: int Example: ``` openGauss=# SELECT position(E'\\000om'::bytea in E'Th\\000omas'::bytea) AS RESULT; result -------- 3 (1 row) ``` * substring(string \[from int] \[for int]) Description: Truncates a substring. Return type: bytea Example: ``` openGauss=# SELECT substring(E'Th\\000omas'::bytea from 2 for 3) AS RESULT; result ---------- \x68006f (1 row) ``` * substr(string, from int \[, for int]) Description: Truncates a substring. Return type: bytea Example: ``` openGauss=# select substr(E'Th\\000omas'::bytea,2, 3) as result; result ---------- \x68006f (1 row) ``` * trim(\[both] bytes from string) Description: Removes the longest string containing only bytes from **bytes** from the start and end of **string**. Return type: bytea Example: ``` openGauss=# SELECT trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea) AS RESULT; result ---------- \x546f6d (1 row) ``` ## Other Binary String Functions openGauss provides common syntax used for calling functions. * btrim(string bytea,bytes bytea) Description: Removes the longest string containing only bytes from **bytes** from the start and end of **string**. Return type: bytea Example: ``` openGauss=# SELECT btrim(E'\\000trim\\000'::bytea, E'\\000'::bytea) AS RESULT; result ------------ \x7472696d (1 row) ``` * get\_bit(string, offset) Description: Extracts bits from a string. Return type: int Example: ``` openGauss=# SELECT get_bit(E'Th\\000omas'::bytea, 45) AS RESULT; result -------- 1 (1 row) ``` * get\_byte(string, offset) Description: Extracts bytes from a string. Return type: int Example: ``` openGauss=# SELECT get_byte(E'Th\\000omas'::bytea, 4) AS RESULT; result -------- 109 (1 row) ``` * rawcmp Description: Specifies the raw data type comparison function. Parameter: raw, raw Return type: integer * raweq Description: Specifies the raw data type comparison function. Parameter: raw, raw Return type: Boolean * rawge Description: Specifies the raw data type comparison function. Parameter: raw, raw Return type: Boolean * rawgt Description: Specifies the raw data type comparison function. Parameter: raw, raw Return type: Boolean * rawin Description: Specifies the raw data type parsing function. Parameter: cstring Return type: bytea * rawle Description: Specifies the raw data type parsing function. Parameter: raw, raw Return type: Boolean * rawlike Description: Specifies the raw data type parsing function. Parameter: raw, raw Return type: Boolean * rawlt Description: Specifies the raw data type parsing function. Parameter: raw, raw Return type: Boolean * rawne Description: Compares whether the raw types are the same. Parameter: raw, raw Return type: Boolean * rawnlike Description: Checks whether the raw type matches the mode. Parameter: raw, raw Return type: Boolean * rawout Description: Specifies the RAW output API. Parameter: bytea Return type: cstring * rawsend Description: Converts the bytea type to the binary type. Parameter: raw Return type: bytea * rawtohex Description: Converts the raw format to the hexadecimal format. Parameter: text Return type: text * set\_bit(string,offset, newvalue) Description: Sets bits in a string. Return type: bytea Example: ``` openGauss=# SELECT set_bit(E'Th\\000omas'::bytea, 45, 0) AS RESULT; result ------------------ \x5468006f6d4173 (1 row) ``` * set\_byte(string,offset, newvalue) Description: Sets bytes in a string. Return type: bytea Example: ``` openGauss=# SELECT set_byte(E'Th\\000omas'::bytea, 4, 64) AS RESULT; result ------------------ \x5468006f406173 (1 row) ``` --- --- url: /en/docs/latest/sql_reference/binary_string_functions_and_operators.md --- # Binary String Functions and Operators ## String Operators SQL defines some string functions that use keywords, rather than commas, to separate arguments. * octet\_length(string) Description: Specifies the number of bytes in a binary string. Return type: int Example: ``` openGauss=# SELECT octet_length(E'jo\\000se'::bytea) AS RESULT; result -------- 5 (1 row) ``` * overlay(string placing string from int \[for int]) Description: Replaces substrings. Return type: bytea Example: ``` openGauss=# SELECT overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 2 for 3) AS RESULT; result ---------------- \x5402036d6173 (1 row) ``` * position(substring in string) Description: Specifies the location of a specified substring. Return type: int Example: ``` openGauss=# SELECT position(E'\\000om'::bytea in E'Th\\000omas'::bytea) AS RESULT; result -------- 3 (1 row) ``` * substring(string \[from int] \[for int]) Description: Truncates a substring. Return type: bytea Example: ``` openGauss=# SELECT substring(E'Th\\000omas'::bytea from 2 for 3) AS RESULT; result ---------- \x68006f (1 row) ``` * substr(string, from int \[, for int]) Description: Truncates a substring. Return type: bytea Example: ``` openGauss=# select substr(E'Th\\000omas'::bytea,2, 3) as result; result ---------- \x68006f (1 row) ``` * trim(\[both] bytes from string) Description: Removes the longest string containing only bytes from **bytes** from the start and end of **string**. Return type: bytea Example: ``` openGauss=# SELECT trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea) AS RESULT; result ---------- \x546f6d (1 row) ``` ## Other Binary String Functions openGauss provides common syntax used for calling functions. * btrim(string bytea,bytes bytea) Description: Removes the longest string containing only bytes from **bytes** from the start and end of **string**. Return type: bytea Example: ``` openGauss=# SELECT btrim(E'\\000trim\\000'::bytea, E'\\000'::bytea) AS RESULT; result ------------ \x7472696d (1 row) ``` * get\_bit(string, offset) Description: Extracts bits from a string. Return type: int Example: ``` openGauss=# SELECT get_bit(E'Th\\000omas'::bytea, 45) AS RESULT; result -------- 1 (1 row) ``` * get\_byte(string, offset) Description: Extracts bytes from a string. Return type: int Example: ``` openGauss=# SELECT get_byte(E'Th\\000omas'::bytea, 4) AS RESULT; result -------- 109 (1 row) ``` * set\_bit(string,offset, newvalue) Description: Sets bits in a string. Return type: bytea Example: ``` openGauss=# SELECT set_bit(E'Th\\000omas'::bytea, 45, 0) AS RESULT; result ------------------ \x5468006f6d4173 (1 row) ``` * set\_byte(string,offset, newvalue) Description: Sets bytes in a string. Return type: bytea Example: ``` openGauss=# SELECT set_byte(E'Th\\000omas'::bytea, 4, 64) AS RESULT; result ------------------ \x5468006f406173 (1 row) ``` --- --- url: /en/docs/latest-lite/sql_reference/binary_types.md --- # Binary Types [Table 1](#en-us_topic_0283136911_en-us_topic_0237121951_en-us_topic_0059778141_t910f42f45b374d94afe2798c42fc5ef6) lists the binary data types supported by openGauss. **Table 1** Binary data types > \[!NOTE]NOTE > > * In addition to the size limitation on each column, the total size of each tuple is 1073733621 bytes (1 GB to 8203 bytes). > * BYTEAWITHOUTORDERWITHEQUALCOL, BYTEAWITHOUTORDERCOL, \_BYTEAWITHOUTORDERWITHEQUALCOL, and \_BYTEAWITHOUTORDERCOL cannot be directly used to create a table. Example: ``` -- Create a table. openGauss=# CREATE TABLE blob_type_t1 ( BT_COL1 INTEGER, BT_COL2 BLOB, BT_COL3 RAW, BT_COL4 BYTEA ) ; -- Insert data. openGauss=# INSERT INTO blob_type_t1 VALUES(10,empty_blob(), HEXTORAW('DEADBEEF'),E'\\xDEADBEEF'); -- Query data in the table. openGauss=# SELECT * FROM blob_type_t1; bt_col1 | bt_col2 | bt_col3 | bt_col4 ---------+---------+----------+------------ 10 | | DEADBEEF | \xdeadbeef (1 row) -- Delete the table. openGauss=# DROP TABLE blob_type_t1; ``` --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_binary_types.md --- # Binary Types [Table 1](#en-us_topic_0283136911_en-us_topic_0237121951_en-us_topic_0059778141_t910f42f45b374d94afe2798c42fc5ef6) lists the binary data types supported by openGauss. Compared with the original openGauss, Dolphin modifies the binary types as follows: 1. The BINARY, VARBINARY, TINYBLOB, MEDIUMBLOB, and LONGBLOB types are added. 2. The input function of the BLOB type is modified. When **dolphin.b\_compatibility\_mode** is set to **on**, the input function is compatible with the common character string input of the MySQL database. The corresponding character string can be output only when **bytea\_output** is set to **escape**; otherwise, the value will be converted into a hexadecimal character string for output. 3. For the TINYBLOB, MEDIUMBLOB, and LONGBLOB types, if **dolphin.b\_compatibility\_mode** is set to **off**, the input function is still compatible with the common character string input of the MySQL database. The corresponding character string can be output only when **bytea\_output** is set to **escape**; otherwise, the character string will be converted into a hexadecimal character string for output. 4. The input function of the BINARY type is modified to support the identification of escape characters in the MySQL database. 5. The BIANRY EXPR is added. The BINARY keyword before any expression indicates that the expression is converted to the binary type. **Table 1** Binary data types > \[!NOTE]NOTE > > * In addition to the size limit of each column, the total size of each tuple cannot exceed 1 GB – 8203 bytes (that is, 1073733621 bytes). > > * BYTEAWITHOUTORDERWITHEQUALCOL, BYTEAWITHOUTORDERCOL, \_BYTEAWITHOUTORDERWITHEQUALCOL, and \_BYTEAWITHOUTORDERCOL cannot be directly used to create a table. Example: ``` --Create a table. openGauss=# CREATE TABLE blob_type_t1 ( BT_COL1 INTEGER, BT_COL2 BLOB, BT_COL3 RAW, BT_COL4 BYTEA ) ; --Insert data. openGauss=# INSERT INTO blob_type_t1 VALUES(10,empty_blob(), HEXTORAW('DEADBEEF'),E'\\xDEADBEEF'); --Query data in the table. openGauss=# SELECT * FROM blob_type_t1; bt_col1 | bt_col2 | bt_col3 | bt_col4 ---------+---------+----------+------------ 10 | | DEADBEEF | \xdeadbeef (1 row) --Delete the table. openGauss=# DROP TABLE blob_type_t1; --Use BINARY to convert data. openGauss=# select 'a\t'::binary; binary -------- \x6109 (1 row) openGauss=# select binary 'a\b'; binary -------- \x6108 (1 row) ``` --- --- url: /en/docs/latest/sql_reference/binary_types.md --- # Binary Types [Table 1](#en-us_topic_0283136911_en-us_topic_0237121951_en-us_topic_0059778141_t910f42f45b374d94afe2798c42fc5ef6) lists the binary data types supported by openGauss. **Table 1** Binary data types > \[!NOTE]NOTE > > * In addition to the size limitation on each column, the total size of each tuple is 1073733621 bytes (1 GB to 8203 bytes). > * BYTEAWITHOUTORDERWITHEQUALCOL, BYTEAWITHOUTORDERCOL, \_BYTEAWITHOUTORDERWITHEQUALCOL, and \_BYTEAWITHOUTORDERCOL cannot be directly used to create a table. Example: ``` -- Create a table. openGauss=# CREATE TABLE blob_type_t1 ( BT_COL1 INTEGER, BT_COL2 BLOB, BT_COL3 RAW, BT_COL4 BYTEA ) ; -- Insert data. openGauss=# INSERT INTO blob_type_t1 VALUES(10,empty_blob(), HEXTORAW('DEADBEEF'),E'\\xDEADBEEF'); -- Query data in the table. openGauss=# SELECT * FROM blob_type_t1; bt_col1 | bt_col2 | bt_col3 | bt_col4 ---------+---------+----------+------------ 10 | | DEADBEEF | \xdeadbeef (1 row) -- Delete the table. openGauss=# DROP TABLE blob_type_t1; ``` --- --- url: /zh/docs/latest/ograc/sql_reference/binary_types.md --- # Binary Types **表 1** 二进制类型 | 名称 | 描述 | 存储空间 | | :------------ | :------------ | :------------ | | BINARY(size) | 存储定长的二进制数据。1. 若输入长度小于size,则右边补0 | 1 ~ 8000字节 | | VARBINARY(size) | 存储变长的二进制数据。 | 1 ~ 8000字节 | | IMAGE | VARBINARY的大对象类型,用于存储大对象数据 | 0 ~ (4G-1) | | RAW(size) | 存储变长的二进制数据 | 1 ~ 8000字节 | | BLOB/BYTEA | RAW的大对象类型,用于存储变长大对象二进制数据。输入为16进制字符串 | 0 ~ (4G-1) | 示例: ``` --创建表。 SQL> CREATE TABLE blob_type_t1 ( a INTEGER, b BLOB, c RAW, d BYTEA, e binary(10), f varbinary(10), g image ) ; --插入数据。 SQL> INSERT INTO blob_type_t1 VALUES(10,empty_blob(), HEXTORAW('DE'),'\xDEADBEEF', '\xDEADBEEF', '\xDEADBEEF', '\xDEADBEEF'); --查询表中的数据。 SQL> SELECT * FROM blob_type_t1; A B C D E F G ---------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- 10 DE DEADBEEF \xDEADBEEF \xDEADBEEF \xDEADBEEF 1 rows fetched. --删除表。 SQL> DROP TABLE blob_type_t1; ``` --- --- url: >- /en/docs/latest-lite/performance_tuning_guide/binding_cpu_cores_for_the_database_server_and_client.md --- # Binding CPU Cores for the Database Server and Client 1. Install the openGauss database. For details, see *openGauss Installation Guide*. 2. Stop the database. For details, see section "Starting and Stopping openGauss" in *openGauss Administrator Guide*. 3. Use the gs\_guc tool to modify the database port and IP address. For details about how to use the gs\_guc tool, see section "Server Tools > gs\_guc" in *openGauss Tool Reference*. 4. Use the gs\_guc tool to set the following parameters. ``` advance_xlog_file_num = 100 numa_distribute_mode = 'all' numa_distribute_mode = 'all' thread_pool_attr = '812,4,(cpubind:0-27,32-59,64-91,96-123)' thread_pool_attr = '464,4,(cpubind:1-27,32-59,64-91,96-123)' xloginsert_locks = 16 wal_writer_cpu=0 wal_file_init_num = 20 xlog_idle_flushes_before_sleep = 500000000 pagewriter_sleep = 10ms ``` 5. Run the following command to start the database on the server in core binding mode. ``` numactl -C 1-27,32-59,64-91,96-123 gaussdb --single_node -D /data1/gaussdata -p 3625 & ``` Core **0** is used for wal\_writer, and **1-27,32-59,64-91,96-123** indicates that 111 cores are used to run the TPC-C program and the other 16 cores are used to process the network interruption of the server. 6. Run the following command to bind the 48 cores of the client CPU to the NIC interrupt queue. ``` sh bind_net_irq.sh 48 ``` --- --- url: >- /en/docs/latest/performance_tuning_guide/binding_cpu_cores_for_the_database_server_and_client.md --- # Binding CPU Cores for the Database Server and Client 1. Install the openGauss database. For details, see *openGauss Installation Guide*. 2. Stop the database. For details, see section "Starting and Stopping openGauss" in *openGauss Administrator Guide*. 3. Use the gs\_guc tool to modify the database port and IP address. For details about how to use the gs\_guc tool, see section "Server Tools > gs\_guc" in *openGauss Tool Reference*. 4. Use the gs\_guc tool to set the following parameters. ``` advance_xlog_file_num = 100 numa_distribute_mode = 'all' thread_pool_attr = '464,4,(cpubind:1-27,32-59,64-91,96-123)' xloginsert_locks = 16 wal_writer_cpu=0 wal_file_init_num = 20 xlog_idle_flushes_before_sleep = 500000000 pagewriter_sleep = 10ms ``` 5. Run the following command to start the database on the server in core binding mode. ``` numactl -C 1-27,32-59,64-91,96-123 gaussdb --single_node -D /data1/gaussdata -p 3625 & ``` *0* is used for wal\_writer . *1-27,32-59,64-91,96-123* indicates that 112 cores are used to run the TPC-C program and the other 16 cores are used to process the network interruption of the server. 6. Run the following command to bind the 48 cores of the client CPU to the NIC interrupt queue. ``` sh bind_net_irq.sh 48 ``` --- --- url: /en/docs/latest-lite/performance_tuning_guide/bios_configuration.md --- # BIOS Configuration 1. Restore BIOS factory defaults. 2. Modify the BIOS settings as follows: 1. Choose **BIOS** > **Advanced** > **MISC Config** and set **Support** **Smmu** to **Disabled**, as shown in [Figure 1](#en-us_topic_0283136610_en-us_topic_0263913266_fig1464144318512). **Figure 1** Modifying BIOS settings (1)\ ![](figures/modifying-bios-settings-1.png) 2. Choose **BIOS** > **Advanced** > **MISC Config** and set **CPU Prefetching Configuration** to **Disabled**, as shown in [Figure 1](#en-us_topic_0283136610_en-us_topic_0263913266_fig1464144318512). 3. Choose **BIOS** > **Advanced** > **Memory Config** and set **Die Interleaving** to **Disable**, as shown in [Figure 1](#en-us_topic_0283136610_en-us_topic_0263913266_fig1464144318512). **Figure 2** Modifying BIOS settings (2)\ ![](figures/modifying-bios-settings-2.png) 3. Restart the BIOS. --- --- url: /en/docs/latest/performance_tuning_guide/bios_configuration.md --- # BIOS Configuration 1. Restore BIOS factory defaults. 2. Modify the BIOS settings as follows: 1. Choose **BIOS** > **Advanced** > **MISC Config** and set **Support** **Smmu** to **Disabled**, as shown in [Figure 1](#en-us_topic_0263913266_fig1464144318512). **Figure 1** Modifying BIOS settings (1)\ ![](figures/modifying-bios-settings-1.png) 2. Choose **BIOS** > **Advanced** > **MISC Config** and set **CPU Prefetching Configuration** to **Disabled**, as shown in [Figure 1](#en-us_topic_0263913266_fig1464144318512). 3. Choose **BIOS** > **Advanced** > **Memory Config** and set **Die Interleaving** to **Disable**, as shown in [Figure 1](#en-us_topic_0263913266_fig1464144318512). **Figure 2** Modifying BIOS settings (2)\ ![](figures/modifying-bios-settings-2.png) 3. Restart the BIOS. --- --- url: /zh/docs/latest-lite/performance_tuning_guide/bios_configuration.md --- # BIOS配置 1. 恢复BIOS出厂设置。 2. 修改相关BIOS设置,如下所示: 1. **BIOS>Advanced>MISC Config,配置Support Smmu为Disabled**,如[图1](#zh-cn_topic_0283136610_zh-cn_topic_0263913266_fig1464144318512)所示。 **图 1** 修改BIOS设置(1)\ ![](figures/修改BIOS设置(1).png) 2. **BIOS>Advanced>MISC Config,配置CPU Prefetching Configuration为Disabled**,如[图1](#zh-cn_topic_0283136610_zh-cn_topic_0263913266_fig1464144318512)所示。 3. **BIOS>Advanced>Memory Config,配置Die Interleaving为Disable**,如[图2](#zh-cn_topic_0283136610_zh-cn_topic_0263913266_fig6430185319610)所示。 **图 2** 修改BIOS设置(2)\ ![](figures/修改BIOS设置(2).png) 3. 重启BIOS系统。 --- --- url: /zh/docs/latest/performance_tuning_guide/bios_configuration.md --- # BIOS配置 1. 恢复BIOS出厂设置。 2. 修改相关BIOS设置,如下所示: a. **BIOS>Advanced>MISC Config,配置Support Smmu为Disabled**,如[图1](#fig1464144318512)所示。 **图 1** 修改BIOS设置(1)\ ![](figures/Modifying-BIOS-Settings1.png) b.**BIOS>Advanced>MISC Config,配置CPU Prefetching Configuration为Disabled**,如[图1](#fig1464144318512)所示。 c.**BIOS>Advanced>Memory Config,配置Die Interleaving为Disable**,如[图2](#fig6430185319610)所示。 **图 2** 修改BIOS设置(2)\ ![](figures/Modifying-BIOS-Settings2.png) 3. 重启操作系统。 --- --- url: /en/docs/latest-lite/sql_reference/bit_string_functions_and_operators.md --- # Bit String Functions and Operators ## Bit String Operators Aside from the usual comparison operators, the following operators can be used. Bit string operands of **&**, **|**, and **#** must be of equal length. In case of bit shifting, the original length of the string is preserved by zero padding (if necessary). * || Description: Connects bit strings. Example: ``` openGauss=# SELECT B'10001' || B'011' AS RESULT; result ---------- 10001011 (1 row) ``` > \[!NOTE]NOTE > It is recommended that a column have no more than 180 consecutive internal joins. A column with over 180 joins will be split into joined consecutive strings. > Example: **str1||str2||str3||str4** is split into **(str1||str2)||(str3||str4)**. * & Description: Specifies the AND operation between bit strings. Example: ``` openGauss=# SELECT B'10001' & B'01101' AS RESULT; result -------- 00001 (1 row) ``` * | Description: Specifies the OR operation between bit strings. Example: ``` openGauss=# SELECT B'10001' | B'01101' AS RESULT; result -------- 11101 (1 row) ``` * \# Description: Specifies the OR operation between bit strings if they are inconsistent. If the same positions in the two bit strings are both 1 or 0, the position returns **0**. Example: ``` openGauss=# SELECT B'10001' # B'01101' AS RESULT; result -------- 11100 (1 row) ``` * \~ Description: Specifies the NOT operation between bit strings. Example: ``` openGauss=# SELECT ~B'10001'AS RESULT; result ---------- 01110 (1 row) ``` * << Description: Shifts left in a bit string. Example: ``` openGauss=# SELECT B'10001' << 3 AS RESULT; result ---------- 01000 (1 row) ``` * \>> Description: Shifts right in a bit string. Example: ``` openGauss=# SELECT B'10001' >> 2 AS RESULT; result ---------- 00100 (1 row) ``` The following SQL-standard functions work on bit strings as well as strings: **length**, **bit\_length**, **octet\_length**, **position**, **substring**, and **overlay**. The following functions work on bit strings as well as binary strings: **get\_bit** and **set\_bit**. When working with a bit string, these functions number the first (leftmost) bit of the string as bit 0. In addition, it is possible to convert between integral values and type **bit**. Example: ``` openGauss=# SELECT 44::bit(10) AS RESULT; result ------------ 0000101100 (1 row) openGauss=# SELECT 44::bit(3) AS RESULT; result -------- 100 (1 row) openGauss=# SELECT cast(-44 as bit(12)) AS RESULT; result -------------- 111111010100 (1 row) openGauss=# SELECT '1110'::bit(4)::integer AS RESULT; result -------- 14 (1 row) openGauss=# select substring('10101111'::bit(8), 2); substring ----------- 0101111 (1 row) ``` > \[!NOTE]NOTE > Casting to just "bit" means casting to bit(1), and so will deliver only the least significant bit of the integer. --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_bit_string_functions_and_operators.md --- # Bit String Functions and Operators Compared with the original openGauss, Dolphin modifies the bit string functions as follows: 1. The `bit_bool` function is added. 2. The `^` operator is added. 3. The `bit_count` function is added. * bit\_bool(bit) Description: Returns a Boolean value based on the data in the bit string. If the value is **0**, **false** is returned. Otherwise, **true** is returned. Return type: Boolean Example: ``` openGauss=# select bit_bool('11111'); bit_bool ---------- t (1 row) ``` ``` openGauss=# select bit_bool('00001'); bit_bool ---------- t (1 row) ``` ``` openGauss=# select bit_bool('00000'); bit_bool ---------- f (1 row) ``` * ^ Description: Implements the bitwise XOR of bit-type data. Return type: bit Example: ``` openGauss=# select b'1001'^b'1100'; ?column? ---------- 0101 (1 row) ``` * bit\_count(N) Description: Returns the number of 1s in the binary string when the input data is converted to an unsigned 64-bit integer. Input type: numeric text bit Return type: text Note: If the entered number or character string exceeds the range of unsigned 64-bit integers, 64 is returned. If the number of 1s in the input bits exceeds 64, 1 is returned. Example: ``` SELECT bit_count(29); bit_count ---------- 4 (1 row) ``` ``` SELECT bit_count(b'101010'); bit_count ---------- 3 (1 row) ``` --- --- url: /en/docs/latest/sql_reference/bit_string_functions_and_operators.md --- # Bit String Functions and Operators ## Bit String Operators Aside from the usual comparison operators, the following operators can be used. Bit string operands of **&**, **|**, and **#** must be of equal length. In case of bit shifting, the original length of the string is preserved by zero padding (if necessary). * || Description: Connects bit strings. Example: ``` openGauss=# SELECT B'10001' || B'011' AS RESULT; result ---------- 10001011 (1 row) ``` > \[!NOTE]NOTE > It is recommended that a column have no more than 180 consecutive internal joins. A column with over 180 joins will be split into joined consecutive strings. > Example: **str1||str2||str3||str4** is split into **(str1||str2)||(str3||str4)**. * & Description: Specifies the AND operation between bit strings. Example: ``` openGauss=# SELECT B'10001' & B'01101' AS RESULT; result -------- 00001 (1 row) ``` * | Description: Specifies the OR operation between bit strings. Example: ``` openGauss=# SELECT B'10001' | B'01101' AS RESULT; result -------- 11101 (1 row) ``` * \# Description: Specifies the OR operation between bit strings if they are inconsistent. If the same positions in the two bit strings are both 1 or 0, the position returns **0**. Example: ``` openGauss=# SELECT B'10001' # B'01101' AS RESULT; result -------- 11100 (1 row) ``` * \~ Description: Specifies the NOT operation between bit strings. Example: ``` openGauss=# SELECT ~B'10001'AS RESULT; result ---------- 01110 (1 row) ``` * << Description: Shifts left in a bit string. Example: ``` openGauss=# SELECT B'10001' << 3 AS RESULT; result ---------- 01000 (1 row) ``` * \>> Description: Shifts right in a bit string. Example: ``` openGauss=# SELECT B'10001' >> 2 AS RESULT; result ---------- 00100 (1 row) ``` The following SQL-standard functions work on bit strings as well as strings: **length**, **bit\_length**, **octet\_length**, **position**, **substring**, and **overlay**. The following functions work on bit strings as well as binary strings: **get\_bit** and **set\_bit**. When working with a bit string, these functions number the first (leftmost) bit of the string as bit 0. In addition, it is possible to convert between integral values and type **bit**. Example: ``` openGauss=# SELECT 44::bit(10) AS RESULT; result ------------ 0000101100 (1 row) openGauss=# SELECT 44::bit(3) AS RESULT; result -------- 100 (1 row) openGauss=# SELECT cast(-44 as bit(12)) AS RESULT; result -------------- 111111010100 (1 row) openGauss=# SELECT '1110'::bit(4)::integer AS RESULT; result -------- 14 (1 row) openGauss=# select substring('10101111'::bit(8), 2); substring ----------- 0101111 (1 row) ``` > \[!NOTE]NOTE > Casting to just "bit" means casting to bit(1), and so will deliver only the least significant bit of the integer. --- --- url: /en/docs/latest-lite/sql_reference/bit_string_types.md --- # Bit String Types Bit strings are strings of 1's and 0's. They can be used to store bit masks. openGauss supports two bit string types: bit(n) and bit varying(n), in which **n** is a positive integer. The **bit** type data must match the length *n* exactly. It is an error to attempt to store shorter or longer bit strings. The **bit varying** data is of variable length up to the maximum length *n*; longer strings will be rejected. Writing **bit** without a length is equivalent to **bit(1)**, while **bit varying** without a length specification means unlimited length. > \[!NOTE]NOTE > If one explicitly casts a bit-string value to **bit(n)**, it will be truncated or zero-padded on the right to be exactly *n* bits, without raising an error. > Similarly, if one explicitly casts a bit-string value to **bit varying(n)**, it will be truncated on the right if it is more than *n* bits. ``` -- Create a table. openGauss=# CREATE TABLE bit_type_t1 ( BT_COL1 INTEGER, BT_COL2 BIT(3), BT_COL3 BIT VARYING(5) ) ; -- Insert data. openGauss=# INSERT INTO bit_type_t1 VALUES(1, B'101', B'00'); -- Specify the type length. An error is reported if an inserted string exceeds this length. openGauss=# INSERT INTO bit_type_t1 VALUES(2, B'10', B'101'); ERROR: bit string length 2 does not match type bit(3) CONTEXT: referenced column: bt_col2 -- Specify the type length. Data is converted if it exceeds this length. openGauss=# INSERT INTO bit_type_t1 VALUES(2, B'10'::bit(3), B'101'); -- View data. openGauss=# SELECT * FROM bit_type_t1; bt_col1 | bt_col2 | bt_col3 ---------+---------+--------- 1 | 101 | 00 2 | 100 | 101 (2 rows) -- Delete the table. openGauss=# DROP TABLE bit_type_t1; ``` --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_bit_string_types.md --- # Bit String Types Compared with the original openGauss, Dolphin modifies the bit string types as follows: 1. The data of the bit type is of variable length up to the maximum length *n*. Longer strings will be rejected. The data of the **bit varying** type is of variable length up to the maximum length *n*. Longer strings will be rejected. 2. If one explicitly casts a bit-string value to **bit(n)**, it will be truncated or zero-padded on the left to be exactly *n* bits, without raising an error. ``` --Create a table. openGauss=# CREATE TABLE bit_type_t1 ( BT_COL1 INTEGER, BT_COL2 BIT(3), BT_COL3 BIT VARYING(5) ) ; --Data is converted if it exceeds the length of this data type. openGauss=# INSERT INTO bit_type_t1 VALUES(2, B'1000'::bit(3), B'101'); --View data. openGauss=# SELECT * FROM bit_type_t1; bt_col1 | bt_col2 | bt_col3 ---------+---------+--------- 2 | 100 | 101 (2 rows) --If the length of a character string is insufficient, the character string is converted to bit(n) and zeros are padded on the left. openGauss=# SELECT B'10'::bit(4); bit -------- 000010 (1 row) --Delete a table. openGauss=# DROP TABLE bit_type_t1; ``` --- --- url: /en/docs/latest/sql_reference/bit_string_types.md --- # Bit String Types Bit strings are strings of 1's and 0's. They can be used to store bit masks. openGauss supports two bit string types: bit(n) and bit varying(n), in which **n** is a positive integer. The **bit** type data must match the length *n* exactly. It is an error to attempt to store shorter or longer bit strings. The **bit varying** data is of variable length up to the maximum length *n*; longer strings will be rejected. Writing **bit** without a length is equivalent to **bit(1)**, while **bit varying** without a length specification means unlimited length. > \[!NOTE]NOTE > If one explicitly casts a bit-string value to **bit(n)**, it will be truncated or zero-padded on the right to be exactly *n* bits, without raising an error. > Similarly, if one explicitly casts a bit-string value to **bit varying(n)**, it will be truncated on the right if it is more than *n* bits. ``` -- Create a table. openGauss=# CREATE TABLE bit_type_t1 ( BT_COL1 INTEGER, BT_COL2 BIT(3), BT_COL3 BIT VARYING(5) ) ; -- Insert data. openGauss=# INSERT INTO bit_type_t1 VALUES(1, B'101', B'00'); -- Specify the type length. An error is reported if an inserted string exceeds this length. openGauss=# INSERT INTO bit_type_t1 VALUES(2, B'10', B'101'); ERROR: bit string length 2 does not match type bit(3) CONTEXT: referenced column: bt_col2 -- Specify the type length. Data is converted if it exceeds this length. openGauss=# INSERT INTO bit_type_t1 VALUES(2, B'10'::bit(3), B'101'); -- View data. openGauss=# SELECT * FROM bit_type_t1; bt_col1 | bt_col2 | bt_col3 ---------+---------+--------- 1 | 101 | 00 2 | 100 | 101 (2 rows) -- Delete the table. openGauss=# DROP TABLE bit_type_t1; ``` --- --- url: /zh/docs/latest-lite/sql_reference/bloom_index.md --- # BLOOM ## 1. 介绍 bloom提供了一种基于Bloom过滤器的索引访问方法。 Bloom过滤器是一种节省空间的数据结构,用于测试元素是否是集合的成员。对于索引访问方法,它允许通过签名快速排除不匹配的元组,其大小在索引创建时确定。 签名是索引属性的有损表示,因此容易报告误报;也就是说,可能会报告某个元素在集合中,而它不在集合中。因此,必须始终使用堆条目中的实际属性值重新检查索引搜索结果。较大的签名会降低误报的几率,从而减少无用的堆访问次数,但当然也会使索引变大,从而使扫描速度变慢。 当表具有许多属性并且查询测试它们的任意组合时,这种类型的索引最有用。传统的btree索引比bloom索引更快,但它可能需要许多 btree索引来支持所有可能的查询,但只需要一个bloom索引。但请注意,bloom索引仅支持相等查询,而btree索引也可以执行不等式和范围搜索。 ## 2. 参数 创建索引时在其WITH子句中接受以下参数: * length 每个签名(索引条目)的长度(以bit为单位)。它被四舍五入到最接近的16的倍数。默认值为 80 bits,最大值为4096 bits。 * col1 — col32 为每个索引列生成的bit数。每个参数的名称是指它控制的索引列的编号。默认值为2 bits。 ## 3. 示例 这是创建bloom索引的示例: ```sql CREATE INDEX bloomidx ON tbloom USING bloom (i1,i2,i3) WITH (length=80, col1=2, col2=2, col3=4); ``` 索引的签名长度为80 bits,属性i1和i2映射到2个bit位,属性i3映射到4个bit位,其余属性默认映射2个bit位。 下面是一个更完整的bloom指数定义和用法示例,以及与等效btree索引的比较。bloom指数比btree索引小得多,并且可以表现得更好。 ```sql openGauss=#CREATE TABLE tbloom AS SELECT (random() * 100000)::int as i1, (random() * 100000)::int as i2, (random() * 100000)::int as i3, (random() * 100000)::int as i4, (random() * 100000)::int as i5, (random() * 100000)::int as i6 FROM generate_series(1,1000000); ``` 对这个大表进行顺序扫描需要很长时间: ```sql openGauss=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451; QUERY PLAN ----------------------------------------------------------------------------------------------------------- Seq Scan on tbloom (cost=0.00..21411.00 rows=1 width=24) (actual time=1159.983..1159.983 rows=0 loops=1) Filter: ((i2 = 898732) AND (i5 = 123451)) Rows Removed by Filter: 1000000 Total runtime: 1160.182 ms (4 rows) ``` 即使定义了btree索引,结果仍然是顺序扫描: ```sql openGauss=# CREATE INDEX btreeidx ON tbloom (i1, i2, i3, i4, i5, i6); CREATE INDEX openGauss=# SELECT pg_size_pretty(pg_relation_size('btreeidx')); pg_size_pretty ---------------- 39 MB (1 row) openGauss=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451; QUERY PLAN --------------------------------------------------------------------------------------------------------- Seq Scan on tbloom (cost=0.00..21411.00 rows=1 width=24) (actual time=566.108..566.108 rows=0 loops=1) Filter: ((i2 = 898732) AND (i5 = 123451)) Rows Removed by Filter: 1000000 Total runtime: 566.301 ms (4 rows) ``` 在处理此类搜索时,在表上定义bloom索引比 btree 更好: ```sql openGauss=# CREATE INDEX bloomidx ON tbloom USING bloom (i1, i2, i3, i4, i5, i6); CREATE INDEX openGauss=# SELECT pg_size_pretty(pg_relation_size('bloomidx')); pg_size_pretty ---------------- 15 MB (1 row) openGauss=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------- Bitmap Heap Scan on tbloom (cost=17848.25..17852.27 rows=1 width=24) (actual time=14.183..14.183 rows=0 loops=1) Recheck Cond: ((i2 = 898732) AND (i5 = 123451)) Rows Removed by Index Recheck: 242 Heap Blocks: exact=241 -> Bitmap Index Scan on bloomidx (cost=0.00..17848.25 rows=1 width=0) (actual time=13.042..13.042 rows=242 loops=1) Index Cond: ((i2 = 898732) AND (i5 = 123451)) Total runtime: 14.621 ms (7 rows) ``` 现在,btree搜索的主要问题是,当搜索条件不约束前导索引列时,btree效率低下。btree的更好策略是在每列上创建一个单独的索引。然后规划者会选择这样的东西: ```sql openGauss=# CREATE INDEX btreeidx1 ON tbloom (i1); CREATE INDEX openGauss=# CREATE INDEX btreeidx2 ON tbloom (i2); CREATE INDEX openGauss=# CREATE INDEX btreeidx3 ON tbloom (i3); CREATE INDEX openGauss=# CREATE INDEX btreeidx4 ON tbloom (i4); CREATE INDEX openGauss=# CREATE INDEX btreeidx5 ON tbloom (i5); CREATE INDEX openGauss=# CREATE INDEX btreeidx6 ON tbloom (i6); CREATE INDEX openGauss=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------- Bitmap Heap Scan on tbloom (cost=8.92..12.93 rows=1 width=24) (actual time=0.256..0.256 rows=0 loops=1) Recheck Cond: ((i5 = 123451) AND (i2 = 898732)) -> BitmapAnd (cost=8.92..8.92 rows=1 width=0) (actual time=0.252..0.252 rows=0 loops=1) -> Bitmap Index Scan on btreeidx5 (cost=0.00..4.33 rows=11 width=0) (actual time=0.249..0.249 rows=0 loops=1) Index Cond: (i5 = 123451) -> Bitmap Index Scan on btreeidx2 (cost=0.00..4.33 rows=11 width=0) (Actual time: never executed) Index Cond: (i2 = 898732) Total runtime: 0.529 ms (8 rows) ``` 尽管此查询的运行速度比使用任何一个索引都要快得多,但我们在索引大小方面付出了代价。每个单列btree索引占用22MB,因此所需的总空间为132MB,是bloom索引所用空间的八倍多。 ## 4. 限制 bloom索引目前仅支持int4和text类型。 bloom索引的运算符类只需要索引数据类型的哈希函数和用于搜索的相等运算符。此示例显示了text数据类型的运算符类定义: ```sql CREATE OPERATOR CLASS text_ops DEFAULT FOR TYPE text USING bloom AS OPERATOR 1 =(text, text), FUNCTION 1 hashtext(text); ``` --- --- url: /zh/docs/latest/sql_reference/bloom_index.md --- # BLOOM ## 1. 介绍 bloom提供了一种基于Bloom过滤器的索引访问方法。 Bloom过滤器是一种节省空间的数据结构,用于测试元素是否是集合的成员。对于索引访问方法,它允许通过签名快速排除不匹配的元组,其大小在索引创建时确定。 签名是索引属性的有损表示,因此容易报告误报;也就是说,可能会报告某个元素在集合中,而它不在集合中。因此,必须始终使用堆条目中的实际属性值重新检查索引搜索结果。较大的签名会降低误报的几率,从而减少无用的堆访问次数,但当然也会使索引变大,从而使扫描速度变慢。 当表具有许多属性并且查询测试它们的任意组合时,这种类型的索引最有用。传统的btree索引比bloom索引更快,但它可能需要许多 btree索引来支持所有可能的查询,但只需要一个bloom索引。但请注意,bloom索引仅支持相等查询,而btree索引也可以执行不等式和范围搜索。 ## 2. 参数 创建索引时在其WITH子句中接受以下参数: * length 每个签名(索引条目)的长度(以bit为单位)。它被四舍五入到最接近的16的倍数。默认值为 80 bits,最大值为4096 bits。 * col1 — col32 为每个索引列生成的bit数。每个参数的名称是指它控制的索引列的编号。默认值为2 bits。 ## 3. 示例 这是创建bloom索引的示例: ```sql CREATE INDEX bloomidx ON tbloom USING bloom (i1,i2,i3) WITH (length=80, col1=2, col2=2, col3=4); ``` 索引的签名长度为80 bits,属性i1和i2映射到2个bit位,属性i3映射到4个bit位,其余属性默认映射2个bit位。 下面是一个更完整的bloom指数定义和用法示例,以及与等效btree索引的比较。bloom指数比btree索引小得多,并且可以表现得更好。 ```sql openGauss=#CREATE TABLE tbloom AS SELECT (random() * 100000)::int as i1, (random() * 100000)::int as i2, (random() * 100000)::int as i3, (random() * 100000)::int as i4, (random() * 100000)::int as i5, (random() * 100000)::int as i6 FROM generate_series(1,1000000); ``` 对这个大表进行顺序扫描需要很长时间: ```sql openGauss=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451; QUERY PLAN ----------------------------------------------------------------------------------------------------------- Seq Scan on tbloom (cost=0.00..21411.00 rows=1 width=24) (actual time=1159.983..1159.983 rows=0 loops=1) Filter: ((i2 = 898732) AND (i5 = 123451)) Rows Removed by Filter: 1000000 Total runtime: 1160.182 ms (4 rows) ``` 即使定义了btree索引,结果仍然是顺序扫描: ```sql openGauss=# CREATE INDEX btreeidx ON tbloom (i1, i2, i3, i4, i5, i6); CREATE INDEX openGauss=# SELECT pg_size_pretty(pg_relation_size('btreeidx')); pg_size_pretty ---------------- 39 MB (1 row) openGauss=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451; QUERY PLAN --------------------------------------------------------------------------------------------------------- Seq Scan on tbloom (cost=0.00..21411.00 rows=1 width=24) (actual time=566.108..566.108 rows=0 loops=1) Filter: ((i2 = 898732) AND (i5 = 123451)) Rows Removed by Filter: 1000000 Total runtime: 566.301 ms (4 rows) ``` 在处理此类搜索时,在表上定义bloom索引比 btree 更好: ```sql openGauss=# CREATE INDEX bloomidx ON tbloom USING bloom (i1, i2, i3, i4, i5, i6); CREATE INDEX openGauss=# SELECT pg_size_pretty(pg_relation_size('bloomidx')); pg_size_pretty ---------------- 15 MB (1 row) openGauss=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------- Bitmap Heap Scan on tbloom (cost=17848.25..17852.27 rows=1 width=24) (actual time=14.183..14.183 rows=0 loops=1) Recheck Cond: ((i2 = 898732) AND (i5 = 123451)) Rows Removed by Index Recheck: 242 Heap Blocks: exact=241 -> Bitmap Index Scan on bloomidx (cost=0.00..17848.25 rows=1 width=0) (actual time=13.042..13.042 rows=242 loops=1) Index Cond: ((i2 = 898732) AND (i5 = 123451)) Total runtime: 14.621 ms (7 rows) ``` 现在,btree搜索的主要问题是,当搜索条件不约束前导索引列时,btree效率低下。btree的更好策略是在每列上创建一个单独的索引。然后规划者会选择这样的东西: ```sql openGauss=# CREATE INDEX btreeidx1 ON tbloom (i1); CREATE INDEX openGauss=# CREATE INDEX btreeidx2 ON tbloom (i2); CREATE INDEX openGauss=# CREATE INDEX btreeidx3 ON tbloom (i3); CREATE INDEX openGauss=# CREATE INDEX btreeidx4 ON tbloom (i4); CREATE INDEX openGauss=# CREATE INDEX btreeidx5 ON tbloom (i5); CREATE INDEX openGauss=# CREATE INDEX btreeidx6 ON tbloom (i6); CREATE INDEX openGauss=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------- Bitmap Heap Scan on tbloom (cost=8.92..12.93 rows=1 width=24) (actual time=0.256..0.256 rows=0 loops=1) Recheck Cond: ((i5 = 123451) AND (i2 = 898732)) -> BitmapAnd (cost=8.92..8.92 rows=1 width=0) (actual time=0.252..0.252 rows=0 loops=1) -> Bitmap Index Scan on btreeidx5 (cost=0.00..4.33 rows=11 width=0) (actual time=0.249..0.249 rows=0 loops=1) Index Cond: (i5 = 123451) -> Bitmap Index Scan on btreeidx2 (cost=0.00..4.33 rows=11 width=0) (Actual time: never executed) Index Cond: (i2 = 898732) Total runtime: 0.529 ms (8 rows) ``` 尽管此查询的运行速度比使用任何一个索引都要快得多,但我们在索引大小方面付出了代价。每个单列btree索引占用22MB,因此所需的总空间为132MB,是bloom索引所用空间的八倍多。 ## 4. 限制 bloom索引目前仅支持int4和text类型。 bloom索引的运算符类只需要索引数据类型的哈希函数和用于搜索的相等运算符。此示例显示了text数据类型的运算符类定义: ```sql CREATE OPERATOR CLASS text_ops DEFAULT FOR TYPE text USING bloom AS OPERATOR 1 =(text, text), FUNCTION 1 hashtext(text); ``` --- --- url: /zh/docs/latest-lite/characteristic_description/bloom_index.md --- # BLOOM索引 ## 可获得性 本特性自openGauss 7.0.0-RC2版本开始引入。 ## 特性简介 openGauss的Bloom索引特性是一种节省空间的数据结构,用于测试元素是否是集合的成员。对于索引访问方法,它允许通过签名快速排除不匹配的元组,其签名大小在索引创建时确定。 ## 客户价值 为多列任意组合的等值查询提供一种高效且空间成本相对较低的解决方案。 ## 特性描述 当表具有许多属性并且查询测试它们的任意组合时,这种类型的索引最有用。传统的btree索引比bloom索引更快,但它可能需要许多btree索引来支持所有可能的查询,但只需要一个bloom索引。但请注意,bloom索引仅支持相等查询,而btree索引也可以执行不等式和范围搜索。 ## 特性增强 无。 ## 特性约束 * 仅支持表的列类型为int4类型和text类型。 * 仅支持行存表,行存段页式表。 * 不支持在线创建索引。 * 索引长度(签名)的长度最大为4096 bits。 ## 依赖关系 无。 ## 使用指导 * **使用bloom索引** 为表创建bloom索引,签名长度为80bits, 列1的值哈希到3个bit位,列2的值哈希到4个bit位。 ``` CREATE TABLE tst (i int4, t text); CREATE INDEX bloomidx ON tst USING bloom (i, t) WITH (length=80, col1 = 3, col2 = 4); ``` --- --- url: /zh/docs/latest/characteristic_description/bloom_index.md --- # BLOOM索引 ## 可获得性 本特性自openGauss 7.0.0-RC2版本开始引入。 ## 特性简介 openGauss的Bloom索引特性是一种节省空间的数据结构,用于测试元素是否是集合的成员。对于索引访问方法,它允许通过签名快速排除不匹配的元组,其签名大小在索引创建时确定。 ## 客户价值 为多列任意组合的等值查询提供一种高效且空间成本相对较低的解决方案。 ## 特性描述 当表具有许多属性并且查询测试它们的任意组合时,这种类型的索引最有用。传统的btree索引比bloom索引更快,但它可能需要许多btree索引来支持所有可能的查询,但只需要一个bloom索引。但请注意,bloom索引仅支持相等查询,而btree索引也可以执行不等式和范围搜索。 ## 特性增强 无。 ## 特性约束 * 仅支持表的列类型为int4类型和text类型。 * 仅支持行存表,行存段页式表。 * 不支持在线创建索引。 * 索引长度(签名)的长度最大为4096 bits。 ## 依赖关系 无。 ## 使用指导 * **使用bloom索引** 为表创建bloom索引,签名长度为80bits, 列1的值哈希到3个bit位,列2的值哈希到4个bit位。 ``` CREATE TABLE tst (i int4, t text); CREATE INDEX bloomidx ON tst USING bloom (i, t) WITH (length=80, col1 = 3, col2 = 4); ``` --- --- url: /zh/docs/latest-lite/datavec/bm25_full_text_search_index.md --- # BM25全文检索索引 ## 可获得性 本特性自 openGauss 7.0.0-RC2 版本开始引入。 ## 特性简介 **图 1主备场景BM25索引设计方案** ![](figures/BM25.png) ## 客户价值 RAG(Retrieval-Augmented Generation,检索增强生成)是一种结合检索系统与生成模型的技术框架, 通过从外部知识库中检索相关信息,生成模型根据这些相关信息生成更加准确的答案。越来越多的企业通过RAG技术搭建自己的智能知识问答、业务推荐等系统,提升了效率、优化用户体验和提供精准服务。 如何快速从外部知识库中检索准确度高,相关性高的文档,进而提升 RAG 系统准确性和响应能力,成为了企业的核心诉求。BM25(Best Matching 25)全文检索算法,通过对文档库构建BM25倒排索引,可以快速准确的检索用户提问的相关文档,已成为 RAG 系统的主流选择。 openGauss 新增BM25全文检索索引功能,通过简单的创建索引命令,即可为文档库构建BM25索引,实现对文档的快速检索,支持新增文档实时更新到索引中。查询响应性能超GIN索引几十甚至上百倍。同时,索引数据对接openGauss存储引擎,支持主备部署,提供高可用、故障切换、备份恢复的能力,以保障业务连续性。 ## 特性描述 openGauss 单机/主备集群场景下,对文档库中的文档进行分词,随后根据分词结果构建倒排索引。扫描阶段,根据搜索词实现对文档的快速搜索。 * 构建阶段: 用户发起BM25索引构建请求,主节点通过分词器对文档进行分词,对每个分词构建倒排索引,即每个分词对应着所有包含该分词的文档信息。支持并行构建。 * 基于日志的索引数据同步: 为了保证索引数据的实时性,索引构建和行数据修改都通过日志方式同步到备机。 * 扫描阶段 用户发起BM25索引查询请求,节点内部会将用户的问题进行分词,根据该分词结果获取相关倒排列表,随后遍历倒排列表通过BM25算法对文档进行打分、排序,最终返回 top-k 个分数最高的文档给大模型生成用户所需答案。同时支持 where 等过滤条件。 ## 特性增强 * 支持 `WITH (dict_path='绝对路径')` 为 BM25 索引指定自定义词典目录。 * BM25 存储支持块级优化,通过可变大小块提升小数据场景的空间利用率。 * `7.0.0 LTS` 版本引入索引空间优化能力,属于内部存储优化,不改变 SQL 使用方式。 ## 特性约束 BM25 全文检索的规格约束如下: * 表:仅支持普通表的构建BM25索引,不支持分区表。支持astore、段页式表,不支持ustore表、列存表、MOT表。 * 数据类型:仅支持 text 字段类型。 * 仅支持单列构建索引,不支持构建多列组合索引,如:create index bm25\_index on bm25\_table using bm25(col1, col2); * 仅支持降序排序。 * 不支持极致RTO。 * 仅支持原词检索,不支持同义词检索和语义相关性检索。 * 索引创建及使用兼容A、B、C、PG库。 * 不支持CONCURRENTLY创建索引。 * 创建索引支持设置 `dict_path` 选项,其他 options 暂不支持。 * 不支持修改已创建索引的 `dict_path`;由于分词器特性,修改自定义词典后已有索引会失效,需删除并重建索引。 * 使用 `dict_path` 自定义词典时,主备场景要求主机与备机的词典目录内容保持一致,且 `GAUSSHOME` 保持一致。 * 旧版本创建的 BM25 索引在新版本中仍可用;如需获得更低空间占用,建议删除旧索引并重建。 * 批量插入文档事务未提交情况下,同时执行索引查询,会出现文档分数变化的现象。批量插入文档失败时事务回滚,建议重建索引。 --- --- url: /zh/docs/latest/datavec/bm25_full_text_search_index.md --- # BM25全文检索索引 ## 可获得性 本特性自 openGauss 7.0.0-RC2 版本开始引入。 ## 特性简介 **图 1主备场景BM25索引设计方案** ![](figures/BM25.png) ## 客户价值 RAG(Retrieval-Augmented Generation,检索增强生成)是一种结合检索系统与生成模型的技术框架, 通过从外部知识库中检索相关信息,生成模型根据这些相关信息生成更加准确的答案。越来越多的企业通过 RAG 技术搭建自己的智能知识问答、业务推荐等系统,提升了效率、优化用户体验和提供精准服务。 如何快速从外部知识库中检索准确度高,相关性高的文档,进而提升 RAG 系统准确性和响应能力,成为了企业的核心诉求。BM25(Best Matching 25)全文检索算法,通过对文档库构建 BM25 倒排索引,可以快速准确的检索用户提问的相关文档,已成为 RAG 系统的主流选择。 openGauss 新增BM25全文检索索引功能,通过简单的创建索引命令,即可为文档库构建BM25索引,实现对文档的快速检索,支持新增文档实时更新到索引中。查询响应性能超GIN索引几十甚至上百倍。同时,索引数据对接openGauss存储引擎,支持主备部署,提供高可用、故障切换、备份恢复的能力,以保障业务连续性。 ## 特性描述 openGauss 单机/主备集群场景下,对文档库中的文档进行分词,随后根据分词结果构建倒排索引。扫描阶段,根据搜索词实现对文档的快速搜索。 * 构建阶段: 用户发起BM25索引构建请求,主节点通过分词器对文档进行分词,对每个分词构建倒排索引,即每个分词对应着所有包含该分词的文档信息。支持并行构建。 * 基于日志的索引数据同步: 为了保证索引数据的实时性,索引构建和行数据修改都通过日志方式同步到备机。 * 扫描阶段: 用户发起BM25索引查询请求,节点内部会将用户的问题进行分词,根据该分词结果获取相关倒排列表,随后遍历倒排列表通过BM25算法对文档进行打分、排序,最终返回 top-k 个分数最高的文档给大模型生成用户所需答案。同时支持 where 等过滤条件。 ## 特性增强 * 支持 `WITH (dict_path='绝对路径')` 为 BM25 索引指定自定义词典目录。 * BM25 存储支持块级优化,通过可变大小块提升小数据场景的空间利用率。 * `7.0.0 LTS` 版本引入索引空间优化能力,属于内部存储优化,不改变 SQL 使用方式。 ## 特性约束 BM25 全文检索的规格约束如下: * 表:仅支持普通表的构建BM25索引,不支持分区表。支持astore、段页式表,不支持ustore表、列存表、MOT表。 * 数据类型:仅支持 text 字段类型。 * 仅支持单列构建索引,不支持构建多列组合索引,如:create index bm25\_index on bm25\_table using bm25(col1, col2); * 仅支持降序排序。 * 不支持极致RTO。 * 仅支持原词检索,不支持同义词检索和语义相关性检索。 * 索引创建及使用兼容A、B、C、PG库。 * 不支持CONCURRENTLY创建索引。 * 创建索引支持设置 `dict_path` 选项,其他 options 暂不支持。 * 不支持修改已创建索引的 `dict_path`;由于分词器特性,修改自定义词典后已有索引会失效,需删除并重建索引。 * 使用 `dict_path` 自定义词典时,主备场景要求主机与备机的词典目录内容保持一致,且 `GAUSSHOME` 保持一致。 * 旧版本创建的 BM25 索引在新版本中仍可用;如需获得更低空间占用,建议删除旧索引并重建。 * 批量插入文档事务未提交情况下,同时执行索引查询,会出现文档分数变化的现象。批量插入文档失败时事务回滚,建议重建索引。 --- --- url: /zh/docs/latest-lite/datavec/bm25_usage_guide.md --- # BM25全文检索索引使用指南 本章节主要介绍openGauss中BM25全文检索索引使用指南。 ## 1. 安装部署 使用Docker实现openGauss容器化部署,简化DevOps用户的安装、配置和环境设置,参考 [容器镜像安装](https://docs.opengauss.org/zh/docs/latest-lite/installation_guide/installing_the_container_image.html)。 ## 2. 语法介绍 BM25全文检索索引对普通表的文档列构建全文索引,实现对文档的高效检索。 * **索引构建** BM25索引支持对指定文档列构建全文索引,支持并行构建,大幅提升大文本数据集的索引构建速度,语法如下: ``` -- 设置并行构建线程数,设置范围1~32。不设置该参数时,默认单线程构建 ALTER TABLE {表名称} SET(parallel_workers=32); -- 给指定表的指定文档列构建BM25索引(默认词典) CREATE INDEX {索引名称} on {表名称} using bm25({文档列名称}); -- 给指定表的指定文档列构建BM25索引(自定义词典目录) CREATE INDEX {索引名称} on {表名称} using bm25({文档列名称}) WITH (dict_path='{词典目录绝对路径}'); ``` BM25索引构建的相关约束见[BM25索引介绍](bm25_full_text_search_index.md) > \[!NOTE]说明 > > 并行构建索引场景下,计算一篇文档中词汇的Maxscore参数会和串行构建场景下存在一定偏差,小概率会影响检索过程中DAAT Maxscore方法文档剪枝策略,导致召回率有一定波动。 > 串行、并行构建索引召回率存在一定偏差。相同数据,多次执行并行构建,也可能存在一定偏差。 * **BM25索引操作符** 由于BM25索引扫描需要指定查询词,因此新增BM25索引操作符:<&>,表示根据查询词来搜索相关的文档。使用方式如下: ``` {文档列名称} <&> {查询词} ``` * **索引扫描** * **BM25索引扫描基本格式** BM25索引的目标是在文档数据集集中搜索出与查询词最相关的 n 篇文档,并按相关性由高到低的顺序返回给用户。其搜索语法下述固定格式: ``` -- LIMIT 不设置时返回所有与查询词相关的文档 select * from {表名称} ORDER BY {文档列名称} <&> {查询词} DESC LIMIT n; ``` * **通过提示词的方式使用BM25索引扫描** ``` -- 查询分数最高的 n 个文档 SELECT /*+ indexscan (表名称 索引名称)*/ * FROM {表名称} ORDER BY {文档列名称} <&> {查询词} DESC LIMIT n; -- 如果想要查看返回的文档分数,可以将分数以虚拟列的方式展示 SELECT /*+ indexscan (表名称 索引名称)*/ *, {文档列名称} <&> {查询词} AS score FROM {表名称} ORDER BY {文档列名称} <&> {查询词} DESC LIMIT n; ``` * **通过扫描GUC设置使用BM25索引扫描** ``` -- 关闭顺序扫描 set enable_seqscan = off; -- 开启索引扫描 set enable_indexscan = on; -- 查询分数最高的 n 个文档 SELECT * FROM {表名称} ORDER BY {文档列名称} <&> {查询词} DESC LIMIT n; ``` > \[!NOTE]说明 > > BM25索引扫描性能可以通过相关GUC参数调优,执行语句前可先进行参数设置,详情参考[BM25参数调优](./bm25_full_text_retrieval_index_parameters.md)。 * **索引删除** ``` DROP INDEX {索引名称}; ``` ## 3. 自定义词典(dict\_path) `dict_path` 用于为单个 BM25 索引指定词典目录,便于不同业务使用不同分词词典。 * 必须是绝对路径。路径需在 `$GAUSSHOME` 目录下。 * 目录下需包含以下文件:`jieba.dict.utf8`、`hmm_model.utf8`、`user.dict.utf8`、`idf.utf8`、`stop_words.utf8`。 * 不支持修改已创建索引的 `dict_path`;如调整自定义词典,已有索引会失效,需删除并重建索引。 * 主备场景下,主机与备机的词典目录内容需要保持一致,且两端 `GAUSSHOME` 需要保持一致。 * 未设置 `dict_path` 时,使用默认词典。 ## 4. 索引空间优化说明 `7.0.0 LTS` 版本引入 BM25 索引空间优化能力。通过可变大小块存储机制,在小文档或小倒排片段场景下可降低空间浪费,提升索引空间利用率。 该优化为内部存储能力增强,不改变 BM25 的 SQL 使用方式。 旧版本创建的 BM25 索引在新版本中仍可用;如需获得更低空间占用,建议删除旧索引并重建。 ## 5. 示例 本节将通过实例对上述索引语法进行演示。 ``` -- 创建普通表,包含id、document列,document存储文本数据 openGauss=# CREATE TABLE bm25_table ( id INT, document TEXT ); CREATE TABLE -- 插入文档数据 INSERT INTO bm25_table VALUES(1, '香蕉是热带水果'); INSERT INTO bm25_table VALUES(2, '小明喜欢吃香蕉'); -- 为document列建立bm25索引 openGauss=# CREATE INDEX bm25_index on bm25_table using bm25(document); ALTER TABLE -- 使用bm25索引检索'香蕉'相关的文档,查看查询计划,走BM25索引 openGauss=# EXPLAIN SELECT /*+ indexscan (bm25_table bm25_index)*/ *, document <&> '香蕉' AS score FROM bm25_table ORDER BY document <&> '香蕉' DESC; QUERY PLAN --------------------------------------------------------- Index Scan using bm25_index on bm25_table (cost=0.00..7.11 rows=1238 width=36) Order by: (document <&> '香蕉'::text) (2 rows) -- 执行查询语句,检索'香蕉'相关的文档,并显示文档分数 openGauss=# SELECT /*+ indexscan (bm25_table bm25_index)*/ *, document <&> '香蕉' AS score FROM bm25_table ORDER BY document <&> '香蕉' DESC; id | document | score 1 | 小明喜欢吃香蕉 | .182321563363075 2 | 香蕉是热带水果 | .182321563363075 (2 rows) -- 使用bm25索引检索'小明喜欢吃什么' openGauss=# SELECT /*+ indexscan (bm25_table bm25_index)*/ *, document <&> '小明喜欢吃什么' AS score FROM bm25_table ORDER BY document <&> '小明喜欢吃什么' DESC; id | document | score 1 | 小明喜欢吃香蕉 | 1.3862943649292 (1 rows) --删除索引 openGauss=# DROP INDEX bm25_index; DROP INDEX ``` --- --- url: /zh/docs/latest/datavec/bm25_usage_guide.md --- # BM25全文检索索引使用指南 本章节主要介绍openGauss中BM25全文检索索引使用指南。 ## 1. 安装部署 使用Docker实现openGauss容器化部署,简化DevOps用户的安装、配置和环境设置,参考 [容器镜像安装](https://docs.opengauss.org/zh/docs/latest/installation_guide/installing_the_container_image.html)。 ## 2. 语法介绍 BM25全文检索索引对普通表的文档列构建全文索引,实现对文档的高效检索。 * **索引构建** BM25索引支持对指定文档列构建全文索引,支持并行构建,大幅提升大文本数据集的索引构建速度,语法如下: ``` -- 设置并行构建线程数,设置范围1~32。不设置该参数时,默认单线程构建 ALTER TABLE {表名称} SET(parallel_workers=32); -- 给指定表的指定文档列构建BM25索引(默认词典) CREATE INDEX {索引名称} on {表名称} using bm25({文档列名称}); -- 给指定表的指定文档列构建BM25索引(自定义词典目录) CREATE INDEX {索引名称} on {表名称} using bm25({文档列名称}) WITH (dict_path='{词典目录绝对路径}'); ``` BM25索引构建的相关约束见[BM25索引介绍](bm25_full_text_search_index.md) > \[!NOTE]说明 > > 并行构建索引场景下,计算一篇文档中词汇的Maxscore参数会和串行构建场景下存在一定偏差,小概率会影响检索过程中DAAT Maxscore方法文档剪枝策略,导致召回率有一定波动。 > 串行、并行构建索引召回率存在一定偏差。相同数据,多次执行并行构建,也可能存在一定偏差。 * **BM25索引操作符** 由于BM25索引扫描需要指定查询词,因此新增BM25索引操作符:<&>,表示根据查询词来搜索相关的文档。使用方式如下: ``` {文档列名称} <&> {查询词} ``` * **索引扫描** * **BM25索引扫描基本格式** BM25索引的目标是在文档数据集集中搜索出与查询词最相关的 n 篇文档,并按相关性由高到低的顺序返回给用户。其搜索语法下述固定格式: ``` -- LIMIT 不设置时返回所有与查询词相关的文档 select * from {表名称} ORDER BY {文档列名称} <&> {查询词} DESC LIMIT n; ``` * **通过提示词的方式使用BM25索引扫描** ``` -- 查询分数最高的 n 个文档 SELECT /*+ indexscan (表名称 索引名称)*/ * FROM {表名称} ORDER BY {文档列名称} <&> {查询词} DESC LIMIT n; -- 如果想要查看返回的文档分数,可以将分数以虚拟列的方式展示 SELECT /*+ indexscan (表名称 索引名称)*/ *, {文档列名称} <&> {查询词} AS score FROM {表名称} ORDER BY {文档列名称} <&> {查询词} DESC LIMIT n; ``` * **通过扫描GUC设置使用BM25索引扫描** ``` -- 关闭顺序扫描 set enable_seqscan = off; -- 开启索引扫描 set enable_indexscan = on; -- 查询分数最高的 n 个文档 SELECT * FROM {表名称} ORDER BY {文档列名称} <&> {查询词} DESC LIMIT n; ``` > \[!NOTE]说明 > > BM25索引扫描性能可以通过相关GUC参数调优,执行语句前可先进行参数设置,详情参考[BM25参数调优](https://docs.opengauss.org/zh/docs/latest/database_reference/bm25_full_text_retrieval_index_parameters.html)。 * **索引删除** ``` DROP INDEX {索引名称}; ``` ## 3. 自定义词典(dict\_path) `dict_path` 用于为单个 BM25 索引指定词典目录,便于不同业务使用不同分词词典。 * 必须是绝对路径。路径需在 `$GAUSSHOME` 目录下。 * 目录下需包含以下文件:`jieba.dict.utf8`、`hmm_model.utf8`、`user.dict.utf8`、`idf.utf8`、`stop_words.utf8`。 * 不支持修改已创建索引的 `dict_path`;如调整自定义词典,已有索引会失效,需删除并重建索引。 * 主备场景下,主机与备机的词典目录内容需要保持一致,且两端 `GAUSSHOME` 需要保持一致。 * 未设置 `dict_path` 时,使用默认词典。 ## 4. 索引空间优化说明 `7.0.0 LTS` 版本引入 BM25 索引空间优化能力。通过可变大小块存储机制,在小文档或小倒排片段场景下可降低空间浪费,提升索引空间利用率。 该优化为内部存储能力增强,不改变 BM25 的 SQL 使用方式。 旧版本创建的 BM25 索引在新版本中仍可用;如需获得更低空间占用,建议删除旧索引并重建。 ## 5. 示例 本节将通过实例对上述索引语法进行演示。 ``` -- 创建普通表,包含id、document列,document存储文本数据 openGauss=# CREATE TABLE bm25_table ( id INT, document TEXT ); CREATE TABLE -- 插入文档数据 INSERT INTO bm25_table VALUES(1, '香蕉是热带水果'); INSERT INTO bm25_table VALUES(2, '小明喜欢吃香蕉'); -- 为document列建立bm25索引 openGauss=# CREATE INDEX bm25_index on bm25_table using bm25(document); ALTER TABLE -- 使用bm25索引检索'香蕉'相关的文档,查看查询计划,走BM25索引 openGauss=# EXPLAIN SELECT /*+ indexscan (bm25_table bm25_index)*/ *, document <&> '香蕉' AS score FROM bm25_table ORDER BY document <&> '香蕉' DESC; QUERY PLAN --------------------------------------------------------- Index Scan using bm25_index on bm25_table (cost=0.00..7.11 rows=1238 width=36) Order by: (document <&> '香蕉'::text) (2 rows) -- 执行查询语句,检索'香蕉'相关的文档,并显示文档分数 openGauss=# SELECT /*+ indexscan (bm25_table bm25_index)*/ *, document <&> '香蕉' AS score FROM bm25_table ORDER BY document <&> '香蕉' DESC; id | document | score 1 | 小明喜欢吃香蕉 | .182321563363075 2 | 香蕉是热带水果 | .182321563363075 (2 rows) -- 使用bm25索引检索'小明喜欢吃什么' openGauss=# SELECT /*+ indexscan (bm25_table bm25_index)*/ *, document <&> '小明喜欢吃什么' AS score FROM bm25_table ORDER BY document <&> '小明喜欢吃什么' DESC; id | document | score 1 | 小明喜欢吃香蕉 | 1.3862943649292 (1 rows) --删除索引 openGauss=# DROP INDEX bm25_index; DROP INDEX ``` --- --- url: /zh/docs/latest-lite/datavec/bm25_full_text_retrieval_index_parameters.md --- # BM25全文检索索引参数 ## enable\_bm25\_taat **参数说明**: 使用BM25索引扫描时,参数开启使用 TAAT 方法按搜索词遍历,对包含搜索词所有文档进行打分、汇总、排序,最终返回 limit n 个分数最高的文档,速度较慢,召回率更高。关闭时,通过 DAAT MaxScore 方法对文档进行剪枝,速度更快,召回率可能会有一定损失。 该参数属于USERSET类型参数,请参考[表1](https://docs.opengauss.org/zh/docs/latest/database_administration_guide/reset_parameters.html#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 布尔型 * on表示开启 TAAT 扫描功能。 * off表示开启 DAAT MaxScore 扫描功能。 **设置建议**:当希望检索搜索词相关的所有文档的排序结果时,建议开启该参数。否则,建议该参数保持关闭状态。 **默认值**: off **设置语法**: ``` set enable_bm25_taat = on; ``` ## bm25\_topk **参数说明**: 使用BM25索引扫描时的动态top-k候选集大小。 该参数属于USERSET类型参数,请参考[表1](https://docs.opengauss.org/zh/docs/latest/database_administration_guide/reset_parameters.html#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应方法三进行设置。 **取值范围**: 整型,5~200 **设置建议**: 建议设置值大于等于`Limit`。如果没有获取足够`Limit`大小的数据会自动扩大bm25\_topk继续扫描,直到获取足够的数据或者没有更多满足条件的数据为止。 **默认值**: 5 **设置语法**: ``` set bm25_topk = 10; ``` > \[!NOTE]说明 > > 设置值小于`Limit`时可能会导致多轮扩大bm25\_topk继续扫描,查询效率会变低。 > 由于 TAAT 方法会默认给包含搜索词的所有候选文档进行打分,因此,此参数仅在 enable\_bm25\_taat 关闭生效。 ## bm25\_k1 **参数说明**: BM25算法参数,影响词频对文档得分。该参数值越大,词频得分就越大。一般保持默认值 1.2 即可。 该参数属于USERSET类型参数,请参考[表1](https://docs.opengauss.org/zh/docs/latest/database_administration_guide/reset_parameters.html#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应方法三进行设置。 **取值范围**: 浮点型,0.0~3.0 **默认值**: 1.2 **设置语法**: ``` set bm25_k1 = 1.5; ``` ## bm25\_b **参数说明**: BM25算法参数,用于调整文档长度对文档评分影响。bm25\_b 越大,对文档长度的惩罚力度就越大。bm25\_b = 0时,长短文档词频一样,则得分一样,bm25\_b 越大,长文档分数越低,短文档分数越高。一般保持默认值 0.75 即可。 该参数属于USERSET类型参数,请参考[表1](https://docs.opengauss.org/zh/docs/latest/database_administration_guide/reset_parameters.html#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应方法三进行设置。 **取值范围**: 浮点型,0.0~1.0 **默认值**: 0.75 **设置语法**: ``` set bm25_b = 0.5; ``` ## max\_score\_ratio **参数说明**: 使用BM25索引 DAAT MaxScore 扫描时,用于控制搜索词 MaxScore 的缩放比例。 该参数属于USERSET类型参数,请参考[表1](https://docs.opengauss.org/zh/docs/latest/database_administration_guide/reset_parameters.html#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 浮点型,0.5~1.3 **默认值**: 1.05 **设置语法**: ``` set max_score_ratio = 0.9; ``` > \[!NOTE]说明 > > 在新增文档时,文档的平均长度是不断变化的。因此,文档词汇的 MaxScore 是一个估计值,新增该参数实现对MaxScore进行调整,建议大于 1.0。 > 在文档扫描时,该参数小于 1.0 时,MaxScore 缩小,能够实现更加激进的剪枝,扫描文档数量变少,查询速度更快,召回率会有一定损失。相反,该参数大于0,剪枝比较宽松,查询速度会慢一点,召回率会更高。 > bm25\_topk 和 max\_score\_ratio 设置不合理的情况下,由于 Limit n > bm25\_topk,内部多轮扩展查询,导致查询结果可能会出现分数不是完全按降序排序。 --- --- url: >- /zh/docs/latest/database_reference/bm25_full_text_retrieval_index_parameters.md --- # BM25全文检索索引参数 ## enable\_bm25\_taat **参数说明**: 使用BM25索引扫描时,参数开启使用 TAAT 方法按搜索词遍历,对包含搜索词所有文档进行打分、汇总、排序,最终返回 limit n 个分数最高的文档,速度较慢,召回率更高。关闭时,通过 DAAT MaxScore 方法对文档进行剪枝,速度更快,召回率可能会有一定损失。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 布尔型 * on表示开启 TAAT 扫描功能。 * off表示开启 DAAT MaxScore 扫描功能。 **设置建议**:当希望检索搜索词相关的所有文档的排序结果时,建议开启该参数。否则,建议该参数保持关闭状态。 **默认值**: off **设置语法**: ``` set enable_bm25_taat = on; ``` ## bm25\_topk **参数说明**: 使用BM25索引扫描时的动态top-k候选集大小。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应方法三进行设置。 **取值范围**: 整型,5~200 **设置建议**: 建议设置值大于等于`Limit`。如果没有获取足够`Limit`大小的数据会自动扩大bm25\_topk继续扫描,直到获取足够的数据或者没有更多满足条件的数据为止。 **默认值**: 5 **设置语法**: ``` set bm25_topk = 10; ``` > \[!NOTE]说明 > > 设置值小于`Limit`时可能会导致多轮扩大bm25\_topk继续扫描,查询效率会变低。 > 由于 TAAT 方法会默认给包含搜索词的所有候选文档进行打分,因此,此参数仅在 enable\_bm25\_taat 关闭生效。 ## bm25\_k1 **参数说明**: BM25算法参数,影响词频对文档得分。该参数值越大,词频得分就越大。一般保持默认值 1.2 即可。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应方法三进行设置。 **取值范围**: 浮点型,0.0~3.0 **默认值**: 1.2 **设置语法**: ``` set bm25_k1 = 1.5; ``` ## bm25\_b **参数说明**: BM25算法参数,用于调整文档长度对文档评分影响。bm25\_b 越大,对文档长度的惩罚力度就越大。bm25\_b = 0时,长短文档词频一样,则得分一样,bm25\_b 越大,长文档分数越低,短文档分数越高。一般保持默认值 0.75 即可。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应方法三进行设置。 **取值范围**: 浮点型,0.0~1.0 **默认值**: 0.75 **设置语法**: ``` set bm25_b = 0.5; ``` ## max\_score\_ratio **参数说明**: 使用BM25索引 DAAT MaxScore 扫描时,用于控制搜索词 MaxScore 的缩放比例。 该参数属于USERSET类型参数,请参考[表1](../database_administration_guide/reset_parameters.md#zh-cn_topic_0283137176_zh-cn_topic_0237121562_zh-cn_topic_0059777490_t91a6f212010f4503b24d7943aed6d846)中对应设置方法进行设置。 **取值范围**: 浮点型,0.5~1.3 **默认值**: 1.05 **设置语法**: ``` set max_score_ratio = 0.9; ``` > \[!NOTE]说明 > > 在新增文档时,文档的平均长度是不断变化的。因此,文档词汇的 MaxScore 是一个估计值,新增该参数实现对MaxScore进行调整,建议大于 1.0。 > 在文档扫描时,该参数小于 1.0 时,MaxScore 缩小,能够实现更加激进的剪枝,扫描文档数量变少,查询速度更快,召回率会有一定损失。相反,该参数大于0,剪枝比较宽松,查询速度会慢一点,召回率会更高。 > bm25\_topk 和 max\_score\_ratio 设置不合理的情况下,由于 Limit n > bm25\_topk,内部多轮扩展查询,导致查询结果可能会出现分数不是完全按降序排序。 --- --- url: /zh/docs/latest-lite/datavec/bm25_index_implementation.md --- # BM25全文检索索引实现 本章节主要介绍openGauss中BM25索引的相关实现。BM25索引主要包含以下几个部分: **文本数据输入**:输入待插入文档库或者查询的文本数据。 **文本分词**:对于输入的文本,使用分词器将其转换为一个个独立的术语。 **构建倒排索引和正排索引**:内置系统函数获取分词好的术语,构建正排索引(文档->\[术语1,术语2,...])和倒排索引(术语1->\[文档1,文档2,...])。 **正排、倒排索引对接openGauss存储引擎**:对接openGauss存储,将构建好的索引数据持久化,支持主备高可用、备份恢复等能力。 **索引扫描**:扫描时通过BM25算法对文档与查询文本之间的相关性进行打分,并返回排序结果。 ![](figures/BM25索引流程图.png) ## 分词器 openGauss BM25集成开源cppjieba分词器,使用“Keyword Extraction”、“Cut With HMM”、“CutForSearch”方法分词,无需手动分词。分词方法使用为内部实现,不支持自定义修改。jieba分词器是一款高效且广泛使用的分词工具,不仅支持英文分词,而且能够很好的将连续的中文文本切分为独立的词语或词组。其设计兼顾了准确性、灵活性和易用性,适用于自然语言处理(NLP)、文本挖掘、信息检索等多种场景。主要支持以下特性: * 精确模式:基于前缀词典与动态规划算法,优先输出最合理的分词结果,适合文本分析。 * 搜索引擎模式:在精确模式基础上对长词再次切分,提升搜索相关内容的召回率。 * 支持用户自定义词典,允许添加专业术语或新词以提升领域适应性。 * 提供关键词提取等进阶功能,扩展分词后处理能力。 ## 正排索引和倒排索引 由于openGauss存储引擎是以8k页面的形式存储数据。因此,正排索引和倒排索引的数据以页面链表的形式进行存储。 `7.0.0 LTS` 版本引入了 BM25 索引空间优化能力,通过可变大小块存储提升小数据场景的空间利用率。旧版本创建的索引在新版本中仍可用;如需获得更低空间占用,建议删除旧索引并重建。 **正排索引**: 正排索引主要是记录文档本身信息和包含的术语信息:\[key: doc\_id] -> \[ctid, (术语1\_location, ..., 术语n\_location)] * 记录文档id以及在行存表中的位置(ctid)等信息,主要用于搜索时,返回文档实际数据以及进行可见性判断。 * 记录每篇文档包含了哪些术语,主要用于文档删除时,能够找到术语对应的倒排索引数据并删除记录的文档相关信息。 **倒排索引**: 倒排索引主要记录术语和包含该术语的文档列表之间的映射关系:\[术语] -> \[doc1, doc2, ..., docn] * 文档列表记录该术语在每篇文档里出现的词频信息和文档长度信息,用于BM25评分。 * 倒排索引主要用于扫描,根据搜索词匹配相应的文档术语倒排索引,对包含该搜索词所有文档使用BM25算法进行相关性打分,筛选出top-k个相关性最高的文档。 --- --- url: /zh/docs/latest/datavec/bm25_index_implementation.md --- # BM25全文检索索引实现 本章节主要介绍openGauss中BM25索引的相关实现。BM25索引主要包含以下几个部分: **1.文本数据输入**:输入待插入文档库或者查询的文本数据。 **2.文本分词**:对于输入的文本,使用分词器将其转换为一个个独立的术语。 **3.构建倒排索引和正排索引**:内置系统函数获取分词好的术语,构建正排索引(文档->\[术语1,术语2,...])和倒排索引(术语1->\[文档1,文档2,...])。 **4.正排、倒排索引对接openGauss存储引擎**:对接openGauss存储,将构建好的索引数据持久化,支持主备高可用、备份恢复等能力。 **5.索引扫描**:扫描时通过BM25算法对文档与查询文本之间的相关性进行打分,并返回排序结果。 ![](figures/BM25索引流程图.png) ## 分词器 openGauss BM25集成开源cppjieba分词器,使用“Keyword Extraction”、“Cut With HMM”、“CutForSearch”方法分词,无需手动分词。分词方法使用为内部实现,不支持自定义修改。jieba分词器是一款高效且广泛使用的分词工具,不仅支持英文分词,而且能够很好的将连续的中文文本切分为独立的词语或词组。其设计兼顾了准确性、灵活性和易用性,适用于自然语言处理(NLP)、文本挖掘、信息检索等多种场景。主要支持以下特性: * 精确模式:基于前缀词典与动态规划算法,优先输出最合理的分词结果,适合文本分析。 * 搜索引擎模式:在精确模式基础上对长词再次切分,提升搜索相关内容的召回率。 * 支持用户自定义词典,允许添加专业术语或新词以提升领域适应性。 * 提供关键词提取等进阶功能,扩展分词后处理能力。 ## 正排索引和倒排索引 由于openGauss存储引擎是以8k页面的形式存储数据。因此,正排索引和倒排索引的数据以页面链表的形式进行存储。 `7.0.0 LTS` 版本引入了 BM25 索引空间优化能力,通过可变大小块存储提升小数据场景的空间利用率。旧版本创建的索引在新版本中仍可用;如需获得更低空间占用,建议删除旧索引并重建。 **正排索引**: 正排索引主要是记录文档本身信息和包含的术语信息:\[key: doc\_id] -> \[ctid, (术语1\_location, ..., 术语n\_location)] * 记录文档id以及在行存表中的位置(ctid)等信息,主要用于搜索时,返回文档实际数据以及进行可见性判断。 * 记录每篇文档包含了哪些术语,主要用于文档删除时,能够找到术语对应的倒排索引数据并删除记录的文档相关信息。 **倒排索引**: 倒排索引主要记录术语和包含该术语的文档列表之间的映射关系:\[术语] -> \[doc1, doc2, ..., docn] * 文档列表记录该术语在每篇文档里出现的词频信息和文档长度信息,用于BM25评分。 * 倒排索引主要用于扫描,根据搜索词匹配相应的文档术语倒排索引,对包含该搜索词所有文档使用BM25算法进行相关性打分,筛选出top-k个相关性最高的文档。 --- --- url: /zh/docs/latest/ograc/sql_reference/boolean_type.md --- # Boolean Type **表 1** 布尔类型 | 名称 | 描述 | 存储空间 | 范围 | | :------------ | :------------ | :------------ | :------------ | | BOOLEAN/BOOL | 存储布尔类型数据 | 4字节 | TRUE,FALSE | * "真"值的有效文本值是: TRUE、true、'T'、't'、'TRUE'、'true'、'1'、任意非零整数。 * "假"值的有效文本值是: FALSE、false、'F'、'f'、'FALSE'、'false'、'0'、0。 示例: ``` --创建表。 SQL> CREATE TABLE bool_type_t1 ( BT_COL1 BOOLEAN, BT_COL2 TEXT ); --插入数据。 SQL> INSERT INTO bool_type_t1 VALUES (TRUE, 'sic est'); SQL> INSERT INTO bool_type_t1 VALUES (FALSE, 'non est'); --查看数据。 SQL> SELECT * FROM bool_type_t1; BT_COL1 BT_COL2 ------- ---------------------------------------------------------------- TRUE sic est FALSE non est 2 rows fetched. SQL> SELECT * FROM bool_type_t1 WHERE bt_col1 = 't'; BT_COL1 BT_COL2 ------- ---------------------------------------------------------------- TRUE sic est 1 rows fetched. --删除表。 SQL> DROP TABLE bool_type_t1; ``` --- --- url: /en/docs/latest-lite/sql_reference/boolean_types.md --- # Boolean Types **Table 1** Boolean types * Valid literal values for the "true" state include: **TRUE**, **'t'**, **'true'**, **'y'**, **'yes'**, **'1'**, **'TRUE'**, **true**, and an integer ranging from 1 to 2^63 – 1 or from –1 to –2^63. * Valid literal values for the "false" state include: **FALSE**, **'f'**, **'false'**, **'n'**, **'no'**, **'0'**, **0**, **'FALSE'**, and **false**. **TRUE** and **FALSE** are standard expressions, compatible with SQL statements. ## Examples Boolean values are displayed using the letters t and f. ``` -- Create a table. openGauss=# CREATE TABLE bool_type_t1 ( BT_COL1 BOOLEAN, BT_COL2 TEXT ); -- Insert data. openGauss=# INSERT INTO bool_type_t1 VALUES (TRUE, 'sic est'); openGauss=# INSERT INTO bool_type_t1 VALUES (FALSE, 'non est'); -- View data. openGauss=# SELECT * FROM bool_type_t1; bt_col1 | bt_col2 ---------+--------- t | sic est f | non est (2 rows) openGauss=# SELECT * FROM bool_type_t1 WHERE bt_col1 = 't'; bt_col1 | bt_col2 ---------+--------- t | sic est (1 row) -- Delete the table. openGauss=# DROP TABLE bool_type_t1; ``` --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_boolean_types.md --- # Boolean Types Compared with the original openGauss, Dolphin modifies the Boolean type as follows: * The output representations of the Boolean type are changed from 't' and 'f' to '1' and '0'. This modification takes effect only on tools except gs\_dump, gs\_dumpall, gsql, gs\_probackup, gs\_rewind, and gs\_clean, for example, JDBC. For more information about the Boolean type of the original openGauss, see [openGauss Boolean Types](https://docs.opengauss.org/en/docs/latest/sql_reference/boolean_types.html). ## Examples ``` --In gsql, the output of the Boolean type is still 't' and 'f'. openGauss=# SELECT true; bool ------ t (1 row) openGauss=# SELECT false; bool ------ f (1 row) ``` --- --- url: /en/docs/latest/sql_reference/boolean_types.md --- # Boolean Types **Table 1** Boolean types * Valid literal values for the "true" state include: **TRUE**, **'t'**, **'true'**, **'y'**, **'yes'**, **'1'**, **'TRUE'**, **true**, and an integer ranging from 1 to 2^63 – 1 or from –1 to –2^63. * Valid literal values for the "false" state include: **FALSE**, **'f'**, **'false'**, **'n'**, **'no'**, **'0'**, **0**, **'FALSE'**, and **false**. **TRUE** and **FALSE** are standard expressions, compatible with SQL statements. ## Examples Boolean values are displayed using the letters t and f. ``` -- Create a table. openGauss=# CREATE TABLE bool_type_t1 ( BT_COL1 BOOLEAN, BT_COL2 TEXT ); -- Insert data. openGauss=# INSERT INTO bool_type_t1 VALUES (TRUE, 'sic est'); openGauss=# INSERT INTO bool_type_t1 VALUES (FALSE, 'non est'); -- View data. openGauss=# SELECT * FROM bool_type_t1; bt_col1 | bt_col2 ---------+--------- t | sic est f | non est (2 rows) openGauss=# SELECT * FROM bool_type_t1 WHERE bt_col1 = 't'; bt_col1 | bt_col2 ---------+--------- t | sic est (1 row) -- Delete the table. openGauss=# DROP TABLE bool_type_t1; ``` --- --- url: /en/docs/latest-lite/sql_reference/branch_statements.md --- # Branch Statements ## Syntax [Figure 1](#en-us_topic_0283137347_en-us_topic_0237122235_en-us_topic_0059779327_fe2376535378e44c78c4e70078d0fb779) shows the syntax diagram for a branch statement. **Figure 1** case\_when::=\ ![](figures/case_when.png "case_when") [Figure 2](#en-us_topic_0283137347_en-us_topic_0237122235_en-us_topic_0059779327_f0b6779d008024e8fb5c2267d8d3bff14) shows the syntax diagram for **when\_clause**. **Figure 2** when\_clause::=\ ![](figures/when_clause.png "when_clause") Parameter description: * *case\_expression*: specifies the variable or expression. * *when\_expression*: specifies the constant or conditional expression. * *statement*: specifies the statement to be executed. ## Examples ``` CREATE OR REPLACE PROCEDURE proc_case_branch(pi_result in integer, pi_return out integer) AS BEGIN CASE pi_result WHEN 1 THEN pi_return := 111; WHEN 2 THEN pi_return := 222; WHEN 3 THEN pi_return := 333; WHEN 6 THEN pi_return := 444; WHEN 7 THEN pi_return := 555; WHEN 8 THEN pi_return := 666; WHEN 9 THEN pi_return := 777; WHEN 10 THEN pi_return := 888; ELSE pi_return := 999; END CASE; raise info 'pi_return : %',pi_return ; END; / CALL proc_case_branch(3,0); -- Delete the stored procedure. DROP PROCEDURE proc_case_branch; ``` --- --- url: /en/docs/latest/sql_reference/branch_statements.md --- # Branch Statements ## Syntax [Figure 1](#en-us_topic_0237122235_en-us_topic_0059779327_fe2376535378e44c78c4e70078d0fb779) shows the syntax diagram for a branch statement. **Figure 1** case\_when::=\ ![](figures/case_when.png "case_when") [Figure 2](#en-us_topic_0237122235_en-us_topic_0059779327_f0b6779d008024e8fb5c2267d8d3bff14) shows the syntax diagram for **when\_clause**. **Figure 2** when\_clause::=\ ![](figures/when_clause.png "when_clause") Parameter description: * *case\_expression*: specifies the variable or expression. * *when\_expression*: specifies the constant or conditional expression. * *statement*: specifies the statement to be executed. ## Examples ``` CREATE OR REPLACE PROCEDURE proc_case_branch(pi_result in integer, pi_return out integer) AS BEGIN CASE pi_result WHEN 1 THEN pi_return := 111; WHEN 2 THEN pi_return := 222; WHEN 3 THEN pi_return := 333; WHEN 6 THEN pi_return := 444; WHEN 7 THEN pi_return := 555; WHEN 8 THEN pi_return := 666; WHEN 9 THEN pi_return := 777; WHEN 10 THEN pi_return := 888; ELSE pi_return := 999; END CASE; raise info 'pi_return : %',pi_return ; END; / CALL proc_case_branch(3,0); -- Delete the stored procedure. DROP PROCEDURE proc_case_branch; ``` --- --- url: /en/docs/latest-lite/brief_tutorial/brief_tutorial.md --- # Brief Tutorial This document describes the product and provides guidance for users to quickly use the database. For details about the features and reference information, see the corresponding section. For example the **Installation Guide** provides information about installation requirements and process, and the **Administration Guide** provides information about administration. Many important features of openGauss are introduced in the **Developer Guide** section. For example, the **[MOT Engine](../database_administration_guide/mot_introduction.md)** section provides a detailed review of the Memory Optimized Tables, a high performance storage engine embedded side-by-side the standard storage engine. This includes "MOT Introduction" section (including performance benchmarks), followed by the "Using MOT" section complete manual guide, and concluded by the "MOT Concepts" section with deeper insight into MOT design and technologies. --- --- url: /en/docs/latest/sql_reference/brief_tutorial/BriefTutorial.md --- # Brief Tutorial This document describes the product and provides guidance for users to quickly use the database. For details about the features and reference information, see the corresponding section. For example the **Installation Guide** provides information about installation requirements and process, and the **Administration Guide** provides information about administration. Many important features of openGauss are introduced in the **Developer Guide** section. For example, the **[MOT Engine](../../database_administration_guide/using_mot_overview.md)** section provides a detailed review of the Memory Optimized Tables, a high performance storage engine embedded side-by-side the standard storage engine. This includes "MOT Introduction" section (including performance benchmarks), followed by the "Using MOT" section complete manual guide, and concluded by the "MOT Concepts" section with deeper insight into MOT design and technologies. --- --- url: /zh/docs/latest-lite/database_om_guide/b_tree_index_faults.md --- # btree 索引故障情况下应对策略 ## 问题现象 偶发索引丢失错误,报错如下。 ``` ERROR: index 'xxxx_index' contains unexpected zero page 或 ERROR: index 'pg_xxxx_index' contains unexpected zero page 或 ERROR: compressed data is corrupt ``` ## 原因分析 该类错误是因为索引发生故障导致的,可能引发故障的原因如下: * 由于软件bug或者硬件原因导致的索引不再可用。 * 索引包含许多空的页面或者几乎为空的页面。 * 并发执行DDL过程中,发生了网络闪断故障。 * 创建并发索引时失败,遗留了一个失效的索引,这样的索引无法被使用。 * 执行DDL或者DML操作时,网络出现故障。 ## 处理办法 执行REINDEX命令进行索引重建。 1. 以操作系统用户omm登录主机。 2. 使用如下命令连接数据库。 ``` gsql -d postgres -p 8000 -r ``` 3. 重建索引。 * 如果进行DDL或DML操作时,因软硬件故障导致索引问题,请执行如下命令重建表索引。 ``` REINDEX TABLE tablename; ``` * 如果错误中提示是xxxx\_index,其中xxxx代表用户表名。请执行如下命令之一重建表的索引。 ``` REINDEX INDEX indexname; ``` 或者 ``` REINDEX TABLE tablename; ``` * 如果错误中提示pg\_xxxx\_index,说明是系统表索引存在问题。请执行如下命令重建表索引。 ``` REINDEX SYSTEM databasename; ``` --- --- url: /zh/docs/latest/resource_pooling/b_tree_index_faults.md --- # btree 索引故障情况下应对策略 ## 问题现象 偶发索引丢失错误,报错如下。 ``` ERROR: index 'xxxx_index' contains unexpected zero page 或 ERROR: index 'pg_xxxx_index' contains unexpected zero page 或 ERROR: compressed data is corrupt ``` ## 原因分析 该类错误是因为索引发生故障导致的,可能引发故障的原因如下: * 由于软件bug或者硬件原因导致的索引不再可用。 * 索引包含许多空的页面或者几乎为空的页面。 * 并发执行DDL过程中,发生了网络闪断故障。 * 创建并发索引时失败,遗留了一个失效的索引,这样的索引无法被使用。 * 执行DDL或者DML操作时,网络出现故障。 ## 处理办法 执行REINDEX命令进行索引重建。 1. 以操作系统用户omm登录主机。 2. 使用如下命令连接数据库。 ``` gsql -d postgres -p 8000 -r ``` 3. 重建索引。 * 如果进行DDL或DML操作时,因软硬件故障导致索引问题,请执行如下命令重建表索引。 ``` REINDEX TABLE tablename; ``` * 如果错误中提示是xxxx\_index,其中xxxx代表用户表名。请执行如下命令之一重建表的索引。 ``` REINDEX INDEX indexname; ``` 或者 ``` REINDEX TABLE tablename; ``` * 如果错误中提示pg\_xxxx\_index,说明是系统表索引存在问题。请执行如下命令重建表索引。 ``` REINDEX SYSTEM databasename; ``` --- --- url: /en/docs/latest-lite/characteristic_description/built_in_stack_tool.md --- # Built-in Stack Tool ## Availability This feature is available since 3.0.0. ## Introduction The stack tool is used to obtain the call stack of each thread in the database. It helps database O\&M personnel locate faults such as deadlock and hang. ## Benefits Provides function-level call stack information to improve the efficiency of database kernel O\&M personnel in analyzing and locating faults such as deadlock and hang. ## Description You can use the gs\_stack() function or the gs\_ctl stack tool to obtain the call stacks of threads in the database. 1. gs\_stack() function * Run **select \* from gs\_stack(pid)** to obtain the call stack of a specified thread. ``` openGauss=# select * from gs_stack(139663481165568); gs_stack -------------------------------------------------------------------- __poll + 0x2d + WaitLatchOrSocket(Latch volatile*, int, int, long) + 0x29f + WaitLatch(Latch volatile*, int, long) + 0x2e + JobScheduleMain() + 0x90f + int GaussDbThreadMain<(knl_thread_role)9>(knl_thread_arg*) + 0x456+ InternalThreadFunc(void*) + 0x2d + ThreadStarterFunc(void*) + 0xa4 + start_thread + 0xc5 + clone + 0x6d + (1 row) ``` * Run **select \* from gs\_stack()** to obtain the call stacks of all threads. ``` openGauss=# select * from gs_stack(); -[ RECORD 1 ]------------------------------------------------------------------------------------------------------- tid | 139670364324352 lwtid | 308 stack | __poll + 0x2d | CommWaitPollParam::caller(int (*)(pollfd*, unsigned long, int), unsigned long) + 0x34 | int comm_socket_call(CommWaitPollParam*, int (*)(pollfd*, unsigned long , int)) + 0x28 | comm_poll(pollfd*, unsigned long, int) + 0xb1 | ServerLoop() + 0x72b | PostmasterMain(int, char**) + 0x314e | main + 0x617 | __libc_start_main + 0xf5 | 0x55d38f8db3a7 [ RECORD 2 ]------------------------------------------------------------------------------------------------------- tid | 139664851859200 lwtid | 520 stack | __poll + 0x2d | WaitLatchOrSocket(Latch volatile*, int, int, long) + 0x29f | SysLoggerMain(int) + 0xc86 | int GaussDbThreadMain<(knl_thread_role)17>(knl_thread_arg*) + 0x45d | InternalThreadFunc(void*) + 0x2d | ThreadStarterFunc(void*) + 0xa4 | start_thread + 0xc5 | clone + 0x6d ``` 2. gs\_ctl stack tool * Run the following command to obtain the call stack of a specified thread: ``` gs_ctl stack -D data_dir -I lwtid ``` In the preceding command, **-D data\_dir** specifies the data directory of the GaussDB process whose call stack needs to be obtained, and **-I lwtid** specifies the lwtid of the target thread. You can run the **ls /proc/pid/task/** command to obtain the lwpid. The following specifies the procedure: 1. Obtain the GaussDB process ID and data directory. ``` ps -ux | more USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND perfadm 308 9.3 10.1 8719348 1649108 ? Sl May20 58:58 /xxx/bin/gaussdb -u 92617 -D /xxx/openGauss/cluster/data1/dn1 -M pending ``` 2. Obtain the lwtid based on the process ID. The directory name in the **task** directory is the lwtid. ``` ls /proc/308/task/ 1096 505 522 525 529 532 536 539 542 546 549 552 555 558 561 565 569 575 584 833 923 926 929 932 935 938 ``` 3. Obtain the call stack based on the specified lwtid. ``` gs_ctl stack -D /xxx/openGauss/cluster/data1/dn1 -I 1096 [2022-05-21 10:52:51.354][24520][][gs_ctl]: gs_stack start: tid<140409677575616> lwtid<1096> __poll + 0x2d CommWaitPollParam::caller(int (*)(pollfd*, unsigned long, int), unsigned long) + 0x34 int comm_socket_call(CommWaitPollParam*, int (*)(pollfd*, unsigned long, int)) + 0x28 comm_poll(pollfd*, unsigned long, int) + 0xb1 ServerLoop() + 0x72b PostmasterMain(int, char**) + 0x329a main + 0x617 __libc_start_main + 0xf5 0x55cf616e7647 [2022-05-21 10:52:51.354][24520][][gs_ctl]: gs_stack finished! ``` * Run the following command to obtain the call stacks of all threads: ``` gs_ctl stack -D data_dir ``` In the preceding command, **-D data\_dir** specifies the data directory of the GaussDB process whose call stack needs to be obtained. The following specifies the procedure: 1. Obtain the GaussDB process ID and data directory. ``` ps -ux | more USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND perfadm 308 9.3 10.1 8719348 1649108 ? Sl May20 58:58 /xxx/bin/gaussdb -u 92617 -D /xxx/openGauss/cluster/data1/dn1 -M pending ``` 2. Obtain the call stacks of all threads. ``` [panhongchang@euler_phy_194 panhongchang]$ gs_ctl stack -D /xxx/openGauss/cluster/data1/dn1 [2022-05-21 10:59:44.063][34511][][gs_ctl]: gs_stack start: Thread 0 tid<140409677575616> lwtid<21045> __poll + 0x2d CommWaitPollParam::caller(int (*)(pollfd*, unsigned long, int), unsigned long) + 0x34 int comm_socket_call(CommWaitPollParam*, int (*)(pollfd*, unsigned long, int)) + 0x28 comm_poll(pollfd*, unsigned long, int) + 0xb1 ServerLoop() + 0x72b PostmasterMain(int, char**) + 0x329a main + 0x617 __libc_start_main + 0xf5 0x55cf616e7647 Thread 1 tid<140405343516416> lwtid<21060> __poll + 0x2d WaitLatchOrSocket(Latch volatile*, int, int, long) + 0x29f SysLoggerMain(int) + 0xc86 int GaussDbThreadMain<(knl_thread_role)17>(knl_thread_arg*) + 0x45d InternalThreadFunc(void*) + 0x2d ThreadStarterFunc(void*) + 0xa4 start_thread + 0xc5 clone + 0x6d ``` The remaining call stacks are omitted here. ## Enhancements None ## Constraints 1. This tool is used only for the GaussDB process. Other processes, such as CMS and GTM, are not supported. 2. If you run SQL statements to execute this tool, ensure that the CN and DN processes are running properly and can be connected to execute SQL statements. 3. If gs\_ctl is used, CN and DN processes must be responsive. 4. Concurrency is not supported. In the scenario where the call stacks of all threads are obtained, the call stacks of threads are not at the same time point. 5. A maximum of 128 call stack layers are supported. If there are more than 128 call stack layers, only the top 128 layers are retained. 6. The symbol table is not tripped. (In the current release, **strip –d** is used, and only the debug information is removed. The symbol table is not tripped. If **strip –s** is used, only the pointer can be displayed, and the symbol name cannot be displayed.) 7. Only the **monadmin** and **sysadmin** users can execute this tool using SQL statements. 8. The call stack can be obtained only after the thread has registered the SIGURG signal. 9. For the code segment that shields the operating system SIGUSR2, the call stack cannot be obtained. If no signal slot has been allocated to the thread, the call stack still cannot be obtained. ## Dependencies None --- --- url: /en/docs/latest/characteristic_description/built_in_stack_tool.md --- # Built-in Stack Tool ## Availability This feature is available since 3.0.0. ## Introduction The stack tool is used to obtain the call stack of each thread in the database. It helps database O\&M personnel locate faults such as deadlock and hang. ## Benefits Provides function-level call stack information to improve the efficiency of database kernel O\&M personnel in analyzing and locating faults such as deadlock and hang. ## Description You can use the gs\_stack() function or the gs\_ctl stack tool to obtain the call stacks of threads in the database. 1. gs\_stack() function * Run **select \* from gs\_stack(pid)** to obtain the call stack of a specified thread. ``` openGauss=# select * from gs_stack(139663481165568); gs_stack -------------------------------------------------------------------- __poll + 0x2d + WaitLatchOrSocket(Latch volatile*, int, int, long) + 0x29f + WaitLatch(Latch volatile*, int, long) + 0x2e + JobScheduleMain() + 0x90f + int GaussDbThreadMain<(knl_thread_role)9>(knl_thread_arg*) + 0x456+ InternalThreadFunc(void*) + 0x2d + ThreadStarterFunc(void*) + 0xa4 + start_thread + 0xc5 + clone + 0x6d + (1 row) ``` * Run **select \* from gs\_stack()** to obtain the call stacks of all threads. ``` openGauss=# select * from gs_stack(); -[ RECORD 1 ]------------------------------------------------------------------------------------------------------- tid | 139670364324352 lwtid | 308 stack | __poll + 0x2d | CommWaitPollParam::caller(int (*)(pollfd*, unsigned long, int), unsigned long) + 0x34 | int comm_socket_call(CommWaitPollParam*, int (*)(pollfd*, unsigned long , int)) + 0x28 | comm_poll(pollfd*, unsigned long, int) + 0xb1 | ServerLoop() + 0x72b | PostmasterMain(int, char**) + 0x314e | main + 0x617 | __libc_start_main + 0xf5 | 0x55d38f8db3a7 [ RECORD 2 ]------------------------------------------------------------------------------------------------------- tid | 139664851859200 lwtid | 520 stack | __poll + 0x2d | WaitLatchOrSocket(Latch volatile*, int, int, long) + 0x29f | SysLoggerMain(int) + 0xc86 | int GaussDbThreadMain<(knl_thread_role)17>(knl_thread_arg*) + 0x45d | InternalThreadFunc(void*) + 0x2d | ThreadStarterFunc(void*) + 0xa4 | start_thread + 0xc5 | clone + 0x6d ``` 2. gs\_ctl stack tool * Run the following command to obtain the call stack of a specified thread: ``` gs_ctl stack -D data_dir -I lwtid ``` In the preceding command, **-D data\_dir** specifies the data directory of the GaussDB process whose call stack needs to be obtained, and **-I lwtid** specifies the lwtid of the target thread. You can run the **ls /proc/pid/task/** command to obtain the lwpid. The following specifies the procedure: 1. Obtain the GaussDB process ID and data directory. ``` ps -ux | more USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND perfadm 308 9.3 10.1 8719348 1649108 ? Sl May20 58:58 /xxx/bin/gaussdb -u 92617 -D /xxx/openGauss/cluster/data1/dn1 -M pending ``` 2. Obtain the lwtid based on the process ID. The directory name in the **task** directory is the lwtid. ``` ls /proc/308/task/ 1096 505 522 525 529 532 536 539 542 546 549 552 555 558 561 565 569 575 584 833 923 926 929 932 935 938 ``` 3. Obtain the call stack based on the specified lwtid. ``` gs_ctl stack -D /xxx/openGauss/cluster/data1/dn1 -I 1096 [2022-05-21 10:52:51.354][24520][][gs_ctl]: gs_stack start: tid<140409677575616> lwtid<1096> __poll + 0x2d CommWaitPollParam::caller(int (*)(pollfd*, unsigned long, int), unsigned long) + 0x34 int comm_socket_call(CommWaitPollParam*, int (*)(pollfd*, unsigned long, int)) + 0x28 comm_poll(pollfd*, unsigned long, int) + 0xb1 ServerLoop() + 0x72b PostmasterMain(int, char**) + 0x329a main + 0x617 __libc_start_main + 0xf5 0x55cf616e7647 [2022-05-21 10:52:51.354][24520][][gs_ctl]: gs_stack finished! ``` * Run the following command to obtain the call stacks of all threads: ``` gs_ctl stack -D data_dir ``` In the preceding command, **-D data\_dir** specifies the data directory of the GaussDB process whose call stack needs to be obtained. The following specifies the procedure: 1. Obtain the GaussDB process ID and data directory. ``` ps -ux | more USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND perfadm 308 9.3 10.1 8719348 1649108 ? Sl May20 58:58 /xxx/bin/gaussdb -u 92617 -D /xxx/openGauss/cluster/data1/dn1 -M pending ``` 2. Obtain the call stacks of all threads. ``` [panhongchang@euler_phy_194 panhongchang]$ gs_ctl stack -D /xxx/openGauss/cluster/data1/dn1 [2022-05-21 10:59:44.063][34511][][gs_ctl]: gs_stack start: Thread 0 tid<140409677575616> lwtid<21045> __poll + 0x2d CommWaitPollParam::caller(int (*)(pollfd*, unsigned long, int), unsigned long) + 0x34 int comm_socket_call(CommWaitPollParam*, int (*)(pollfd*, unsigned long, int)) + 0x28 comm_poll(pollfd*, unsigned long, int) + 0xb1 ServerLoop() + 0x72b PostmasterMain(int, char**) + 0x329a main + 0x617 __libc_start_main + 0xf5 0x55cf616e7647 Thread 1 tid<140405343516416> lwtid<21060> __poll + 0x2d WaitLatchOrSocket(Latch volatile*, int, int, long) + 0x29f SysLoggerMain(int) + 0xc86 int GaussDbThreadMain<(knl_thread_role)17>(knl_thread_arg*) + 0x45d InternalThreadFunc(void*) + 0x2d ThreadStarterFunc(void*) + 0xa4 start_thread + 0xc5 clone + 0x6d ``` The remaining call stacks are omitted here. ## Enhancements None ## Constraints 1. This tool is used only for the GaussDB process. Other processes, such as CMS and GTM, are not supported. 2. If you run SQL statements to execute this tool, ensure that the CN and DN processes are running properly and can be connected to execute SQL statements. 3. If gs\_ctl is used, CN and DN processes must be responsive. 4. Concurrency is not supported. In the scenario where the call stacks of all threads are obtained, the call stacks of threads are not at the same time point. 5. A maximum of 128 call stack layers are supported. If there are more than 128 call stack layers, only the top 128 layers are retained. 6. The symbol table is not tripped. (In the current release, **strip –d** is used, and only the debug information is removed. The symbol table is not tripped. If **strip –s** is used, only the pointer can be displayed, and the symbol name cannot be displayed.) 7. Only the **monadmin** and **sysadmin** users can execute this tool using SQL statements. 8. The call stack can be obtained only after the thread has registered the SIGURG signal. 9. For the code segment that shields the operating system SIGUSR2, the call stack cannot be obtained. If no signal slot has been allocated to the thread, the call stack still cannot be obtained. ## Dependencies None --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin_lock.md --- # B数据库锁 如果需要保持数据库数据的一致性,可以使用LOCK TABLES来阻止其他用户修改表。 例如,一个应用需要保证表中的数据在事务的运行过程中不被修改。为实现这个目的,则可以对表使用进行锁定。这样将防止数据不被并发修改。 LOCK TABLES使用后,会让接下来的sql处于事务状态中,所以需要用UNLOCK TABLES手动释放锁并结束事务。 另外如果需要对当前session只允许读的话,那么还可以用FLUSH TABLES WITH READ LOCK实现,之后也需要用UNLOCK TABLES手动结束这个功能。 ## 语法格式 * 上锁 ``` LOCK {TABLE | TABLES} namelist READ/WRITE ``` * 让当前session处于只读表的状态 ``` FLUSH {TABLE | TABLES} WITH READ LOCK ``` * 解锁 ``` UNLOCK {TABLE | TABLES} ``` ## 参数说明 * **namelist** 要锁定的表的名称,可以有多个表。 * **READ/WRITE** 锁的模式。有: * **READ** 读锁,只读取表而不修改的锁模式。 * **WRITE** 写锁,这个模式保证其所有者(事务)是可以访问该表的唯一事务。 * **TABLE | TABLES** 在LOCK TABLES、FLUSH TABLES、UNLOCK TABLES语句中,TABLE和TABLES是同义词。 ## 示例 在执行删除操作时对一个表进行WRITE锁。 ``` --创建示例表格。 openGauss=# CREATE TABLE graderecord ( number INTEGER, name CHAR(20), class CHAR(20), grade INTEGER ); --插入数据。 openGauss=# insert into graderecord values('210101','Alan','21.01',92); --给示例表格。 openGauss=# LOCK TABLES graderecord WRITE; --删除示例表格。 openGauss=# DELETE FROM graderecord WHERE name ='Alan'; openGauss=# UNLOCK TABLES; ``` --- --- url: /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin_lock.md --- # B数据库锁 如果需要保持数据库数据的一致性,可以使用LOCK TABLES来阻止其他用户修改表。 例如,一个应用需要保证表中的数据在事务的运行过程中不被修改。为实现这个目的,则可以对表使用进行锁定。这样将防止数据不被并发修改。 LOCK TABLES使用后,会让接下来的sql处于事务状态中,所以需要用UNLOCK TABLES手动释放锁并结束事务。 另外如果需要对当前session只允许读的话,那么还可以用FLUSH TABLES WITH READ LOCK实现,之后也需要用UNLOCK TABLES手动结束这个功能。 ## 语法格式 * 上锁 ``` LOCK {TABLE | TABLES} namelist READ/WRITE ``` * 让当前session处于只读表的状态 ``` FLUSH {TABLE | TABLES} WITH READ LOCK ``` * 解锁 ``` UNLOCK {TABLE | TABLES} ``` ## 参数说明 * **namelist** 要锁定的表的名称,可以有多个表。 * **READ/WRITE** 锁的模式。有: * **READ** 读锁,只读取表而不修改的锁模式。 * **WRITE** 写锁,这个模式保证其所有者(事务)是可以访问该表的唯一事务。 * **TABLE | TABLES** 在LOCK TABLES、FLUSH TABLES、UNLOCK TABLES语句中,TABLE和TABLES是同义词。 ## 示例 在执行删除操作时对一个表进行WRITE锁。 ``` --创建示例表格。 openGauss=# CREATE TABLE graderecord ( number INTEGER, name CHAR(20), class CHAR(20), grade INTEGER ); --插入数据。 openGauss=# insert into graderecord values('210101','Alan','21.01',92); --给示例表格。 openGauss=# LOCK TABLES graderecord WRITE; --删除示例表格。 openGauss=# DELETE FROM graderecord WHERE name ='Alan'; openGauss=# UNLOCK TABLES; ``` --- --- url: /zh/docs/latest-lite/datavec/integrationcsharp.md --- # C# SDK对接向量数据库 本文介绍如何使用C#语言调用openGauss向量数据库。 ## 环境要求 * 使用`dotnet --version`查看是否安装.NET开发工具,若无,则需安装dotnet-sdk * 安装相关库 ``` dotnet add package Pgvector dotnet add package Npgsql ``` ## 基本操作 ### 1.连接数据库 ```C# public async Task Connect(string connStr) { var dataSourceBuilder = new NpgsqlDataSourceBuilder(connStr); dataSourceBuilder.UseVector(); await using var dataSource = dataSourceBuilder.Build(); var conn = dataSource.OpenConnection(); conn.ReloadTypes(); return conn; } ``` ### 2.创建表 ```C# public async Task CreateTableAsync(NpgsqlConnection conn) { const string create = "CREATE TABLE items (id serial PRIMARY KEY, embedding vector(3))"; await using var cmd = new NpgsqlCommand(create, conn); await cmd.ExecuteNonQueryAsync(); } ``` ### 3.创建索引 ```C# public async Task CreateIndexAsync(NpgsqlConnection conn) { const string createIndex = "CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)"; await using var cmd = new NpgsqlCommand(createIndex, conn); await cmd.ExecuteNonQueryAsync(); } ``` ### 4.插入/删除/更新数据 * 批量插入 ```C# public async Task InsertDataAsync(NpgsqlConnection conn, Vector vector) { const string insert = "INSERT INTO items (embedding) VALUES ($1)"; await using var cmd = new NpgsqlCommand(insert, conn); cmd.Parameters.AddWithValue(vector); await cmd.ExecuteNonQueryAsync(); } ``` * 删除 ```C# public async Task DeleteDataAsync(NpgsqlConnection conn, int id) { const string delete = "DELETE FROM items WHERE id = $1"; await using var cmd = new NpgsqlCommand(delete, conn); cmd.Parameters.AddWithValue(id); await cmd.ExecuteNonQueryAsync(); } ``` * 更新 ```C# public async Task UpdateDataAsync(NpgsqlConnection conn, Vector vector, int id) { const string update = "UPDATE items SET embedding = $1 WHERE id = $2"; await using var cmd = new NpgsqlCommand(update, conn); cmd.Parameters.AddWithValue(vector).DataTypeName = "vector"; cmd.Parameters.AddWithValue(id); await cmd.ExecuteNonQueryAsync(); } ``` ### 5.查询 ```C# public async Task> QueryAsync(NpgsqlConnection conn, Vector vector, int limit) { const string query = "SELECT * FROM items ORDER BY embedding <-> $1 LIMIT $2" await using var cmd = new NpgsqlCommand(query, conn); cmd.Parameters.AddWithValue(vector).DataTypeName = "vector"; cmd.Parameters.AddWithValue(limit); var results = new System.Collections.Generic.List<(int, Vector)>(); await using var reader = await cmd.ExecuteReaderAsync(); while (await reader.ReadAsync()) { var id = reader.GetInt32(0); var embedding = (Vector)reader.GetValue(1); results.Add((id, embedding)); } return results; } ``` ### 6.删除表 ```C# public async Task DropTableAsync(NpgsqlConnection conn) { const string drop = "DROP TABLE IF EXISTS items"; await using var cmd = new NpgsqlCommand(drop, conn); await cmd.ExecuteNonQueryAsync(); } ``` ### 7.关闭连接 ```C# public async Task CloseConnectionAsync(NpgsqlConnection conn) { if(conn != null) { await conn.CloseAsync(); await conn.DisposeAsync(); } } ``` ## 用例 ```C# using System; using Pgvector; using Npgsql; namespace Demo { public class Program { public static async Task Main(string[] args) { var connstr = "Host=localhost;Database=Yourdb;Port=Yourport;Username=Yourname;Password=YourPassword"; var dbHandler = new Program(); var conn = await dbHandler.Connect(connstr); await dbHandler.CreateTableAsync(conn); await dbHandler.CreateIndexAsync(conn); var vectorq = new Vector(new float[] {1, 1, 1}); await dbHandler.InsertDataAsync(conn, vectorq); var results = await dbHandler.QueryAsync(conn, vectorq, 10); await dbHandler.CloseConnectionAsync(conn); } } } ``` --- --- url: /zh/docs/latest/datavec/integration_csharp.md --- # C# SDK对接向量数据库 本文介绍如何使用C#语言调用openGauss向量数据库。 ## 环境要求 * 使用`dotnet --version`查看是否安装.NET开发工具,若无,则需安装dotnet-sdk * 安装相关库 ``` dotnet add package Pgvector dotnet add package Npgsql ``` ## 基本操作 ### 1.连接数据库 ```C# public async Task Connect(string connStr) { var dataSourceBuilder = new NpgsqlDataSourceBuilder(connStr); dataSourceBuilder.UseVector(); await using var dataSource = dataSourceBuilder.Build(); var conn = dataSource.OpenConnection(); conn.ReloadTypes(); return conn; } ``` ### 2.创建表 ```C# public async Task CreateTableAsync(NpgsqlConnection conn) { const string create = "CREATE TABLE items (id serial PRIMARY KEY, embedding vector(3))"; await using var cmd = new NpgsqlCommand(create, conn); await cmd.ExecuteNonQueryAsync(); } ``` ### 3.创建索引 ```C# public async Task CreateIndexAsync(NpgsqlConnection conn) { const string createIndex = "CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)"; await using var cmd = new NpgsqlCommand(createIndex, conn); await cmd.ExecuteNonQueryAsync(); } ``` ### 4.插入/删除/更新数据 * 批量插入 ```C# public async Task InsertDataAsync(NpgsqlConnection conn, Vector vector) { const string insert = "INSERT INTO items (embedding) VALUES ($1)"; await using var cmd = new NpgsqlCommand(insert, conn); cmd.Parameters.AddWithValue(vector); await cmd.ExecuteNonQueryAsync(); } ``` * 删除 ```C# public async Task DeleteDataAsync(NpgsqlConnection conn, int id) { const string delete = "DELETE FROM items WHERE id = $1"; await using var cmd = new NpgsqlCommand(delete, conn); cmd.Parameters.AddWithValue(id); await cmd.ExecuteNonQueryAsync(); } ``` * 更新 ```C# public async Task UpdateDataAsync(NpgsqlConnection conn, Vector vector, int id) { const string update = "UPDATE items SET embedding = $1 WHERE id = $2"; await using var cmd = new NpgsqlCommand(update, conn); cmd.Parameters.AddWithValue(vector).DataTypeName = "vector"; cmd.Parameters.AddWithValue(id); await cmd.ExecuteNonQueryAsync(); } ``` ### 5.查询 ```C# public async Task> QueryAsync(NpgsqlConnection conn, Vector vector, int limit) { const string query = "SELECT * FROM items ORDER BY embedding <-> $1 LIMIT $2" await using var cmd = new NpgsqlCommand(query, conn); cmd.Parameters.AddWithValue(vector).DataTypeName = "vector"; cmd.Parameters.AddWithValue(limit); var results = new System.Collections.Generic.List<(int, Vector)>(); await using var reader = await cmd.ExecuteReaderAsync(); while (await reader.ReadAsync()) { var id = reader.GetInt32(0); var embedding = (Vector)reader.GetValue(1); results.Add((id, embedding)); } return results; } ``` ### 6.删除表 ```C# public async Task DropTableAsync(NpgsqlConnection conn) { const string drop = "DROP TABLE IF EXISTS items"; await using var cmd = new NpgsqlCommand(drop, conn); await cmd.ExecuteNonQueryAsync(); } ``` ### 7.关闭连接 ```C# public async Task CloseConnectionAsync(NpgsqlConnection conn) { if(conn != null) { await conn.CloseAsync(); await conn.DisposeAsync(); } } ``` ## 用例 ```C# using System; using Pgvector; using Npgsql; namespace Demo { public class Program { public static async Task Main(string[] args) { var connstr = "Host=localhost;Database=Yourdb;Port=Yourport;Username=Yourname;Password=YourPassword"; var dbHandler = new Program(); var conn = await dbHandler.Connect(connstr); await dbHandler.CreateTableAsync(conn); await dbHandler.CreateIndexAsync(conn); var vectorq = new Vector(new float[] {1, 1, 1}); await dbHandler.InsertDataAsync(conn, vectorq); var results = await dbHandler.QueryAsync(conn, vectorq, 10); await dbHandler.CloseConnectionAsync(conn); } } } ``` --- --- url: /zh/docs/latest-lite/datavec/integrationcpp.md --- # C++ SDK对接向量数据库 本文介绍如何使用C++语言调用openGauss向量数据库 ## 环境准备 * g++ * libpq库\ 详见[基于libpq开发流程](https://docs.opengauss.org/zh/docs/latest-lite/developer_guide/development_process_libpq.html)。 ## 基本操作 ### 1.连接数据库 ```cpp #include #include #include #include #include #include class OpenGaussManager { private: PGconn* conn; // 转义标识符(表名、列名等) std::string escape_identifier(const std::string& identifier) { char* escaped = PQescapeIdentifier(conn, identifier.c_str(), identifier.size()); if (!escaped) throw std::runtime_error(PQerrorMessage(conn)); std::string result(escaped); PQfreemem(escaped); return result; } // 执行SQL并检查结果 void execute_sql(const std::string& sql) { PGresult* res = PQexec(conn, sql.c_str()); if (PQresultStatus(res) != PGRES_COMMAND_OK) { std::string err = PQerrorMessage(conn); PQclear(res); throw std::runtime_error("SQL error: " + err); } PQclear(res); } // 将vector转为PostgreSQL数组格式 std::string vector_to_string(const std::vector& vec) { std::ostringstream oss; oss << "'["; for (size_t i = 0; i < vec.size(); ++i) { if (i > 0) oss << ","; oss << vec[i]; } oss << "]'"; return oss.str(); } public: // 构造函数(仅初始化连接指针) OpenGaussManager(const std::string& conninfo){ conn = PQconnectdb(conninfo.c_str()); if (PQstatus(conn) != CONNECTION_OK) { std::cerr << "Connection failed: " << PQerrorMessage(conn) << std::endl; PQfinish(conn); conn = nullptr; } } // 析构函数(确保释放连接) ~OpenGaussManager() { disconnectDB(); } //其它方法 }; ``` ### 2.创建表 ```cpp void create_table(const std::string& table_name, int vector_dim) { std::string sql = "CREATE TABLE IF NOT EXISTS public." + escape_identifier(table_name) + " (id BIGINT PRIMARY KEY, " + "embedding vector(" + std::to_string(vector_dim) + "))"; execute_sql(sql); } ``` ### 3.创建索引 ```cpp void create_index(const std::string& table_name) { std::string sql = "CREATE INDEX ON " + escape_identifier(table_name) + "USING hnsw(embedding vector_l2_ops);"; execute_sql(sql); } ``` ### 4.插入/删除/更新数据 * 插入 ```cpp void insert(const std::string& table_name, int id, const std::vector& embedding) { std::string sql = "INSERT INTO public." + escape_identifier(table_name) + " (id, embedding) VALUES (" + std::to_string(id) + ", " + vector_to_string(embedding) + ")"; execute_sql(sql); } ``` * 删除 ```cpp int delete_by_id(const std::string& table_name, int id) { std::string sql = "DELETE FROM public." + escape_identifier(table_name) + " WHERE id = " + std::to_string(id) + " RETURNING id"; PGresult* res = PQexec(conn, sql.c_str()); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); throw std::runtime_error("Delete failed: " + std::string(PQerrorMessage(conn))); } int deleted_count = PQntuples(res); PQclear(res); return deleted_count; } ``` * 更新 ```cpp void update(const std::string& table_name, int id, const std::vector& embedding) { std::string sql = "UPDATE public." + escape_identifier(table_name) + " SET embedding = " + vector_to_string(embedding) + " WHERE id = " + std::to_string(id); execute_sql(sql); } ``` ### 5.查询 ```cpp std::vector>> select( const std::string& table_name, const std::vector& query_vec, int topk = 10 ) { std::vector>> results; std::string sql = "SELECT id, embedding FROM public." + escape_identifier(table_name) + " ORDER BY embedding <-> " + vector_to_string(query_vec) + " LIMIT " + std::to_string(topk); PGresult* res = PQexec(conn, sql.c_str()); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); throw std::runtime_error("Query failed: " + std::string(PQerrorMessage(conn))); } // 解析结果 int rows = PQntuples(res); for (int i = 0; i < rows; ++i) { // 解析ID int id = std::stoi(PQgetvalue(res, i, 0)); // 解析vector std::vector vec; std::string vec_str = PQgetvalue(res, i, 1); std::istringstream iss(vec_str.substr(1, vec_str.size() -2)); std::string val; while (std::getline(iss, val, ',')) { vec.push_back(std::stof(val)); } results.emplace_back(id, vec); } PQclear(res); return results; } ``` ### 6.删除表 ```cpp void drop_table(const std::string& table_name, bool cascade = false) { std::string sql = "DROP TABLE IF EXISTS public." + escape_identifier(table_name) + (cascade ? " CASCADE" : ""); execute_sql(sql); execute_sql("COMMIT"); } ``` ### 7.关闭连接 ```cpp void disconnectDB() { if (conn != nullptr) { PQfinish(conn); conn = nullptr; } } ``` ### 8.多向量并发查询 多向量召回支持在单次搜索请求中同时提交多个查询向量,openGauss将并行对查询向量进行搜索,并返回多组结果。 #### 函数名 ```cpp PGresult **PQexecMultiSearchParams(const char *connParams, const char *queryTemplate, const QueryParams *queryParams, const int queryCount, const char *preExecForConn, int threadCount) ``` #### 输入参数 * connParams:数据库连接配置,包含host、dbname、user、password、port * queryTemplate:查询语句,要求是单条查询语句(select为首单词)、包含向量操作符(<->/<=>/<#>/<+>/<~>/<%>) * queryParams:查询参数,要求不为空 * queryCount:查询请求个数 * preExecForConn:设置连接参数的sql语句,如:"set hnsw\_ef\_search=200;" * threadCount:连接池最大连接数,和数据库最大连接数(由参数max\_connections设置)有关,一般来说,连接池最大连接数要小于数据库最大连接数,但是数据库对于管理员用户的连接限制会略超过max\_connections设置。 #### 输出参数 * 查询结果,PGresult\*类型数组,形式为\[\[\[id:1, vector:\[1,2,3]], \[id:2 vector:\[4,5,6]],...], \[\[id:3, vector:\[1,2,2]], \[id:2 vector:\[4,5,6]],...], ...],表示n个查询向量对应的limit个结果,解析方式参考示例。 #### 使用案例 ```cpp #include #include #include #include #include #include const char *get_example_vector(int index) { static const char *vectors[] = { "[0.12, 0.34, 0.56]", "[4, 5, 6]" }; return vectors[index % 2]; } int main() { const char *conn_params = "host=127.0.0.1 dbname=postgres user=test password=yourpassword port=5432"; const int num_connections = 2; int success_count = 0; const char *query_template = "select id, embedding from vectors order by embedding <-> $1 limit 2;"; const char *preExec = "set enable_seqscan=true;"; int num_vectors = 2; QueryParams query_params[num_vectors]; const char *param_values[num_vectors][1]; for (int i = 0; i < num_vectors; i++) { param_values[i][0] = get_example_vector(i); query_params[i].paramCount = 1; query_params[i].paramValues = param_values[i]; query_params[i].paramLengths = NULL; query_params[i].paramFormats = NULL; query_params[i].resultFormat = 0; } PGresult **results = PQexecMultiSearchParams(conn_params, query_template, query_params, num_vectors, preExec, num_connections); if (!results) { printf("search error!\n"); } for (int i = 0; i < num_vectors; i++) { PGresult *res = results[i]; if (!res) { std::cout << "result is invalid, query id:" << i << std::endl; continue; } ExecStatusType status = PQresultStatus(res); int rows = PQntuples(res); int cols = PQnfields(res); std::cout << "search query id:" << i << ", rows:" << rows << ", cols:" << cols << ", status:" << status << ", errMsg:" << PQresultErrorMessage(res) << std::endl; for (int j = 0; j < rows; ++j) { int id = std::stoi(PQgetvalue(res, j, 0)); std::cout << "id:" << id << std::endl; std::vector vec; std::string vec_str = PQgetvalue(res, j, 1); std::istringstream iss(vec_str.substr(1, vec_str.size() - 2)); std::string val; std::cout << "vector: ["; while (std::getline(iss, val, ',')) { vec.push_back(std::stof(val)); std::cout << val << ","; } std::cout << "]" << std::endl; } } PQclearMultiResults(results, num_vectors); return 0; } ``` ## 用例 ```cpp int main() { try { // 1. 连接数据库 OpenGaussManager db("host=127.0.0.1 dbname=vector_db user=admin password=Admin@123 port=5432"); // 2. 创建表(维度为3) db.create_table("image_vectors", 3); std::cout << "Table created successfully." << std::endl; // 3. 插入测试数据 std::vector ids = {1}; std::vector> embeddings = { {0.1f, 0.2f, 0.128f}, }; db.insert("image_vectors", ids[0], embeddings[0]); std::cout << "Inserted " << ids.size() << " vectors." << std::endl; // 4. 查询相似向量 std::vector query_vec = {0.12f, 0.22f, 0.128f}; auto results = db.select("image_vectors", query_vec, 3); std::cout << "Top " << results.size() << " similar vectors:" << std::endl; for (const auto& [id, vec] : results) { std::cout << "ID: " << id << " Vector: ["; for (size_t i = 0; i < std::min(5UL, vec.size()); ++i) { if (i > 0) std::cout << ", "; std::cout << vec[i]; } std::cout << ", ...]" << std::endl; } // 5. 更新向量 std::vector new_vec = {0.15f, 0.25f, 0.128f}; db.update("image_vectors", 1, new_vec); std::cout << "Updated vector with ID=1" << std::endl; // 6. 删除数据 int deleted = db.delete_by_id("image_vectors", 1); std::cout << "Deleted " << deleted << " records" << std::endl; // 7. 清理表 db.drop_table("image_vectors"); std::cout << "Table dropped successfully." << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } ``` 编译并运行: ``` g++ -o test test.cpp -I //include/ -L //lib/ -lpq ./test ``` --- --- url: /zh/docs/latest/datavec/integration_cpp.md --- # C++ SDK对接向量数据库 本文介绍如何使用C++语言调用openGauss向量数据库 ## 环境准备 * g++ * libpq库\ 详见[基于libpq开发流程](https://docs.opengauss.org/zh/docs/latest/developer_guide/development_process_libpq.html)。 ## 基本操作 ### 1.连接数据库 ```cpp #include #include #include #include #include #include class OpenGaussManager { private: PGconn* conn; // 转义标识符(表名、列名等) std::string escape_identifier(const std::string& identifier) { char* escaped = PQescapeIdentifier(conn, identifier.c_str(), identifier.size()); if (!escaped) throw std::runtime_error(PQerrorMessage(conn)); std::string result(escaped); PQfreemem(escaped); return result; } // 执行SQL并检查结果 void execute_sql(const std::string& sql) { PGresult* res = PQexec(conn, sql.c_str()); if (PQresultStatus(res) != PGRES_COMMAND_OK) { std::string err = PQerrorMessage(conn); PQclear(res); throw std::runtime_error("SQL error: " + err); } PQclear(res); } // 将vector转为PostgreSQL数组格式 std::string vector_to_string(const std::vector& vec) { std::ostringstream oss; oss << "'["; for (size_t i = 0; i < vec.size(); ++i) { if (i > 0) oss << ","; oss << vec[i]; } oss << "]'"; return oss.str(); } public: // 构造函数(仅初始化连接指针) OpenGaussManager(const std::string& conninfo){ conn = PQconnectdb(conninfo.c_str()); if (PQstatus(conn) != CONNECTION_OK) { std::cerr << "Connection failed: " << PQerrorMessage(conn) << std::endl; PQfinish(conn); conn = nullptr; } } // 析构函数(确保释放连接) ~OpenGaussManager() { disconnectDB(); } //其它方法 }; ``` ### 2.创建表 ```cpp void create_table(const std::string& table_name, int vector_dim) { std::string sql = "CREATE TABLE IF NOT EXISTS public." + escape_identifier(table_name) + " (id BIGINT PRIMARY KEY, " + "embedding vector(" + std::to_string(vector_dim) + "))"; execute_sql(sql); } ``` ### 3.创建索引 ```cpp void create_index(const std::string& table_name) { std::string sql = "CREATE INDEX ON " + escape_identifier(table_name) + "USING hnsw(embedding vector_l2_ops);"; execute_sql(sql); } ``` ### 4.插入/删除/更新数据 * 插入 ```cpp void insert(const std::string& table_name, int id, const std::vector& embedding) { std::string sql = "INSERT INTO public." + escape_identifier(table_name) + " (id, embedding) VALUES (" + std::to_string(id) + ", " + vector_to_string(embedding) + ")"; execute_sql(sql); } ``` * 删除 ```cpp int delete_by_id(const std::string& table_name, int id) { std::string sql = "DELETE FROM public." + escape_identifier(table_name) + " WHERE id = " + std::to_string(id) + " RETURNING id"; PGresult* res = PQexec(conn, sql.c_str()); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); throw std::runtime_error("Delete failed: " + std::string(PQerrorMessage(conn))); } int deleted_count = PQntuples(res); PQclear(res); return deleted_count; } ``` * 更新 ```cpp void update(const std::string& table_name, int id, const std::vector& embedding) { std::string sql = "UPDATE public." + escape_identifier(table_name) + " SET embedding = " + vector_to_string(embedding) + " WHERE id = " + std::to_string(id); execute_sql(sql); } ``` ### 5.查询 ```cpp std::vector>> select( const std::string& table_name, const std::vector& query_vec, int topk = 10 ) { std::vector>> results; std::string sql = "SELECT id, embedding FROM public." + escape_identifier(table_name) + " ORDER BY embedding <-> " + vector_to_string(query_vec) + " LIMIT " + std::to_string(topk); PGresult* res = PQexec(conn, sql.c_str()); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); throw std::runtime_error("Query failed: " + std::string(PQerrorMessage(conn))); } // 解析结果 int rows = PQntuples(res); for (int i = 0; i < rows; ++i) { // 解析ID int id = std::stoi(PQgetvalue(res, i, 0)); // 解析vector std::vector vec; std::string vec_str = PQgetvalue(res, i, 1); std::istringstream iss(vec_str.substr(1, vec_str.size() -2)); std::string val; while (std::getline(iss, val, ',')) { vec.push_back(std::stof(val)); } results.emplace_back(id, vec); } PQclear(res); return results; } ``` ### 6.删除表 ```cpp void drop_table(const std::string& table_name, bool cascade = false) { std::string sql = "DROP TABLE IF EXISTS public." + escape_identifier(table_name) + (cascade ? " CASCADE" : ""); execute_sql(sql); execute_sql("COMMIT"); } ``` ### 7.关闭连接 ```cpp void disconnectDB() { if (conn != nullptr) { PQfinish(conn); conn = nullptr; } } ``` ### 8.多向量并发查询 多向量召回支持在单次搜索请求中同时提交多个查询向量,openGauss将并行对查询向量进行搜索,并返回多组结果。 #### 函数名 ```cpp PGresult **PQexecMultiSearchParams(const char *connParams, const char *queryTemplate, const QueryParams *queryParams, const int queryCount, const char *preExecForConn, int threadCount) ``` #### 输入参数 * connParamsi:数据库连接配置,包含host、dbname、user、password、port * queryTemplate:查询语句,要求是单条查询语句(select为首单词)、包含向量操作符(<->/<=>/<#>/<+>/<~>/<%>) * queryParams:查询参数,要求不为空 * queryCount:查询请求个数 * preExecForConn:设置连接参数的sql语句,如:"set hnsw\_ef\_search=200;" * threadCount:连接池最大连接数,和数据库最大连接数(由参数max\_connections设置)有关,一般来说,连接池最大连接数要小于数据库最大连接数,但是数据库对于管理员用户的连接限制会略超过max\_connections设置。 #### 输出参数 * 查询结果,PGresult\*类型数组,形式为\[\[\[id:1, vector:\[1,2,3]], \[id:2 vector:\[4,5,6]],...], \[\[id:3, vector:\[1,2,2]], \[id:2 vector:\[4,5,6]],...], ...],表示n个查询向量对应的limit个结果,解析方式参考示例。 #### 使用案例 ```cpp #include #include #include #include #include #include const char *get_example_vector(int index) { static const char *vectors[] = { "[0.12, 0.34, 0.56]", "[4, 5, 6]" }; return vectors[index % 2]; } int main() { const char *conn_params = "host=127.0.0.1 dbname=postgres user=test password=yourpassword port=5432"; const int num_connections = 2; int success_count = 0; const char *query_template = "select id, embedding from vectors order by embedding <-> $1 limit 2;"; const char *preExec = "set enable_seqscan=true;"; int num_vectors = 2; QueryParams query_params[num_vectors]; const char *param_values[num_vectors][1]; for (int i = 0; i < num_vectors; i++) { param_values[i][0] = get_example_vector(i); query_params[i].paramCount = 1; query_params[i].paramValues = param_values[i]; query_params[i].paramLengths = NULL; query_params[i].paramFormats = NULL; query_params[i].resultFormat = 0; } PGresult **results = PQexecMultiSearchParams(conn_params, query_template, query_params, num_vectors, preExec, num_connections); if (!results) { printf("search error!\n"); } for (int i = 0; i < num_vectors; i++) { PGresult *res = results[i]; if (!res) { std::cout << "result is invalid, query id:" << i << std::endl; continue; } ExecStatusType status = PQresultStatus(res); int rows = PQntuples(res); int cols = PQnfields(res); std::cout << "search query id:" << i << ", rows:" << rows << ", cols:" << cols << ", status:" << status << ", errMsg:" << PQresultErrorMessage(res) << std::endl; for (int j = 0; j < rows; ++j) { int id = std::stoi(PQgetvalue(res, j, 0)); std::cout << "id:" << id << std::endl; std::vector vec; std::string vec_str = PQgetvalue(res, j, 1); std::istringstream iss(vec_str.substr(1, vec_str.size() - 2)); std::string val; std::cout << "vector: ["; while (std::getline(iss, val, ',')) { vec.push_back(std::stof(val)); std::cout << val << ","; } std::cout << "]" << std::endl; } } PQclearMultiResults(results, num_vectors); return 0; } ``` ## 用例 ```cpp int main() { try { // 1. 连接数据库 OpenGaussManager db("host=127.0.0.1 dbname=vector_db user=admin password=xxxxxx port=5432"); // 2. 创建表(维度为3) db.create_table("image_vectors", 3); std::cout << "Table created successfully." << std::endl; // 3. 插入测试数据 std::vector ids = {1}; std::vector> embeddings = { {0.1f, 0.2f, 0.128f}, }; db.insert("image_vectors", ids[0], embeddings[0]); std::cout << "Inserted " << ids.size() << " vectors." << std::endl; // 4. 查询相似向量 std::vector query_vec = {0.12f, 0.22f, 0.128f}; auto results = db.select("image_vectors", query_vec, 3); std::cout << "Top " << results.size() << " similar vectors:" << std::endl; for (const auto& [id, vec] : results) { std::cout << "ID: " << id << " Vector: ["; for (size_t i = 0; i < std::min(5UL, vec.size()); ++i) { if (i > 0) std::cout << ", "; std::cout << vec[i]; } std::cout << ", ...]" << std::endl; } // 5. 更新向量 std::vector new_vec = {0.15f, 0.25f, 0.128f}; db.update("image_vectors", 1, new_vec); std::cout << "Updated vector with ID=1" << std::endl; // 6. 删除数据 int deleted = db.delete_by_id("image_vectors", 1); std::cout << "Deleted " << deleted << " records" << std::endl; // 7. 清理表 db.drop_table("image_vectors"); std::cout << "Table dropped successfully." << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } ``` 编译并运行: ```cpp g++ -o test test.cpp -I //include/ -L //lib/ -lpq ./test ``` --- --- url: /en/docs/latest-lite/sql_reference/cache_io_stats.md --- # Cache IO Stats Cache IO Stats contains two tables: User table and User index. The columns in the tables are described as follows. ## User table IO activity ordered by heap blks hit ratio **Table 1** Columns in the User table IO activity ordered by heap blks hit ratio report ## User index IO activity ordered by idx blks hit ratio **Table 2** Columns in the User index IO activity ordered by idx blks hit ratio report --- --- url: /en/docs/latest/sql_reference/cache_io_stats.md --- # Cache IO Stats Cache IO Stats contains two tables: User table and User index. The columns in the tables are described as follows. ## User table IO activity ordered by heap blks hit ratio **Table 1** Columns in the User table IO activity ordered by heap blks hit ratio report ## User index IO activity ordered by idx blks hit ratio **Table 2** Columns in the User index IO activity ordered by idx blks hit ratio report --- --- url: /zh/docs/latest-lite/sql_reference/cache_io_stats.md --- # Cache IO Stats Cache IO Stats包含User table和User index两张表,列名称及描述如下所示。 ## User table IO activity ordered by heap blks hit ratio **表 1** User table IO activity ordered by heap blks hit ratio报表主要内容 ## User index IO activity ordered by idx blks hit ratio **表 2** User index IO activity ordered by idx blks hit ratio报表主要内容 --- --- url: /zh/docs/latest/sql_reference/cache_io_stats.md --- # Cache IO Stats Cache IO Stats包含User table和User index两张表,列名称及描述如下所示。 ## User table IO activity ordered by heap blks hit ratio **表 1** User table IO activity ordered by heap blks hit ratio报表主要内容 ## User index IO activity ordered by idx blks hit ratio **表 2** User index IO activity ordered by idx blks hit ratio报表主要内容 --- --- url: /en/docs/latest-lite/sql_reference/call.md --- # CALL ## Function **CALL** calls defined functions and stored procedures. ## Precautions The owner of a function or stored procedure, users granted with the **EXECUTE** permission on the function or stored procedure, or users granted with the **EXECUTE ANY FUNCTION** permission can call the function or stored procedure. The system administrator has the permission to call the function or stored procedure by default. ## Syntax ``` CALL [schema.|package.] {func_name| procedure_name} ( param_expr ); ``` ## Parameter Description * **schema** Specifies the name of the schema where a function or stored procedure is located. * package Specifies the name of the package where a function or stored procedure is located. * **func\_name** Specifies the name of the function or stored procedure to be called. Value range: an existing function name. * **param\_expr** Specifies a list of parameters. Use := or => to separate a parameter name and its value. This method allows parameters to be placed in any order. If only parameter values are in the list, the value order must be the same as that defined in the function or stored procedure. Value range: an existing function parameter name or stored procedure parameter name. > \[!NOTE]NOTE > > The parameters include input parameters (whose name and type are separated by IN) and output parameters (whose name and type are separated by OUT). When you run the **CALL** statement to call a function or stored procedure, the parameter list must contain an output parameter for non-overloaded functions. You can set the output parameter to a variable or any constant. For details, see [Examples](#en-us_topic_0283137636_en-us_topic_0237122088_en-us_topic_0059778236_s299dc001fa4b48cd9b56412a73db23c0). For an overloaded package function, the parameter list can have no output parameter, but the function may not be found. If an output parameter is contained, it must be a constant. ## Examples ``` -- Create the func_add_sql function, calculate the sum of two integers, and return the result. openGauss=# CREATE FUNCTION func_add_sql(num1 integer, num2 integer) RETURN integer AS BEGIN RETURN num1 + num2; END; / -- Transfer by parameter value. openGauss=# CALL func_add_sql(1, 3); -- Transfer by naming tag method. openGauss=# CALL func_add_sql(num1 => 1,num2 => 3); openGauss=# CALL func_add_sql(num2 := 2, num1 := 3); -- Delete the function. openGauss=# DROP FUNCTION func_add_sql; -- Create a function with output parameters. openGauss=# CREATE FUNCTION func_increment_sql(num1 IN integer, num2 IN integer, res OUT integer) RETURN integer AS BEGIN res := num1 + num2; END; / -- Set output parameters to constants. openGauss=# CALL func_increment_sql(1,2,1); -- Delete the function. openGauss=# DROP FUNCTION func_increment_sql; ``` --- --- url: /en/docs/latest/sql_reference/call.md --- # CALL ## Function **CALL** calls defined functions and stored procedures. ## Precautions The owner of a function or stored procedure, users granted with the **EXECUTE** permission on the function or stored procedure, or users granted with the **EXECUTE ANY FUNCTION** permission can call the function or stored procedure. The system administrator has the permission to call the function or stored procedure by default. ## Syntax ``` CALL [schema.|package.] {func_name| procedure_name} ( param_expr ); ``` ## Parameter Description * **schema** Specifies the name of the schema where a function or stored procedure is located. * package Specifies the name of the package where a function or stored procedure is located. * **func\_name** Specifies the name of the function or stored procedure to be called. Value range: an existing function name. * **param\_expr** Specifies a list of parameters. Use := or => to separate a parameter name and its value. This method allows parameters to be placed in any order. If only parameter values are in the list, the value order must be the same as that defined in the function or stored procedure. Value range: an existing function parameter name or stored procedure parameter name. > \[!NOTE]NOTE > The parameters include input parameters (whose name and type are separated by IN) and output parameters (whose name and type are separated by OUT). When you run the **CALL** statement to call a function or stored procedure, the parameter list must contain an output parameter for non-overloaded functions. You can set the output parameter to a variable or any constant. For details, see [Examples](#en-us_topic_0283137636_en-us_topic_0237122088_en-us_topic_0059778236_s299dc001fa4b48cd9b56412a73db23c0). For an overloaded package function, the parameter list can have no output parameter, but the function may not be found. If an output parameter is contained, it must be a constant. ## Examples ``` -- Create the func_add_sql function, calculate the sum of two integers, and return the result. openGauss=# CREATE FUNCTION func_add_sql(num1 integer, num2 integer) RETURN integer AS BEGIN RETURN num1 + num2; END; / -- Transfer by parameter value. openGauss=# CALL func_add_sql(1, 3); -- Transfer by naming tag method. openGauss=# CALL func_add_sql(num1 => 1,num2 => 3); openGauss=# CALL func_add_sql(num2 := 2, num1 := 3); -- Delete the function. openGauss=# DROP FUNCTION func_add_sql; -- Create a function with output parameters. openGauss=# CREATE FUNCTION func_increment_sql(num1 IN integer, num2 IN integer, res OUT integer) RETURN integer AS BEGIN res := num1 + num2; END; / -- Set output parameters to constants. openGauss=# CALL func_increment_sql(1,2,1); -- Delete the function. openGauss=# DROP FUNCTION func_increment_sql; ``` --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CALL.md --- # CALL ## 功能描述 使用CALL命令可以调用已定义的函数和存储过程。 ## 注意事项 相比于原始的openGauss,dolphin对于CALL语法的修改为: 1. 可以使用CALL语法调用含有查询语句的存储过程。 2. 可以MySQL 5.7.x的客户端工具,mysql-connector-java-5.1.47使用CALL语法调用含有查询语句的存储过程。 ## 语法格式 ``` CALL [schema.|package.] {func_name| procedure_name} ( param_expr ); ``` ## 参数说明 * **schema** 函数或存储过程所在的模式名称。 * **package** 函数或存储过程所在的package名称。 * **func\_name** 所调用函数或存储过程的名称。 取值范围:已存在的函数名称。 * **param\_expr** 参数列表可以用符号“:=”或者“=>”将参数名和参数值隔开,这种方法的好处是参数可以以任意顺序排列。若参数列表中仅出现参数值,则参数值的排列顺序必须和函数或存储过程定义时的相同。 取值范围:已存在的函数参数名称或存储过程参数名称。 > \[!NOTE]说明 > 当开启参数dolphin.sql\_mode 为 'block\_return\_multi\_results' 使用call调用存储存储过程或者函数时会有以下限制: * 必须使用用户自定义变量作为输出参数。 * 只能支持调用plpgsql语言的存储过程。 ## 示例 ``` --设置参数 openGauss=# set dolphin.sql_mode = 'block_return_multi_results'; --创建一个存储过程,返回多个查询语句的结果。 openGauss=# CREATE PROCEDURE proc_a_2 () as begin select * from t; select * from test_1; end; / --调用存储过程。 openGauss=# call proc_a_2(); ``` ## 相关链接 [CALL](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/CALL.html) --- --- url: /zh/docs/latest-lite/sql_reference/call.md --- # CALL ## 功能描述 使用CALL命令可以调用已定义的函数和存储过程。 ## 注意事项 函数或存储过程的所有者、被授予了函数或存储过程EXECUTE权限的用户或被授予EXECUTE ANY FUNCTION权限的用户有权调用函数或存储过程,系统管理员默认拥有此权限。 ## 语法格式 ``` CALL [schema.|package.] {func_name| procedure_name} ( param_expr ); ``` ## 参数说明 * **schema** 函数或存储过程所在的模式名称。 * package 函数或存储过程所在的package名称。 * **func\_name** 所调用函数或存储过程的名称。 取值范围:已存在的函数名称。 * **param\_expr** 参数列表可以用符号 “:=”或者“=>”将参数名和参数值隔开,这种方法的好处是参数可以以任意顺序排列。若参数列表中仅出现参数值,则参数值的排列顺序必须和函数或存储过程定义时的相同。 取值范围:已存在的函数参数名称或存储过程参数名称。 > \[!NOTE]说明 > 参数可以包含入参(参数名和类型之间指定“IN”关键字)和出参(参数名和类型之间指定“OUT”关键字),使用CALL命令调用函数或存储过程时,对于非重载的函数,参数列表必须包含出参,出参可以传入一个变量或者任一常量。对于重载的package函数,参数列表里可以忽略出参(此处如果想创建只有出参不同入参相同的重载函数,需要set behavior\_compat\_options ="proc\_outparam\_override" > ),忽略出参时可能会导致函数找不到,因为其本质是调用了另一个同名的不含出参的重载函数。包含出参时,出参只能是常量。以上两种情况详见[示例](#zh-cn_topic_0283137636_zh-cn_topic_0237122088_zh-cn_topic_0059778236_s299dc001fa4b48cd9b56412a73db23c0) ## 示例 ``` --创建一个函数func_add_sql,计算两个整数的和,并返回结果。 openGauss=# CREATE FUNCTION func_add_sql(num1 integer, num2 integer) RETURN integer AS BEGIN RETURN num1 + num2; END; / --按参数值传递。 openGauss=# CALL func_add_sql(1, 3); --使用命名标记法传参。 openGauss=# CALL func_add_sql(num1 => 1,num2 => 3); openGauss=# CALL func_add_sql(num2 := 2, num1 := 3); --删除函数。 openGauss=# DROP FUNCTION func_add_sql; --创建带出参的函数。 openGauss=# CREATE FUNCTION func_increment_sql(num1 IN integer, num2 IN integer, res OUT integer) RETURN integer AS BEGIN res := num1 + num2; END; / --出参传入常量。 openGauss=# CALL func_increment_sql(1,2,1); --删除函数。 openGauss=# DROP FUNCTION func_increment_sql; --创建package属性的重载函数并通过call调用 openGauss=# set behavior_compat_options ="proc_outparam_override"; openGauss=# CREATE OR REPLACE PACKAGE test_overload IS function testp(a int) return int; function testp(a int, b out int) return int; end test_overload; / openGauss=# create or replace package body test_overload --创建package body is function testp(a int) return int is Begin raise notice 'func without out_arg'; return a; end; function testp(a int, b out int) return int is begin b:=1; Raise notice 'func with out_arg'; return 2; end; end test_overload; / openGauss=# call test_overload.testp(1);--调用忽略出参 openGauss=# call test_overload.testp(1,2);--调用包含出参 ``` --- --- url: /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CALL.md --- # CALL ## 功能描述 使用CALL命令可以调用已定义的函数和存储过程。 ## 注意事项 相比于原始的openGauss,dolphin对于CALL语法的修改为: 1. 可以使用CALL语法调用含有查询语句的存储过程。 2. 可以MySQL 5.7.x的客户端工具,mysql-connector-java-5.1.47使用CALL语法调用含有查询语句的存储过程。 ## 语法格式 ``` CALL [schema.|package.] {func_name| procedure_name} ( param_expr ); ``` ## 参数说明 * **schema** 函数或存储过程所在的模式名称。 * **package** 函数或存储过程所在的package名称。 * **func\_name** 所调用函数或存储过程的名称。 取值范围:已存在的函数名称。 * **param\_expr** 参数列表可以用符号“:=”或者“=>”将参数名和参数值隔开,这种方法的好处是参数可以以任意顺序排列。若参数列表中仅出现参数值,则参数值的排列顺序必须和函数或存储过程定义时的相同。 取值范围:已存在的函数参数名称或存储过程参数名称。 > \[!NOTE]说明 > 当开启参数dolphin.sql\_mode 为 'block\_return\_multi\_results' 使用call调用存储存储过程或者函数时会有以下限制: * 必须使用用户自定义变量作为输出参数。 * 只能支持调用plpgsql语言的存储过程。 ## 示例 ``` --设置参数 openGauss=# set dolphin.sql_mode = 'block_return_multi_results'; --创建一个存储过程,返回多个查询语句的结果。 openGauss=# CREATE PROCEDURE proc_a_2 () as begin select * from t; select * from test_1; end; / --调用存储过程。 openGauss=# call proc_a_2(); ``` ## 相关链接 [CALL](https://docs.opengauss.org/zh/docs/latest/sql_reference/call.html) --- --- url: /zh/docs/latest/sql_reference/call.md --- # CALL ## 功能描述 使用CALL命令可以调用已定义的函数和存储过程。 ## 注意事项 函数或存储过程的所有者、被授予了函数或存储过程EXECUTE权限的用户或被授予EXECUTE ANY FUNCTION权限的用户有权调用函数或存储过程,系统管理员默认拥有此权限。 ## 语法格式 ``` CALL [schema.|package.] {func_name| procedure_name} ( param_expr ); ``` ## 参数说明 * **schema** 函数或存储过程所在的模式名称。 * **package** 函数或存储过程所在的package名称。 * **func\_name** 所调用函数或存储过程的名称。 取值范围:已存在的函数名称。 * **param\_expr** 参数列表可以用符号“:=”或者“=>”将参数名和参数值隔开,这种方法的好处是参数可以以任意顺序排列。若参数列表中仅出现参数值,则参数值的排列顺序必须和函数或存储过程定义时的相同。 取值范围:已存在的函数参数名称或存储过程参数名称。 > \[!NOTE]说明 > 参数可以包含入参(参数名和类型之间指定“IN”关键字)和出参(参数名和类型之间指定“OUT”关键字),使用CALL命令调用函数或存储过程时,对于非重载的函数,参数列表必须包含出参,出参可以传入一个变量或者任一常量。对于重载的package函数,参数列表里可以忽略出参(此处如果想创建只有出参不同入参相同的重载函数,需要set behavior\_compat\_options ="proc\_outparam\_override" > ),忽略出参时可能会导致函数找不到,因为其本质是调用了另一个同名的不含出参的重载函数。包含出参时,出参只能是常量。以上两种情况详见[示例](#zh-cn_topic_0283137636_zh-cn_topic_0237122088_zh-cn_topic_0059778236_s299dc001fa4b48cd9b56412a73db23c0) ## 示例 ``` --创建一个函数func_add_sql,计算两个整数的和,并返回结果。 openGauss=# CREATE FUNCTION func_add_sql(num1 integer, num2 integer) RETURN integer AS BEGIN RETURN num1 + num2; END; / --按参数值传递。 openGauss=# CALL func_add_sql(1, 3); --使用命名标记法传参。 openGauss=# CALL func_add_sql(num1 => 1,num2 => 3); openGauss=# CALL func_add_sql(num2 := 2, num1 := 3); --删除函数。 openGauss=# DROP FUNCTION func_add_sql; --创建带出参的函数。 openGauss=# CREATE FUNCTION func_increment_sql(num1 IN integer, num2 IN integer, res OUT integer) RETURN integer AS BEGIN res := num1 + num2; END; / --出参传入常量。 openGauss=# CALL func_increment_sql(1,2,1); --删除函数。 openGauss=# DROP FUNCTION func_increment_sql; --创建package属性的重载函数并通过call调用 openGauss=# set behavior_compat_options ="proc_outparam_override"; openGauss=# CREATE OR REPLACE PACKAGE test_overload IS function testp(a int) return int; function testp(a int, b out int) return int; end test_overload; / openGauss=# create or replace package body test_overload --创建package body is function testp(a int) return int is Begin raise notice 'func without out_arg'; return a; end; function testp(a int, b out int) return int is begin b:=1; Raise notice 'func with out_arg'; return 2; end; end test_overload; / openGauss=# call test_overload.testp(1);--调用忽略出参 openGauss=# call test_overload.testp(1,2);--调用包含出参 ``` --- --- url: /en/docs/latest/sql_reference/call_statement.md --- # Call Statement ## Syntax [Figure 1](#en-us_topic_0237122223_en-us_topic_0059778001_fa4de2ab1dc7e4c04b4997c6238ee1861) shows the syntax diagram for calling a clause. **Figure 1** call\_clause::=\ ![](figures/call_clause.png "call_clause") The above syntax diagram is explained as follows: * **procedure\_name** specifies the name of a stored procedure. * **parameter** specifies the parameters for the stored procedure. You can set no parameter or multiple parameters. ## Example ``` -- Create the stored procedure proc_staffs: postgres=# CREATE OR REPLACE PROCEDURE proc_staffs ( section NUMBER(6), salary_sum out NUMBER(8,2), staffs_count out INTEGER ) IS BEGIN SELECT sum(salary), count(*) INTO salary_sum, staffs_count FROM hr.staffs where section_id = section; END; / -- Invoke a stored procedure proc_return: postgres=# CALL proc_staffs(2,8,6); -- Delete a stored procedure: postgres=# DROP PROCEDURE proc_staffs; ``` --- --- url: /en/docs/latest-lite/sql_reference/call_statements.md --- # Call Statements ## Syntax [Figure 1](#en-us_topic_0283136925_en-us_topic_0237122223_en-us_topic_0059778001_fa4de2ab1dc7e4c04b4997c6238ee1861) shows the syntax diagram for calling a clause. **Figure 1** call\_clause::=\ ![](figures/call_clause.png "call_clause") The above syntax diagram is explained as follows: * **procedure\_name** specifies the name of a stored procedure. * **parameter** specifies the parameters for the stored procedure. You can set no parameter or multiple parameters. ## Examples ``` -- Create the stored procedure proc_staffs. openGauss=# CREATE OR REPLACE PROCEDURE proc_staffs ( section NUMBER(6), salary_sum out NUMBER(8,2), staffs_count out INTEGER ) IS BEGIN SELECT sum(salary), count(*) INTO salary_sum, staffs_count FROM hr.staffs where section_id = section; END; / -- Invoke the stored procedure proc_return. openGauss=# CALL proc_staffs(2,8,6); -- Delete a stored procedure. openGauss=# DROP PROCEDURE proc_staffs; ``` --- --- url: /en/docs/latest/database_administration_guide/cascaded_standby_node.md --- # Cascaded Standby Server ## Availability This feature is available since openGauss 1.1.0. ## Introduction A cascaded standby server can be connected to a standby server based on the one-primary-multiple-standby architecture. ## Benefits The one-primary-multiple-standby architecture cannot support a flexible structure in special service scenarios. The multi-equipment room deployment cannot meet requirements of the complete structure in the HA switchover scenario (three instances in the primary-standby equipment rooms and two or three instances in the standby-standby equipment rooms). If the number of standby servers increases, the primary server may be overloaded. Queries that have low real-time requirements can be implemented on cascaded standby servers. Therefore, the cascading backup capability is required. ## Description The primary server replicates logs to the standby server in synchronous or asynchronous mode. The standby server replicates logs to the cascaded standby server only in asynchronous mode. In the current one-primary-multiple-standby architecture, the primary server uses the WAL sender process (walsender) to replicate logs to the standby server. The standby server uses the WAL receiver process (walreceiver) to receive and then flushes logs to local disks. The standby server reads redo logs to complete data replication between the primary and standby servers. There is a one-to-one mapping between walsender and walreceiver on the primary and standby servers. Logs are sent between the standby and cascaded standby servers in asynchronous mode using walsender and walreceiver, reducing the streaming replication pressure on the primary server. ## Enhancements None ## Constraints * A cascaded standby server can only replicate data from a standby server and cannot directly replicate data from the primary server. * A cascaded standby server does not support data build from a standby server. Currently, data can be built only from the primary server. If the standby server is fully built, the cascaded standby server needs to be fully built. * The cascaded standby node is in asynchronous replication mode. * The cascaded standby server cannot be promoted. * The cascaded standby server cannot be notified. * Currently, the overall architecture of the primary-standby-cascaded standby cluster cannot be queried. You need to find the standby server through the primary server and then find the cascaded standby server based on the standby server. * A cascaded standby server cannot own another cascaded standby server. * When the ultimate RTO is enabled, no cascaded standby server is supported. ## Dependencies None --- --- url: >- /en/docs/latest-lite/performance_tuning_guide/case_adjusting_i_o_parameters_to_reduce_the_log_bloat_rate.md --- # Case: Adjusting I/O Parameters to Reduce the Log Bloat Rate * Parameter values before adjustment: * pagewriter\_sleep=2000ms * bgwriter\_delay=2000ms * max\_io\_capacity=500MB * Parameter values after adjustment: * pagewriter\_sleep=100ms * bgwriter\_delay=1s * max\_io\_capacity=300MB > \[!NOTE]NOTE > > * The **max\_io\_capacity** parameter is set to a small value because the I/O does not use the maximum value of the previous parameter. This parameter is used to limit the upper limit of the I/O usage of the backend write process. > * Log recycling is triggered only when the number of logs reaches a certain value. The formula for calculating the value is as follows: Value of **wal\_keep\_segments** + Value of **checkpoint\_segments** x 2 + 1. If **checkpoint\_segments** is set to **128** and **wal\_keep\_segments** is set to **128**, the number of logs is (128 + 128 x 2 + 1) x 16 MB = 6 GB. > * Before the parameters are adjusted, the Xlogs of different data volumes bloat in different degrees in the TPC-C data export phase. As a result, GB-level logs bloat. The main cause is that dirty pages are not flushed to disks, the recovery point cannot be pushed forward, and logs cannot be recycled in time. After the parameters are adjusted, the log bloat rate decreases significantly. > * Take the data warehouse 2000 as an example. Before the parameter adjustment, the log size bloats by 10 GB in the data export phase. After the parameter adjustment, the log size remains within the range of the minimum xlog value calculated based on the parameter setting. --- --- url: >- /en/docs/latest/performance_tuning_guide/case_adjusting_i_o_parameters_to_reduce_the_log_bloat_rate.md --- # Case: Adjusting I/O Parameters to Reduce the Log Bloat Rate * Parameter values before adjustment: * pagewriter\_sleep=2000ms * bgwriter\_delay=2000ms * max\_io\_capacity=500MB * Parameter values after adjustment: * pagewriter\_sleep=100ms * bgwriter\_delay=1s * max\_io\_capacity=300MB > \[!NOTE]NOTE > > * The **max\_io\_capacity** parameter is set to a small value because the I/O does not use the maximum value of the previous parameter. This parameter is used to limit the upper limit of the I/O usage of the backend write process. > * Log recycling is triggered only when the number of logs reaches a certain value. The formula for calculating the value is as follows: Value of **wal\_keep\_segments** + Value of **checkpoint\_segments** x 2 + 1. If **checkpoint\_segments** is set to 128 and **wal\_keep\_segments** is set to **128**, the number of logs is (128 + 128 x 2 + 1) x 16 MB = 6 GB. > * Before the parameters are adjusted, the Xlogs of different data volumes bloat in different degrees in the TPC-C data export phase. As a result, GB-level logs bloat. The main cause is that dirty pages are not flushed to disks, the recovery point cannot be pushed forward, and logs cannot be recycled in time. After the parameters are adjusted, the log bloat rate decreases significantly. > * Take the 2000 warehouses as an example. Before the parameter adjustment, the log size bloats by 10 GB in the data export phase. After the parameter adjustment, the log size remains within the range of the minimum xlog value calculated based on the parameter setting. --- --- url: >- /en/docs/latest-lite/performance_tuning_guide/case_creating_an_appropriate_index.md --- # Case: Creating an Appropriate Index ## Symptom Query the information about all personnel in the sales department. ``` SELECT staff_id,first_name,last_name,employment_id,state_name,city FROM staffs,sections,states,places WHERE sections.section_name='Sales' AND staffs.section_id = sections.section_id AND sections.place_id = places.place_id AND places.state_id = states.state_id ORDER BY staff_id; ``` ## Optimization Analysis The original execution plan is as follows before creating the **places.place\_id** and **states.state\_id** indexes: ``` QUERY PLAN --------------------------------------------------------------------------------------------------- Sort (cost=129.74..131.18 rows=576 width=136) Sort Key: staffs.staff_id -> Hash Join (cost=70.54..103.33 rows=576 width=136) Hash Cond: (states.state_id = places.state_id) -> Seq Scan on states (cost=0.00..22.38 rows=1238 width=36) -> Hash (cost=69.38..69.38 rows=93 width=108) -> Hash Join (cost=42.41..69.38 rows=93 width=108) Hash Cond: (places.place_id = sections.place_id) -> Seq Scan on places (cost=0.00..21.67 rows=1167 width=40) -> Hash (cost=42.21..42.21 rows=16 width=76) -> Hash Join (cost=24.66..42.21 rows=16 width=76) Hash Cond: (staffs.section_id = sections.section_id) -> Seq Scan on staffs (cost=0.00..15.37 rows=537 width=76) -> Hash (cost=24.59..24.59 rows=6 width=8) -> Seq Scan on sections (cost=0.00..24.59 rows=6 width=8) Filter: (section_name = 'Sales'::text) (16 rows) ``` The optimized execution plan is as follows (two indexes have been created on the **places.place\_id** and **states.state\_id** columns): ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------- Sort (cost=119.76..121.20 rows=576 width=136) Sort Key: staffs.staff_id -> Hash Join (cost=70.14..93.35 rows=576 width=136) Hash Cond: (staffs.section_id = sections.section_id) -> Seq Scan on staffs (cost=0.00..15.37 rows=537 width=76) -> Hash (cost=67.43..67.43 rows=217 width=68) -> Nested Loop (cost=24.66..67.43 rows=217 width=68) -> Hash Join (cost=24.66..51.06 rows=35 width=40) Hash Cond: (places.place_id = sections.place_id) -> Seq Scan on places (cost=0.00..21.67 rows=1167 width=40) -> Hash (cost=24.59..24.59 rows=6 width=8) -> Seq Scan on sections (cost=0.00..24.59 rows=6 width=8) Filter: (section_name = 'Sales'::text) -> Index Scan using states_state_id_idx on states (cost=0.00..0.41 rows=6 width=36) Index Cond: (state_id = places.state_id) (15 rows) ``` --- --- url: /en/docs/latest/performance_tuning_guide/case_creating_an_appropriate_index.md --- # Case: Creating an Appropriate Index ## Symptom Query the information about all personnel in the sales department. ``` SELECT staff_id,first_name,last_name,employment_id,state_name,city FROM staffs,sections,states,places WHERE sections.section_name='Sales' AND staffs.section_id = sections.section_id AND sections.place_id = places.place_id AND places.state_id = states.state_id ORDER BY staff_id; ``` ## Optimization Analysis The original execution plan is as follows before creating the **places.place\_id** and **states.state\_id** indexes: ``` QUERY PLAN --------------------------------------------------------------------------------------------------- Sort (cost=129.74..131.18 rows=576 width=136) Sort Key: staffs.staff_id -> Hash Join (cost=70.54..103.33 rows=576 width=136) Hash Cond: (states.state_id = places.state_id) -> Seq Scan on states (cost=0.00..22.38 rows=1238 width=36) -> Hash (cost=69.38..69.38 rows=93 width=108) -> Hash Join (cost=42.41..69.38 rows=93 width=108) Hash Cond: (places.place_id = sections.place_id) -> Seq Scan on places (cost=0.00..21.67 rows=1167 width=40) -> Hash (cost=42.21..42.21 rows=16 width=76) -> Hash Join (cost=24.66..42.21 rows=16 width=76) Hash Cond: (staffs.section_id = sections.section_id) -> Seq Scan on staffs (cost=0.00..15.37 rows=537 width=76) -> Hash (cost=24.59..24.59 rows=6 width=8) -> Seq Scan on sections (cost=0.00..24.59 rows=6 width=8) Filter: (section_name = 'Sales'::text) (16 rows) ``` The optimized execution plan is as follows (two indexes have been created on the **places.place\_id** and **states.state\_id** columns): ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------- Sort (cost=119.76..121.20 rows=576 width=136) Sort Key: staffs.staff_id -> Hash Join (cost=70.14..93.35 rows=576 width=136) Hash Cond: (staffs.section_id = sections.section_id) -> Seq Scan on staffs (cost=0.00..15.37 rows=537 width=76) -> Hash (cost=67.43..67.43 rows=217 width=68) -> Nested Loop (cost=24.66..67.43 rows=217 width=68) -> Hash Join (cost=24.66..51.06 rows=35 width=40) Hash Cond: (places.place_id = sections.place_id) -> Seq Scan on places (cost=0.00..21.67 rows=1167 width=40) -> Hash (cost=24.59..24.59 rows=6 width=8) -> Seq Scan on sections (cost=0.00..24.59 rows=6 width=8) Filter: (section_name = 'Sales'::text) -> Index Scan using states_state_id_idx on states (cost=0.00..0.41 rows=6 width=36) Index Cond: (state_id = places.state_id) (15 rows) ``` --- --- url: >- /en/docs/latest-lite/performance_tuning_guide/case_modifying_the_guc_parameter_rewrite_rule.md --- # Case: Modifying the GUC Parameter rewrite\_rule **rewrite\_rule** contains multiple query rewriting rules: **magicset**, **partialpush**, **uniquecheck**, **disablerep**, **intargetlist**, and **predpush**. The following describes the application scenarios of some important rules: ## Promoting the Subquery in the Target Column Using intargetlist The query performance can be greatly improved by converting the subquery in the target column to JOIN. The following is an example: ``` openGauss=# set rewrite_rule='none'; SET openGauss=# create table t1(c1 int,c2 int); CREATE TABLE openGauss=# create table t2(c1 int,c2 int); CREATE TABLE openGauss=# explain (verbose on, costs off) select c1,(select avg(c2) from t2 where t2.c2=t1.c2) from t1 where t1.c1<100 order by t1.c2; QUERY PLAN ----------------------------------------------- Sort Output: t1.c1, ((SubPlan 1)), t1.c2 Sort Key: t1.c2 -> Seq Scan on public.t1 Output: t1.c1, (SubPlan 1), t1.c2 Filter: (t1.c1 < 100) SubPlan 1 -> Aggregate Output: avg(t2.c2) -> Seq Scan on public.t2 Output: t2.c1, t2.c2 Filter: (t2.c2 = t1.c2) (12 rows) ``` Because the subquery **(select avg(c2) from t2 where t2.c2=t1.c2)** in the target column cannot be pulled up, execution of the subquery is triggered each time a row of data of **t1** is scanned, and the query efficiency is low. If the **intargetlist** parameter is enabled, the subquery is converted to JOIN to improve the query performance. ``` openGauss=# set rewrite_rule='intargetlist'; SET openGauss=# explain (verbose on, costs off) select c1,(select avg(c2) from t2 where t2.c2=t1.c2) from t1 where t1.c1<100 order by t1.c2; QUERY PLAN ----------------------------------------------- Sort Output: t1.c1, (avg(t2.c2)), t1.c2 Sort Key: t1.c2 -> Hash Left Join Output: t1.c1, (avg(t2.c2)), t1.c2 Hash Cond: (t1.c2 = t2.c2) -> Seq Scan on public.t1 Output: t1.c1, t1.c2 Filter: (t1.c1 < 100) -> Hash Output: (avg(t2.c2)), t2.c2 -> HashAggregate Output: avg(t2.c2), t2.c2 Group By Key: t2.c2 -> Seq Scan on public.t2 Output: t2.c2 (16 rows) ``` ## Promoting the Subquery Without Aggregate Using uniquecheck Ensure that each condition has only one line of output. The subqueries with aggregate functions can be automatically pulled up. For subqueries without aggregate functions, the following is an example: select t1.c1 from t1 where t1.c1 = (select t2.c1 from t2 where t1.c1=t2.c2) ; Rewrite as follows: select t1.c1 from t1 join (select t2.c1 from t2 where t2.c1 is not null group by t2.c1(unique check)) tt(c1) on tt.c1=t1.c1; To ensure semantic equivalence, the subquery **tt** must ensure that each **group by t2.c1** has only one line of output. Enable the **uniquecheck** query rewriting parameter to ensure that the query can be pulled up and equivalent. If more than one row of data is output at run time, an error is reported. ``` openGauss=# set rewrite_rule='uniquecheck'; SET openGauss=# explain verbose select t1.c1 from t1 where t1.c1 = (select t2.c1 from t2 where t1.c1=t2.c1); QUERY PLAN ------------------------------------------------------------------------------------- Hash Join (cost=43.36..104.40 rows=2149 distinct=[200, 200] width=4) Output: t1.c1 Hash Cond: (t1.c1 = subquery."?column?") -> Seq Scan on public.t1 (cost=0.00..31.49 rows=2149 width=4) Output: t1.c1, t1.c2 -> Hash (cost=40.86..40.86 rows=200 width=8) Output: subquery."?column?", subquery.c1 -> Subquery Scan on subquery (cost=36.86..40.86 rows=200 width=8) Output: subquery."?column?", subquery.c1 -> HashAggregate (cost=36.86..38.86 rows=200 width=4) Output: t2.c1, t2.c1 Group By Key: t2.c1 Filter: (t2.c1 IS NOT NULL) Unique Check Required -> Seq Scan on public.t2 (cost=0.00..31.49 rows=2149 width=4) Output: t2.c1 (16 rows) ``` Note: Because **group by t2.c1 unique check** occurs before the filter condition **tt.c1=t1.c1**, an error may be reported after the query that does not report an error is rewritten. An example is as follows: There are tables **t1** and **t2**. The data in the tables is as follows: ``` openGauss=# select * from t1 order by c2; c1 | c2 ----+---- 1 | 1 2 | 2 3 | 3 (3 rows) openGauss=# select * from t2 order by c2; c1 | c2 ----+---- 1 | 1 2 | 2 3 | 3 4 | 4 4 | 4 5 | 5 (6 rows) ``` Disable and enable the **uniquecheck** parameter for comparison. After the parameter is enabled, an error is reported. ``` openGauss=# select t1.c1 from t1 where t1.c1 = (select t2.c1 from t2 where t1.c1=t2.c2) ; c1 ---- 1 2 3 (3 rows) openGauss=# set rewrite_rule='uniquecheck'; SET openGauss=# select t1.c1 from t1 where t1.c1 = (select t2.c1 from t2 where t1.c1=t2.c2) ; ERROR: more than one row returned by a subquery used as an expression ``` --- --- url: >- /en/docs/latest/performance_tuning_guide/case_modifying_the_guc_parameter_rewrite_rule.md --- # Case: Modifying the GUC Parameter rewrite\_rule **rewrite\_rule** contains multiple query rewriting rules: **magicset**, **partialpush**, **uniquecheck**, **disablerep**, **intargetlist**, and **predpush**. The following describes the application scenarios of some important rules: ## Promoting the Subquery in the Target Column Using intargetlist The query performance can be greatly improved by converting the subquery in the target column to JOIN. The following is an example: ``` openGauss=# set rewrite_rule='none'; SET postgres=# create table t1(c1 int,c2 int); CREATE TABLE postgres=# create table t2(c1 int,c2 int); CREATE TABLE postgres=# explain (verbose on, costs off) select c1,(select avg(c2) from t2 where t2.c2=t1.c2) from t1 where t1.c1<100 order by t1.c2; QUERY PLAN ----------------------------------------------- Sort Output: t1.c1, ((SubPlan 1)), t1.c2 Sort Key: t1.c2 -> Seq Scan on public.t1 Output: t1.c1, (SubPlan 1), t1.c2 Filter: (t1.c1 < 100) SubPlan 1 -> Aggregate Output: avg(t2.c2) -> Seq Scan on public.t2 Output: t2.c1, t2.c2 Filter: (t2.c2 = t1.c2) (12 rows) ``` Because the subquery **(select avg(c2) from t2 where t2.c2=t1.c2)** in the target column cannot be pulled up, execution of the subquery is triggered each time a row of data of **t1** is scanned, and the query efficiency is low. If the **intargetlist** parameter is enabled, the subquery is converted to JOIN to improve the query performance. ``` openGauss=# set rewrite_rule='intargetlist'; SET openGauss=# explain (verbose on, costs off) select c1,(select avg(c2) from t2 where t2.c2=t1.c2) from t1 where t1.c1<100 order by t1.c2; QUERY PLAN ----------------------------------------------- Sort Output: t1.c1, (avg(t2.c2)), t1.c2 Sort Key: t1.c2 -> Hash Left Join Output: t1.c1, (avg(t2.c2)), t1.c2 Hash Cond: (t1.c2 = t2.c2) -> Seq Scan on public.t1 Output: t1.c1, t1.c2 Filter: (t1.c1 < 100) -> Hash Output: (avg(t2.c2)), t2.c2 -> HashAggregate Output: avg(t2.c2), t2.c2 Group By Key: t2.c2 -> Seq Scan on public.t2 Output: t2.c2 (16 rows) ``` ## Promoting the Subquery Without Aggregate Using uniquecheck Ensure that each condition has only one line of output. The subqueries with aggregate functions can be automatically pulled up. For subqueries without aggregate functions, the following is an example: select t1.c1 from t1 where t1.c1 = (select t2.c1 from t2 where t1.c1=t2.c2) ; Rewrite as follows: select t1.c1 from t1 join (select t2.c1 from t2 where t2.c1 is not null group by t2.c1(unique check)) tt(c1) on tt.c1=t1.c1; To ensure semantic equivalence, the subquery **tt** must ensure that each **group by t2.c1** has only one line of output. Enable the **uniquecheck** query rewriting parameter to ensure that the query can be pulled up and equivalent. If more than one row of data is output at run time, an error is reported. ``` postgres=# set rewrite_rule='uniquecheck'; SET openGauss=# explain verbose select t1.c1 from t1 where t1.c1 = (select t2.c1 from t2 where t1.c1=t2.c1); QUERY PLAN ------------------------------------------------------------------------------------- Hash Join (cost=43.36..104.40 rows=2149 distinct=[200, 200] width=4) Output: t1.c1 Hash Cond: (t1.c1 = subquery."?column?") -> Seq Scan on public.t1 (cost=0.00..31.49 rows=2149 width=4) Output: t1.c1, t1.c2 -> Hash (cost=40.86..40.86 rows=200 width=8) Output: subquery."?column?", subquery.c1 -> Subquery Scan on subquery (cost=36.86..40.86 rows=200 width=8) Output: subquery."?column?", subquery.c1 -> HashAggregate (cost=36.86..38.86 rows=200 width=4) Output: t2.c1, t2.c1 Group By Key: t2.c1 Filter: (t2.c1 IS NOT NULL) Unique Check Required -> Seq Scan on public.t2 (cost=0.00..31.49 rows=2149 width=4) Output: t2.c1 (16 rows) ``` Note: Because **group by t2.c1 unique check** occurs before the filter condition **tt.c1=t1.c1**, an error may be reported after the query that does not report an error is rewritten. An example is as follows: There are tables **t1** and **t2**. The data in the tables is as follows: ``` openGauss=# select * from t1 order by c2; c1 | c2 ----+---- 1 | 1 2 | 2 3 | 3 (3 rows) openGauss=# select * from t2 order by c2; c1 | c2 ----+---- 1 | 1 2 | 2 3 | 3 4 | 4 4 | 4 5 | 5 (6 rows) ``` Disable and enable the **uniquecheck** parameter for comparison. After the parameter is enabled, an error is reported. ``` openGauss=# select t1.c1 from t1 where t1.c1 = (select t2.c1 from t2 where t1.c1=t2.c2) ; c1 ---- 1 2 3 (3 rows) openGauss=# set rewrite_rule='uniquecheck'; SET openGauss=# select t1.c1 from t1 where t1.c1 = (select t2.c1 from t2 where t1.c1=t2.c2) ; ERROR: more than one row returned by a subquery used as an expression ``` --- --- url: >- /en/docs/latest-lite/performance_tuning_guide/case_reconstructing_partitioned_tables.md --- # Case: Reconstructing Partitioned Tables ## Symptom In the following simple SQL statements, the performance bottlenecks exist in the scan operation on the **normal\_date** table. ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------- Seq Scan on normal_date (cost=0.00..259.00 rows=30 width=12) (actual time=0.100..3.466 rows=30 loops=1) Filter: (("time" >= '2022-09-01 00:00:00'::timestamp without time zone) AND ("time" <= '2022-10-01 00:00:00'::timestamp without time zone)) Rows Removed by Filter: 9970 Total runtime: 3.587 ms (4 rows) ``` ## Optimization Analysis Obviously, the table data (in the **time** column) has date features in the service layer, and this meet the features of a partitioned table. Replan the table definition of the **normal\_date** table by defining a partitioned table **normal\_date\_part**. Set the **time** column as a partitioning key and month as an interval unit for the partitioned table. The modified result is as follows, and the performance is nearly 10 times. ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------- Partition Iterator (cost=0.00..480.00 rows=30 width=12) (actual time=0.038..0.085 rows=30 loops=1) Iterations: 2 -> Partitioned Seq Scan on normal_date_part (cost=0.00..480.00 rows=30 width=12) (actual time=0.049..0.063 rows=30 loops=2) Filter: (("time" >= '2022-09-01 00:00:00'::timestamp without time zone) AND ("time" <= '2022-10-01 00:00:00'::timestamp without time zone)) Rows Removed by Filter: 31 Selected Partitions: 3..4 Total runtime: 0.360 ms (7 rows) ``` --- --- url: >- /en/docs/latest/performance_tuning_guide/case_reconstructing_partitioned_tables.md --- # Case: Reconstructing Partitioned Tables ## Symptom In the following simple SQL statements, the performance bottlenecks exist in the scan operation on the **normal\_date** table. ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------- Seq Scan on normal_date (cost=0.00..259.00 rows=30 width=12) (actual time=0.100..3.466 rows=30 loops=1) Filter: (("time" >= '2022-09-01 00:00:00'::timestamp without time zone) AND ("time" <= '2022-10-01 00:00:00'::timestamp without time zone)) Rows Removed by Filter: 9970 Total runtime: 3.587 ms (4 rows) ``` ## Optimization Analysis Obviously, the table data (in the **time** column) has date features in the service layer, and this meet the features of a partitioned table. Replan the table definition of the **normal\_date** table by defining a partitioned table **normal\_date\_part**. Set the **time** column as a partitioning key and month as an interval unit for the partitioned table. The modified result is as follows, and the performance is nearly 10 times. ``` QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------- Partition Iterator (cost=0.00..480.00 rows=30 width=12) (actual time=0.038..0.085 rows=30 loops=1) Iterations: 2 -> Partitioned Seq Scan on normal_date_part (cost=0.00..480.00 rows=30 width=12) (actual time=0.049..0.063 rows=30 loops=2) Filter: (("time" >= '2022-09-01 00:00:00'::timestamp without time zone) AND ("time" <= '2022-10-01 00:00:00'::timestamp without time zone)) Rows Removed by Filter: 31 Selected Partitions: 3..4 Total runtime: 0.360 ms (7 rows) ``` --- --- url: >- /en/docs/latest-lite/performance_tuning_guide/case_rewriting_sql_and_deleting_subqueries_1.md --- # Case: Rewriting SQL and Deleting Subqueries (1) ## Symptom ``` select 1, (select count(*) from normal_date n where n.id = a.id) as GZCS from normal_date a; ``` This SQL performance is poor. SubPlan exists in the execution plan as follows: ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------------- Seq Scan on normal_date a (cost=0.00..888118.42 rows=5129 width=4) (actual time=2.394..22194.907 rows=10000 loops=1) SubPlan 1 -> Aggregate (cost=173.12..173.12 rows=1 width=8) (actual time=22179.496..22179.942 rows=10000 loops=10000) -> Seq Scan on normal_date n (cost=0.00..173.11 rows=1 width=0) (actual time=11279.349..22159.608 rows=10000 loops=10000) Filter: (id = a.id) Rows Removed by Filter: 99990000 Total runtime: 22196.415 ms (7 rows) ``` ## Optimization Description The core of this optimization is to eliminate subqueries. Based on the service scenario analysis, *a\*\*.\*\*id* is not null. In terms of SQL syntax, you can rewrite the SQL statement as follows: ``` select count(*) from normal_date n, normal_date a where n.id = a.id group by a.id; The plan is as follows: QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------- HashAggregate (cost=480.86..532.15 rows=5129 width=12) (actual time=21.539..24.356 rows=10000 loops=1) Group By Key: a.id -> Hash Join (cost=224.40..455.22 rows=5129 width=4) (actual time=6.402..13.484 rows=10000 loops=1) Hash Cond: (n.id = a.id) -> Seq Scan on normal_date n (cost=0.00..160.29 rows=5129 width=4) (actual time=0.087..1.459 rows=10000 loops=1) -> Hash (cost=160.29..160.29 rows=5129 width=4) (actual time=6.065..6.065 rows=10000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 352kB -> Seq Scan on normal_date a (cost=0.00..160.29 rows=5129 width=4) (actual time=0.046..2.738 rows=10000 loops=1) Total runtime: 26.844 ms (9 rows) ``` > \[!NOTE]NOTE > To ensure the equivalence of rewriting, the *not null* constraint is added to *normal\_date.id*. --- --- url: >- /en/docs/latest/performance_tuning_guide/case_rewriting_sql_and_deleting_subqueries_1.md --- # Case: Rewriting SQL and Deleting Subqueries (1) ## Symptom ``` select 1, (select count(*) from normal_date n where n.id = a.id) as GZCS from normal_date a; ``` This SQL performance is poor. SubPlan exists in the execution plan as follows: ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------------- Seq Scan on normal_date a (cost=0.00..888118.42 rows=5129 width=4) (actual time=2.394..22194.907 rows=10000 loops=1) SubPlan 1 -> Aggregate (cost=173.12..173.12 rows=1 width=8) (actual time=22179.496..22179.942 rows=10000 loops=10000) -> Seq Scan on normal_date n (cost=0.00..173.11 rows=1 width=0) (actual time=11279.349..22159.608 rows=10000 loops=10000) Filter: (id = a.id) Rows Removed by Filter: 99990000 Total runtime: 22196.415 ms (7 rows) ``` ## Optimization Description The core of this optimization is to eliminate subqueries. Based on the service scenario analysis, *a\*\*.\*\*id* is not null. In terms of SQL syntax, you can rewrite the SQL statement as follows: ``` select count(*) from normal_date n, normal_date a where n.id = a.id group by a.id; The plan is as follows: QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------- HashAggregate (cost=480.86..532.15 rows=5129 width=12) (actual time=21.539..24.356 rows=10000 loops=1) Group By Key: a.id -> Hash Join (cost=224.40..455.22 rows=5129 width=4) (actual time=6.402..13.484 rows=10000 loops=1) Hash Cond: (n.id = a.id) -> Seq Scan on normal_date n (cost=0.00..160.29 rows=5129 width=4) (actual time=0.087..1.459 rows=10000 loops=1) -> Hash (cost=160.29..160.29 rows=5129 width=4) (actual time=6.065..6.065 rows=10000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 352kB -> Seq Scan on normal_date a (cost=0.00..160.29 rows=5129 width=4) (actual time=0.046..2.738 rows=10000 loops=1) Total runtime: 26.844 ms (9 rows) ``` > \[!NOTE]NOTE > To ensure the equivalence of rewriting, the *not null* constraint is added to *normal\_date.id*. --- --- url: >- /en/docs/latest-lite/performance_tuning_guide/case_rewriting_sql_and_deleting_subqueries_2.md --- # Case: Rewriting SQL and Deleting Subqueries (2) ## Symptom Take the following SQL statement as an example: ``` UPDATE normal_date n SET time = ( SELECT time FROM normal_date_part p WHERE p.id = n.id ) WHERE EXISTS (SELECT 1 FROM normal_date_part n2 WHERE n2.id = n.id); ``` The plan is: ``` QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Update on normal_date n (cost=224.40..2334150.22 rows=5129 width=16) (actual time=17.336..42944.734 rows=10000 loops=1) -> Hash Semi Join (cost=224.40..2334150.22 rows=5129 width=16) (actual time=16.997..42852.967 rows=10000 loops=1) Hash Cond: (n.id = n2.id) -> Seq Scan on normal_date n (cost=0.00..160.29 rows=5129 width=10) (actual time=0.113..7.271 rows=10000 loops=1) -> Hash (cost=160.29..160.29 rows=5129 width=10) (actual time=7.381..7.381 rows=10000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 430kB -> Seq Scan on normal_date n2 (cost=0.00..160.29 rows=5129 width=10) (actual time=0.052..3.501 rows=10000 loops=1) SubPlan 1 -> Partition Iterator (cost=0.00..455.00 rows=1 width=8) (actual time=21006.481..42756.884 rows=10000 loops=10000) Iterations: 331 -> Partitioned Seq Scan on normal_date_part p (cost=0.00..455.00 rows=1 width=8) (actual time=27228.532..27261.944 rows=10000 loops=3310000) Filter: (id = n.id) Rows Removed by Filter: 99990000 Selected Partitions: 1..331 Total runtime: 42947.153 ms (15 rows) ``` ## Optimization Description SubPlan exists in the execution plan, and the calculation accounts for a large proportion in the SubPlan query. That is, SubPlan is a performance bottleneck. Based on the SQL syntax, you can rewrite the SQL statements and delete SubPlan as follows: ``` update normal_date n set time = ( select time from normal_date_part p where p.id = n.id ); ``` --- --- url: >- /en/docs/latest/performance_tuning_guide/case_rewriting_sql_and_deleting_subqueries_2.md --- # Case: Rewriting SQL and Deleting Subqueries (2) ## Symptom Take the following SQL statement as an example: ``` UPDATE normal_date n SET time = ( SELECT time FROM normal_date_part p WHERE p.id = n.id ) WHERE EXISTS (SELECT 1 FROM normal_date_part n2 WHERE n2.id = n.id); ``` The plan is: ``` QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Update on normal_date n (cost=224.40..2334150.22 rows=5129 width=16) (actual time=17.336..42944.734 rows=10000 loops=1) -> Hash Semi Join (cost=224.40..2334150.22 rows=5129 width=16) (actual time=16.997..42852.967 rows=10000 loops=1) Hash Cond: (n.id = n2.id) -> Seq Scan on normal_date n (cost=0.00..160.29 rows=5129 width=10) (actual time=0.113..7.271 rows=10000 loops=1) -> Hash (cost=160.29..160.29 rows=5129 width=10) (actual time=7.381..7.381 rows=10000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 430kB -> Seq Scan on normal_date n2 (cost=0.00..160.29 rows=5129 width=10) (actual time=0.052..3.501 rows=10000 loops=1) SubPlan 1 -> Partition Iterator (cost=0.00..455.00 rows=1 width=8) (actual time=21006.481..42756.884 rows=10000 loops=10000) Iterations: 331 -> Partitioned Seq Scan on normal_date_part p (cost=0.00..455.00 rows=1 width=8) (actual time=27228.532..27261.944 rows=10000 loops=3310000) Filter: (id = n.id) Rows Removed by Filter: 99990000 Selected Partitions: 1..331 Total runtime: 42947.153 ms (15 rows) ``` ## Optimization Description SubPlan exists in the execution plan, and the calculation accounts for a large proportion in the SubPlan query. That is, SubPlan is a performance bottleneck. Based on the SQL syntax, you can rewrite the SQL statements and delete SubPlan as follows: ``` update normal_date n set time = ( select time from normal_date_part p where p.id = n.id ); ``` --- --- url: >- /en/docs/latest-lite/performance_tuning_guide/case_rewriting_sql_statements_and_deleting_in_clause.md --- # Case: Rewriting SQL Statements and Deleting in-clause ## Symptom in-clause/any-clause is a common SQL statement constraint. Sometimes, the clause following **in** or **any** is a constant. For example: ``` select count(1) from calc_empfyc_c1_result_tmp_t1 where ls_pid_cusr1 in ('20120405', '20130405') ``` Or ``` select count(1) from calc_empfyc_c1_result_tmp_t1 where ls_pid_cusr1 in any('20120405', '20130405'); ``` Sometimes, the **IN**/**ANY** clause is used as follows: ``` SELECT * FROM test1 t1, test2 t2 WHERE t1.a = any(values(t2.a),(t2.b)); ``` **a** and **b** are two columns in **t2**, and **"t1.a = any(values(t2.ba,(t2.b))"** is equivalent to **"t1.a = t2.a or t1.a = t2.b"**.\_ Therefore, join-condition is essentially an inequality, and nestloop must be used for this join operation. The execution plan is as follows: ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------- Nested Loop (cost=0.00..138614.38 rows=2309100 width=16) (actual time=0.152..19225.483 rows=1000 loops=1) Join Filter: (SubPlan 1) Rows Removed by Join Filter: 999000 -> Seq Scan on test1 t1 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.021..3.309 rows=1000 loops=1) -> Materialize (cost=0.00..42.23 rows=2149 width=8) (actual time=0.331..1265.810 rows=1000000 loops=1000) -> Seq Scan on test2 t2 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.013..0.268 rows=1000 loops=1) SubPlan 1 -> Values Scan on "*VALUES*" (cost=0.00..0.03 rows=2 width=4) (actual time=2890.741..7372.739 rows=1999000 loops=1000000) Total runtime: 19227.328 ms (9 rows) ``` ## Optimization Description The test result shows that both result sets are too large. As a result, nestloop is time-consuming with more than one hour to return results. Therefore, the key to performance optimization is to eliminate nestloop, using more efficient hashjoin. From the perspective of semantic equivalence, the SQL statements can be written as follows: ``` SELECT * FROM ( SELECT * FROM test1 t1, test2 t2 WHERE t1.a = t2.a UNION SELECT * FROM test1 t1, test2 t2 WHERE t1.a = t2.b ); ``` The optimized SQL queries consist of two equivalent join subqueries, and each subquery can be used for hashjoin in this scenario. The optimized execution plan is as follows. ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------- HashAggregate (cost=1634.99..2096.81 rows=46182 width=16) (actual time=6.369..6.772 rows=1000 loops=1) Group By Key: t1.a, t1.b, t2.a, t2.b -> Append (cost=58.35..1173.17 rows=46182 width=16) (actual time=0.833..3.414 rows=2000 loops=1) -> Hash Join (cost=58.35..355.67 rows=23091 width=16) (actual time=0.832..1.590 rows=1000 loops=1) Hash Cond: (t1.a = t2.a) -> Seq Scan on test1 t1 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.015..0.156 rows=1000 loops=1) -> Hash (cost=31.49..31.49 rows=2149 width=8) (actual time=0.531..0.531 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on test2 t2 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.010..0.199 rows=1000 loops=1) -> Hash Join (cost=58.35..355.67 rows=23091 width=16) (actual time=0.694..1.421 rows=1000 loops=1) Hash Cond: (t1.a = t2.b) -> Seq Scan on test1 t1 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.010..0.160 rows=1000 loops=1) -> Hash (cost=31.49..31.49 rows=2149 width=8) (actual time=0.524..0.524 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on test2 t2 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.008..0.177 rows=1000 loops=1) Total runtime: 7.759 ms (16 rows) ``` --- --- url: >- /en/docs/latest/performance_tuning_guide/case_rewriting_sql_statements_and_deleting_in_clause.md --- # Case: Rewriting SQL Statements and Deleting in-clause ## Symptom in-clause/any-clause is a common SQL statement constraint. Sometimes, the clause following **in** or **any** is a constant. For example: ``` select count(1) from calc_empfyc_c1_result_tmp_t1 where ls_pid_cusr1 in ('20120405', '20130405') ``` Or ``` select count(1) from calc_empfyc_c1_result_tmp_t1 where ls_pid_cusr1 in any('20120405', '20130405'); ``` Sometimes, the **IN**/**ANY** clause is used as follows: ``` SELECT * FROM test1 t1, test2 t2 WHERE t1.a = any(values(t2.a),(t2.b)); ``` **a** and **b** are two columns in **t2**, and **"t1.a = any(values(t2.ba,(t2.b))"** is equivalent to **"t1.a = t2.a or t1.a = t2.b"**.\_ Therefore, join-condition is essentially an inequality, and nestloop must be used for this join operation. The execution plan is as follows: ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------- Nested Loop (cost=0.00..138614.38 rows=2309100 width=16) (actual time=0.152..19225.483 rows=1000 loops=1) Join Filter: (SubPlan 1) Rows Removed by Join Filter: 999000 -> Seq Scan on test1 t1 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.021..3.309 rows=1000 loops=1) -> Materialize (cost=0.00..42.23 rows=2149 width=8) (actual time=0.331..1265.810 rows=1000000 loops=1000) -> Seq Scan on test2 t2 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.013..0.268 rows=1000 loops=1) SubPlan 1 -> Values Scan on "*VALUES*" (cost=0.00..0.03 rows=2 width=4) (actual time=2890.741..7372.739 rows=1999000 loops=1000000) Total runtime: 19227.328 ms (9 rows) ``` ## Optimization Description The test result shows that both result sets are too large. As a result, nestloop is time-consuming with more than one hour to return results. Therefore, the key to performance optimization is to eliminate nestloop, using more efficient hashjoin. From the perspective of semantic equivalence, the SQL statements can be written as follows: ``` SELECT * FROM ( SELECT * FROM test1 t1, test2 t2 WHERE t1.a = t2.a UNION SELECT * FROM test1 t1, test2 t2 WHERE t1.a = t2.b ); ``` The optimized SQL queries consist of two equivalent join subqueries, and each subquery can be used for hashjoin in this scenario. The optimized execution plan is as follows. ``` QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------- HashAggregate (cost=1634.99..2096.81 rows=46182 width=16) (actual time=6.369..6.772 rows=1000 loops=1) Group By Key: t1.a, t1.b, t2.a, t2.b -> Append (cost=58.35..1173.17 rows=46182 width=16) (actual time=0.833..3.414 rows=2000 loops=1) -> Hash Join (cost=58.35..355.67 rows=23091 width=16) (actual time=0.832..1.590 rows=1000 loops=1) Hash Cond: (t1.a = t2.a) -> Seq Scan on test1 t1 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.015..0.156 rows=1000 loops=1) -> Hash (cost=31.49..31.49 rows=2149 width=8) (actual time=0.531..0.531 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on test2 t2 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.010..0.199 rows=1000 loops=1) -> Hash Join (cost=58.35..355.67 rows=23091 width=16) (actual time=0.694..1.421 rows=1000 loops=1) Hash Cond: (t1.a = t2.b) -> Seq Scan on test1 t1 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.010..0.160 rows=1000 loops=1) -> Hash (cost=31.49..31.49 rows=2149 width=8) (actual time=0.524..0.524 rows=1000 loops=1) Buckets: 32768 Batches: 1 Memory Usage: 40kB -> Seq Scan on test2 t2 (cost=0.00..31.49 rows=2149 width=8) (actual time=0.008..0.177 rows=1000 loops=1) Total runtime: 7.759 ms (16 rows) ``` --- --- url: /en/docs/latest-lite/characteristic_description/cbo_optimizer.md --- # CBO Optimizer ## Availability This feature is available since openGauss 1.0.0. ## Introduction The openGauss optimizer is cost-based optimization (CBO). ## Benefits The openGauss CBO optimizer can select the most efficient execution plan among multiple plans based on the cost to meet customer service requirements to the maximum extent. ## Description By using CBO, the database calculates the number of tuples and the execution cost for each step under each execution plan based on the number of table tuples, column width, null record ratio, and characteristic values, such as distinct, MCV, and HB values, and certain cost calculation methods. The database then selects the execution plan that takes the lowest cost for the overall execution or for the return of the first tuple. ## Enhancements None. ## Constraints None. ## Dependencies None. --- --- url: /en/docs/latest/characteristic_description/cbo_optimizer.md --- # CBO Optimizer ## Availability This feature is available since openGauss 1.0.0. ## Introduction The openGauss optimizer is cost-based optimization (CBO). ## Benefits The openGauss CBO optimizer can select the most efficient execution plan among multiple plans based on the cost to meet customer service requirements to the maximum extent. ## Description By using CBO, the database calculates the number of tuples and the execution cost for each step under each execution plan based on the number of table tuples, column width, null record ratio, and characteristic values, such as distinct, MCV, and HB values, and certain cost calculation methods. The database then selects the execution plan that takes the lowest cost for the overall execution or for the return of the first tuple. ## Enhancements None ## Constraints None ## Dependencies None --- --- url: /zh/docs/latest-lite/characteristic_description/cbo_optimizer.md --- # CBO优化器 ## 可获得性 本特性自openGauss 1.0.0版本开始引入。 ## 特性简介 openGauss优化器是基于代价的优化 (Cost-Based Optimization,简称CBO)。 ## 客户价值 openGauss CBO优化器能够在众多计划中依据代价选出最高效的执行计划,最大限度的满足客户业务要求。 ## 特性描述 在CBO优化器模型下,数据库根据表的元组数、字段宽度、NULL记录比率、distinct值、MCV值、HB值等表的特征值,以及一定的代价计算模型,计算出每一个执行步骤的不同执行方式的输出元组数和执行代价(cost),进而选出整体执行代价最小/首元组返回代价最小的执行方式进行执行。 ## 特性增强 无。 ## 特性约束 无。 ## 依赖关系 无。 --- --- url: /zh/docs/latest/characteristic_description/cbo_optimizer.md --- # CBO优化器 ## 可获得性 本特性自openGauss 1.0.0版本开始引入。 ## 特性简介 openGauss优化器是基于代价的优化(Cost-Based Optimization,简称CBO)。 ## 客户价值 openGauss CBO优化器能够在众多计划中依据代价选出最高效的执行计划,最大限度的满足客户业务要求。 ## 特性描述 在CBO优化器模型下,数据库根据表的元组数、字段宽度、NULL记录比率、DISTINCT值、MCV值、HB值等表的特征值,以及一定的代价计算模型,计算出每一个执行步骤的不同执行方式的输出元组数和代价(包括执行代价cost和启动代价startup cost),进而选出整体执行代价最小、首元组返回代价最小的执行方式进行执行。优化器支持动态采样以应对统计信息缺失场景,支持ROWID扫描实现数据行直接定位,索引扫描支持快速全扫描和跳跃扫描等以获取最优计划,支持分区表的分区裁剪以减少数据扫描范围。 ## 特性增强 无。 ## 特性约束 无。 ## 依赖关系 无。 --- --- url: >- /en/docs/latest-lite/sql_reference/character_processing_functions_and_operators.md --- # Character Processing Functions and Operators String functions and operators provided by openGauss are for concatenating strings with each other, concatenating strings with non-strings, and matching the patterns of strings. Note: Except length-related functions, other functions and operators of string processing functions do not support parameters greater than 1 GB. * bit\_length(string) Description: Specifies the number of bits occupied by a string. Return type: int Example: ``` openGauss=# SELECT bit_length('world'); bit_length ------------ 40 (1 row) ``` * btrim(string text \[, characters text]) Description: Removes the longest string consisting only of characters in **characters** (a space by default) from the start and end of **string**. Return type: text Example: ``` openGauss=# SELECT btrim('sring' , 'ing'); btrim ------- sr (1 row) ``` * char\_length(string) or character\_length(string) Description: Specifies the number of characters in a string. Return type: int Example: ``` openGauss=# SELECT char_length('hello'); char_length ------------- 5 (1 row) ``` * instr(text,text,int,int) Description: **instr(string1,string2,int1,int2)** returns the text from **int1** to **int2** in **string1**. The first **int** indicates the start position for matching, and the second **int** indicates the number of matching times. Return type: int Example: ``` openGauss=# SELECT instr( 'abcdabcdabcd', 'bcd', 2, 2 ); instr ------- 6 (1 row) ``` * lengthb(text/bpchar) Description: Obtains the number of bytes of a specified string. Return type: int Example: ``` openGauss=# SELECT lengthb('hello'); lengthb --------- 5 (1 row) ``` * left(str text, n int) Description: Returns the first *n\_ characters in a string. When \_n* is negative, all but the last **|n|** characters are returned. Return type: text Example: ``` openGauss=# SELECT left('abcde', 2); left ------ ab (1 row) ``` * length(string bytea, encoding name ) Description: Specifies the number of characters in **string** in the given **encoding**. **string** must be valid in this encoding. Return type: int Example: ``` openGauss=# SELECT length('jose', 'UTF8'); length -------- 4 (1 row) ``` > \[!NOTE]NOTE > > If the length of the bytea type is queried and UTF8 encoding is specified, the maximum length can only be **536870888**. * lpad(string text, length int \[, fill text]) Description: Fills up **string** to **length** by appending the characters **fill** (a space by default). If **string** is already longer than **length**, then it is truncated. Return type: text Example: ``` openGauss=# SELECT lpad('hi', 5, 'xyza'); lpad ------- xyzhi (1 row) ``` * notlike(x bytea name text, y bytea text) Description: Compares x and y to check whether they are inconsistent. Return type: Boolean Example: ``` openGauss=# SELECT notlike(1,2); notlike -------------- t (1 row) openGauss=# SELECT notlike(1,1); notlike -------------- f (1 row) ``` * octet\_length(string) Description: Specifies the number of bytes in a string. Return type: int Example: ``` openGauss=# SELECT octet_length('jose'); octet_length -------------- 4 (1 row) ``` * overlay(string placing string FROM int \[for int]) Description: Replaces substrings. **FROM int** indicates the start position of the replacement in the first string. **for int** indicates the number of characters replaced in the first string. Return type: text Example: ``` openGauss=# SELECT overlay('hello' placing 'world' from 2 for 3 ); overlay --------- hworldo (1 row) ``` * position(substring in string) Description: Specifies the position of a substring. Parameters are case-sensitive. Return type: int. If the character string does not exist, **0** is returned. Example: ``` openGauss=# SELECT position('ing' in 'string'); position ---------- 4 (1 row) ``` * pg\_client\_encoding() Description: Specifies the current client encoding name. Return type: name Example: ``` openGauss=# SELECT pg_client_encoding(); pg_client_encoding -------------------- UTF8 (1 row) ``` * quote\_ident(string text) Description: Returns the given string suitably quoted to be used as an identifier in an SQL statement string (quotation marks are used as required). Quotation marks are added only if necessary (that is, if the string contains non-identifier characters or would be case-folded). Embedded quotation marks are properly doubled. Return type: text Example: ``` openGauss=# SELECT quote_ident('hello world'); quote_ident -------------- "hello world" (1 row) ``` * quote\_literal(string text) Description: Returns the given string suitably quoted to be used as a string literal in an SQL statement string (quotation marks are used as required). Return type: text Example: ``` openGauss=# SELECT quote_literal('hello'); quote_literal --------------- 'hello' (1 row) ``` If a command similar to the following exists, the text will be escaped. ``` openGauss=# SELECT quote_literal(E'O\'hello'); quote_literal --------------- 'O''hello' (1 row) ``` If a command similar to the following exists, the backslash will be properly doubled. ``` openGauss=# SELECT quote_literal('O\hello'); quote_literal --------------- E'O\\hello' (1 row) ``` If the parameter is null, **NULL** is returned. If the parameter may be null, you are advised to use **quote\_nullable**. ``` openGauss=# SELECT quote_literal(NULL); quote_literal --------------- (1 row) ``` * quote\_literal(value anyelement) Description: Converts the given value to text and then quotes it as a literal. Return type: text Example: ``` openGauss=# SELECT quote_literal(42.5); quote_literal --------------- '42.5' (1 row) ``` If a command similar to the following exists, the given value will be escaped. ``` openGauss=# SELECT quote_literal(E'O\'42.5'); quote_literal --------------- '0''42.5' (1 row) ``` If a command similar to the following exists, the backslash will be properly doubled. ``` openGauss=# SELECT quote_literal('O\42.5'); quote_literal --------------- E'O\\42.5' (1 row) ``` * quote\_nullable(string text) Description: Returns the given string suitably quoted to be used as a string literal in an SQL statement string (quotation marks are used as required). Return type: text Example: ``` openGauss=# SELECT quote_nullable('hello'); quote_nullable ---------------- 'hello' (1 row) ``` If a command similar to the following exists, the text will be escaped. ``` openGauss=# SELECT quote_nullable(E'O\'hello'); quote_nullable ---------------- 'O''hello' (1 row) ``` If a command similar to the following exists, the backslash will be properly doubled. ``` openGauss=# SELECT quote_nullable('O\hello'); quote_nullable ---------------- E'O\\hello' (1 row) ``` If the parameter is null, **NULL** is returned. ``` openGauss=# SELECT quote_nullable(NULL); quote_nullable ---------------- NULL (1 row) ``` * quote\_nullable(value anyelement) Description: Converts the given value to text and then quotes it as a literal. Return type: text Example: ``` openGauss=# SELECT quote_nullable(42.5); quote_nullable ---------------- '42.5' (1 row) ``` If a command similar to the following exists, the given value will be escaped. ``` openGauss=# SELECT quote_nullable(E'O\'42.5'); quote_nullable ---------------- 'O''42.5' (1 row) ``` If a command similar to the following exists, the backslash will be properly doubled. ``` openGauss=# SELECT quote_nullable('O\42.5'); quote_nullable ---------------- E'O\\42.5' (1 row) ``` If the parameter is null, **NULL** is returned. ``` openGauss=# SELECT quote_nullable(NULL); quote_nullable ---------------- NULL (1 row) ``` * substring\_inner(string \[from int] \[for int]) Description: Extracts a substring. **from int** indicates the start position of the truncation. **for int** indicates the number of characters truncated. Return type: text Example: ``` openGauss=# select substring_inner('adcde', 2,3); substring_inner ----------------- dcd (1 row) ``` * substring(string \[from int] \[for int]) Description: Extracts a substring. **from int** indicates the start position of the truncation. **for int** indicates the number of characters truncated. Return type: text Example: ``` openGauss=# SELECT substring('Thomas' from 2 for 3); substring ----------- hom (1 row) ``` * substring(string from *pattern*) Description: Extracts substrings matching the POSIX regular expression. It returns the text that matches the pattern. If no match record is found, a null value is returned. Return type: text Example: ``` openGauss=# SELECT substring('Thomas' from '...$'); substring ----------- mas (1 row) openGauss=# SELECT substring('foobar' from 'o(.)b'); result -------- o (1 row) openGauss=# SELECT substring('foobar' from '(o(.)b)'); result -------- oob (1 row) ``` > \[!NOTE]NOTE > > If the POSIX pattern contains any parentheses, the portion of the text that matched the first parenthesized sub-expression (the one whose left parenthesis comes first) is returned. You can put parentheses around the whole expression if you want to use parentheses within it without triggering this exception. * substring(string from *pattern* for *escape*) Description: Extracts substrings matching the SQL regular expression. The declared schema must match the entire data string; otherwise, the function fails and returns a null value. To indicate the part of the pattern that should be returned on success, the pattern must contain two occurrences of the escape character followed by a double quotation mark ("). The text matching the portion of the pattern between these marks is returned. Return type: text Example: ``` openGauss=# SELECT substring('Thomas' from '%#"o_a#"_' for '#'); substring ----------- oma (1 row) ``` * rawcat(raw,raw) Description: Indicates the string concatenation function. Return type: raw Example: ``` openGauss=# SELECT rawcat('ab','cd'); rawcat -------- ABCD (1 row) ``` * regexp\_like(text,text,text) Description: Indicates the mode matching function of a regular expression. Return type: Boolean Example: ``` openGauss=# SELECT regexp_like('str','[ac]'); regexp_like ------------- f (1 row) ``` * regexp\_substr(string text, pattern text \[, position int \[, occurrence int \[, flags text]]]) Description: Extracts substrings from a regular expression. Its function is similar to **substr**. When a regular expression contains multiple parallel brackets, it also needs to be processed. Parameter description: * **string**: source character string used for matching. * **pattern**: regular expression pattern string used for matching. * **position**: start character of the source string used for matching. This parameter is optional. The default value is **1**. * **occurrence**: sequence number of the matched substring to be extracted. This parameter is optional. The default value is **1**. * **flags**: contains zero or multiple single-letter flags that change the matching behavior of the function. This parameter is optional. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the **'\n'** character by default. The meaning of option **n** is the same as that of option **m**. Return type: text Example: ``` openGauss=# SELECT regexp_substr('str','[ac]'); regexp_substr --------------- (1 row) openGauss=# SELECT regexp_substr('foobarbaz', 'b(..)', 3, 2) AS RESULT; result -------- baz (1 row) ``` * regexp\_count(string text, pattern text \[, position int \[, flags text]]) Description: obtains the number of substrings used for matching. Parameter description: * **string**: source character string used for matching. * **pattern**: regular expression pattern string used for matching. * **position**: sequence number of the character to be matched from the source character string. This parameter is optional. The default value is **1**. * **flags**: contains zero or multiple single-letter flags that change the matching behavior of the function. This parameter is optional. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the \*\*'\n'\*\*character by default. The meaning of option **n** is the same as that of option **m**. Return type: int Example: ``` openGauss=# SELECT regexp_count('foobarbaz','b(..)', 5) AS RESULT; result -------- 1 (1 row) ``` * regexp\_instr(string text, pattern text \[, position int \[, occurrence int \[, return\_opt int \[, flags text]]]]) Description: obtains the position (starting from 1) of the substring that meets the matching condition. If no substring is matched, **0** is returned. Parameter description: * **string**: source character string used for matching. * **pattern**: regular expression pattern string used for matching. * **position**: start character of the source string used for matching. This parameter is optional. The default value is **1**. * **occurrence**: sequence number of the matched substring to be replaced. This parameter is optional. The default value is **1**. * **return\_opt**: specifies whether to return the position of the first or last character of the matched substring. This parameter is optional. If the value is **0**, the position of the first character (starting from 1) of the matched substring is returned. If the value is greater than 0, the position of the next character of the end character of the matched substring is returned. The default value is **0**. * **flags**: contains zero or multiple single-letter flags that change the matching behavior of the function. This parameter is optional. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the **'\n'** character by default. The meaning of option **n** is the same as that of option **m**. Return type: int Example: ``` openGauss=# SELECT regexp_instr('foobarbaz','b(..)', 1, 1, 0) AS RESULT; result -------- 4 (1 row) openGauss=# SELECT regexp_instr('foobarbaz','b(..)', 1, 2, 0) AS RESULT; result -------- 7 (1 row) ``` * regexp\_matches(string text, pattern text \[, flags text]) Description: Returns all captured substrings resulting from matching a POSIX regular expression against **string**. If the pattern does not match, the function returns no rows. If the pattern contains no parenthesized sub-expressions, then each row returned is a single-element text array containing the substring matching the whole pattern. If the pattern contains parenthesized sub-expressions, the function returns a text array whose *n\_th element is the substring matching the \_n*th parenthesized sub-expression of the pattern. The optional **flags** argument contains zero or multiple single-letter flags that change function behavior. **i** indicates that the matching is not related to uppercase and lowercase. **g** indicates that each matched substring is replaced, instead of replacing only the first one. > \[!TIP]NOTICE > > If the last parameter is provided but the parameter value is an empty string ('') and the SQL compatibility mode of the database is set to A, the returned result is an empty set. This is because the A compatibility mode treats the empty string ('') as **NULL**. To resolve this problem, you can: > > * Change the database SQL compatibility mode to C. > * Do not provide the last parameter or do not set the last parameter to an empty string. Return type: SETOF text\[] Example: ``` openGauss=# SELECT regexp_matches('foobarbequebaz', '(bar)(beque)'); regexp_matches ---------------- {bar,beque} (1 row) openGauss=# SELECT regexp_matches('foobarbequebaz', 'barbeque'); regexp_matches ---------------- {barbeque} (1 row) openGauss=# SELECT regexp_matches('foobarbequebazilbarfbonk', '(b[^b]+)(b[^b]+)', 'g'); result -------------- {bar,beque} {bazil,barf} (2 rows) ``` * regexp\_split\_to\_array(string text, pattern text \[, flags text ]) Description: Splits **string** using a POSIX regular expression as the delimiter. The **regexp\_split\_to\_array** function behaves the same as **regexp\_split\_to\_table**, except that **regexp\_split\_to\_array** returns its result as an array of text. Return type: text\[] Example: ``` openGauss=# SELECT regexp_split_to_array('hello world', E'\\s+'); regexp_split_to_array ----------------------- {hello,world} (1 row) ``` * regexp\_split\_to\_table(string text, pattern text \[, flags text]) Description: Splits **string** using a POSIX regular expression as the delimiter. If there is no match to the pattern, the function returns the string. If there is at least one match, for each match it returns the text from the end of the last match (or the beginning of the string) to the beginning of the match. When there are no more matches, it returns the text from the end of the last match to the end of the string. The **flags** parameter is a text string containing zero or more single-letter flags that change the function's behavior. **i** indicates case-insensitive matching. Return type: SETOF text Example: ``` openGauss=# SELECT regexp_split_to_table('hello world', E'\\s+'); regexp_split_to_table ----------------------- hello world (2 rows) ``` * repeat(string text, number int ) Description: Repeats **string** the specified number of times. Return type: text Example: ``` openGauss=# SELECT repeat('Pg', 4); repeat ---------- PgPgPgPg (1 row) ``` > \[!NOTE]NOTE > > The maximum size of memory allocated at a time cannot exceed 1 GB due to the memory allocation mechanism of the database. Therefore, the maximum value of **number** cannot exceed (1 GB – **x**)/**lengthb** (**string**) – 1. **x** indicates the length of the header information, which is usually greater than 4 bytes. The value varies among different scenarios. * replace(string text, from text, to text) Description: Replaces all occurrences in **string** of substring **from** with substring **to**. Return type: text Example: ``` openGauss=# SELECT replace('abcdefabcdef', 'cd', 'XXX'); replace ---------------- abXXXefabXXXef (1 row) ``` * replace(string, substring) Description: Deletes all substrings in a string. String type: text Substring type: text Return type: text Example: ``` openGauss=# SELECT replace('abcdefabcdef', 'cd'); replace ---------------- abefabef (1 row) ``` * reverse(str) Description: Returns the reversed string. Return type: text Example: ``` openGauss=# SELECT reverse('abcde'); reverse --------- edcba (1 row) ``` * right(str text, n int) Description: Returns the last *n\_ characters in a string. When \_n* is negative, all but the first **|n|** characters are returned. Return type: text Example: ``` openGauss=# SELECT right('abcde', 2); right ------- de (1 row) openGauss=# SELECT right('abcde', -2); right ------- cde (1 row) ``` * rpad(string text, length int \[, fill text]) Description: Fills up **string** to **length** by appending the characters **fill** (a space by default). If **string** is already longer than **length**, then it is truncated. Return type: text Example: ``` openGauss=# SELECT rpad('hi', 5, 'xy'); rpad ------- hixyx (1 row) ``` * rtrim(string text \[, characters text]) Description: Removes the longest string containing only characters from characters (a space by default) from the end of string. Return type: text Example: ``` openGauss=# SELECT rtrim('trimxxxx', 'x'); rtrim ------- trim (1 row) ``` * substrb(text,int,int) Description: Extracts a substring. The first **int**indicates the start position of the subtraction. The second **int** indicates the number of characters extracted. Return type: text Example: ``` openGauss=# SELECT substrb('string',2,3); substrb --------- tri (1 row) ``` * substrb(text,int) Description: Extracts a substring. **int** indicates the start position of the extraction. Return type: text Example: ``` openGauss=# SELECT substrb('string',2); substrb --------- tring (1 row) ``` * substr(bytea,from,count) Description: Extracts a substring from **bytea**. **from** specifies the position where the extraction starts. **count** specifies the length of the extracted substring. Return type: text Example: ``` openGauss=# SELECT substr('string',2,3); substr -------- tri (1 row) ``` * string || string Description: Concatenates strings. Return type: text Example: ``` openGauss=# SELECT 'MPP'||'DB' AS RESULT; result -------- MPPDB (1 row) ``` * string || non-string or non-string || string Description: Concatenates strings and non-strings. Return type: text Example: ``` openGauss=# SELECT 'Value: '||42 AS RESULT; result ----------- Value: 42 (1 row) ``` * split\_part(string text, delimiter text, field int) Description: Splits **string** on **delimiter** and returns the **field**th column (counting from text of the first appeared delimiter). Return type: text Example: ``` openGauss=# SELECT split_part('abc~@~def~@~ghi', '~@~', 2); split_part ------------ def (1 row) ``` * strpos(string, substring) Description: Specifies the position of a substring. It is the same as **position(substring in string)**. However, the parameter sequences of them are reversed. Return type: int Example: ``` openGauss=# SELECT strpos('source', 'rc'); strpos -------- 4 (1 row) ``` * to\_hex(number int or bigint) Description: Converts a number to a hexadecimal expression. Return type: text Example: ``` openGauss=# SELECT to_hex(2147483647); to_hex ---------- 7fffffff (1 row) ``` * translate(string text, from text, to text) Description: Any character in **string** that matches a character in the **from** set is replaced by the corresponding character in the **to** set. If **from** is longer than **to**, extra characters occurred in **from** are removed. Return type: text Example: ``` openGauss=# SELECT translate('12345', '143', 'ax'); translate ----------- a2x5 (1 row) ``` * length(string) Description: Obtains the number of characters in a string. Return type: integer Example: ``` openGauss=# SELECT length('abcd'); length -------- 4 (1 row) ``` * lengthb(string) Description: Obtains the number of characters in a string. The value depends on character sets (GBK and UTF8). Return type: integer Example: ``` openGauss=# SELECT lengthb('Chinese'); lengthb --------- 7 (1 row) ``` * substr(string,from) Description: Extracts substrings from a string. **from** indicates the start position of the extraction. * If **from** starts at 0, the value **1** is used. * If the value of **from** is positive, all characters from **from** to the end are extracted. * If the value of **from** is negative, the last *n* characters in the string are extracted, in which **n** indicates the absolute value of **from**. Return type: varchar Example: If the value of **from** is positive: ``` openGauss=# SELECT substr('ABCDEF',2); substr -------- BCDEF (1 row) ``` If the value of **from** is negative: ``` openGauss=# SELECT substr('ABCDEF',-2); substr -------- EF (1 row) ``` * substr(string,from,count) Description: Extracts substrings from a string. **from** indicates the start position of the extraction. **count** indicates the length of the extracted substring. * If **from** starts at 0, the value **1** is used. * If the value of **from** is positive, extract **count** characters starting from **from**. * If the value of **from** is negative, extract the last **n** **count** characters in the string, in which **n** indicates the absolute value of **from**. * If the value of **count** is smaller than **1**, **null** is returned. Return type: varchar Example: If the value of **from** is positive: ``` openGauss=# SELECT substr('ABCDEF',2,2); substr -------- BC (1 row) ``` If the value of **from** is negative: ``` openGauss=# SELECT substr('ABCDEF',-3,2); substr -------- DE (1 row) ``` * substrb(string,from) Description: The functionality of this function is the same as that of **SUBSTR(string,from)**. However, the calculation unit is byte. Return type: bytea Example: ``` openGauss=# SELECT substrb('ABCDEF',-2); substrb --------- EF (1 row) ``` * substrb(string,from,count) Description: The functionality of this function is the same as that of **SUBSTR(string,from,count)**. However, the calculation unit is byte. Return type: bytea Example: ``` openGauss=# SELECT substrb('ABCDEF',2,2); substrb --------- BC (1 row) ``` * trim(\[leading |trailing |both] \[characters] from string) Description: Removes the longest string containing only the characters (a space by default) from the start/end/both ends of the string. Return type: text Example: ``` openGauss=# SELECT trim(BOTH 'x' FROM 'xTomxx'); btrim ------- Tom (1 row) ``` ``` openGauss=# SELECT trim(LEADING 'x' FROM 'xTomxx'); ltrim ------- Tomxx (1 row) ``` ``` openGauss=# SELECT trim(TRAILING 'x' FROM 'xTomxx'); rtrim ------- xTom (1 row) ``` * rtrim(string \[, characters]) Description: Removes the longest string containing only characters from characters (a space by default) from the end of string. Return type: text Example: ``` openGauss=# SELECT rtrim('TRIMxxxx','x'); rtrim ------- TRIM (1 row) ``` * ltrim(string \[, characters]) Description: Removes the longest string containing only characters from characters (a space by default) from the start of string. Return type: text Example: ``` openGauss=# SELECT ltrim('xxxxTRIM','x'); ltrim ------- TRIM (1 row) ``` * upper(string) Description: Converts the string into the uppercase. Return type: text Example: ``` openGauss=# SELECT upper('tom'); upper ------- TOM (1 row) ``` * lower(string) Description: Converts the string into the lowercase. Return type: text Example: ``` openGauss=# SELECT lower('TOM'); lower ------- tom (1 row) ``` * rpad(string varchar, length int \[, fill varchar]) Description: Fills up **string** to **length** by appending the characters **fill** (a space by default). If **string** is already longer than **length**, then it is truncated. **length** in openGauss indicates the character length. One Chinese character is counted as one character. Return type: varchar Example: ``` openGauss=# SELECT rpad('hi',5,'xyza'); rpad ------- hixyz (1 row) ``` ``` openGauss=# SELECT rpad('hi',5,'abcdefg'); rpad ------- hiabc (1 row) ``` * instr(string,substring\[,position,occurrence]) Description: Queries and returns the value of the substring position that occurs the **occurrence** (1 by default) times from the **position** (1 by default) in the string. * If the value of **position** is **0**, **0** is returned. * If the value of **position** is negative, the search is performed backwards from the last *n\_th character in the string, in which \_n* indicates the absolute value of **position**. In this function, the calculation unit is character. One Chinese character is one character. Return type: integer Example: ``` openGauss=# SELECT instr('corporate floor','or', 3); instr ------- 5 (1 row) ``` ``` openGauss=# SELECT instr('corporate floor','or',-3,2); instr ------- 2 (1 row) ``` * initcap(string) Description: Converts the first letter of each word in the string into the uppercase and the other letters into the lowercase. Return type: text Example: ``` openGauss=# SELECT initcap('hi THOMAS'); initcap ----------- Hi Thomas (1 row) ``` * ascii(string) Description: Indicates the ASCII code of the first character in the string. Return type: integer Example: ``` openGauss=# SELECT ascii('xyz'); ascii ------- 120 (1 row) ``` * replace(string varchar, search\_string varchar, replacement\_string varchar) Description: Replaces all **search\_string** in the string with **replacement\_string**. Return type: varchar Example: ``` openGauss=# SELECT replace('jack and jue','j','bl'); replace ---------------- black and blue (1 row) ``` * lpad(string varchar, length int\[, repeat\_string varchar]) Description: Adds a series of **repeat\_string** (a space by default) on the left of the string to generate a new string with the total length of *n*. If the length of the string is longer than the specified length, the function truncates the string and returns the substrings with the specified length. Return type: varchar Example: ``` openGauss=# SELECT lpad('PAGE 1',15,'*.'); lpad ----------------- *.*.*.*.*PAGE 1 (1 row) ``` ``` openGauss=# SELECT lpad('hello world',5,'abcd'); lpad ------- hello (1 row) ``` * concat(str1,str2) Description: Connects str1 and str2 and returns the string. > \[!TIP]NOTICE > > If the SQL compatibility mode is set to **MY** and **str1** or **str2** is set to **NULL**, **NULL** will be returned. Return type: varchar Example: ``` openGauss=# SELECT concat('Hello', ' World!'); concat -------------- Hello World! (1 row) openGauss=# SELECT concat('Hello', NULL); concat -------- Hello (1 row) ``` * chr(integer) Description: Specifies the character of the ASCII code. Return type: varchar Example: ``` openGauss=# SELECT chr(65); chr ----- A (1 row) ``` * regexp\_substr(source\_char, pattern) Description: Extracts substrings from a regular expression. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the period (.) cannot match the **'\n'** character. If **aformat\_regexp\_match** is not contained, the period (.) matches the **'\n'** character by default. Return type: text Example: ``` openGauss=# SELECT regexp_substr('500 Hello World, Redwood Shores, CA', ',[^,]+,') "REGEXPR_SUBSTR"; REGEXPR_SUBSTR ------------------- , Redwood Shores, (1 row) ``` * regexp\_replace(string, pattern, replacement \[,flags ]) Description: Replaces substrings matching the POSIX regular expression. The source string is returned unchanged if there is no match to the pattern. If there is a match, the source string is returned with the replacement string substituted for the matching substring. The replacement string can contain **\n**, where **n** is 1 through 9, to indicate that the source substring matching the *n*th parenthesized sub-expression of the pattern should be inserted, and it can contain **\\&** to indicate that the substring matching the entire pattern should be inserted. The optional **flags** argument contains zero or multiple single-letter flags that change the function behavior. **i** indicates that the matching is not related to uppercase and lowercase. **g** indicates that each matched substring is replaced, instead of replacing only the first one. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the **'\n'** character by default. The meaning of option **n** is the same as that of option **m**. Return type: varchar Example: ``` openGauss=# SELECT regexp_replace('Thomas', '.[mN]a.', 'M'); regexp_replace ---------------- ThM (1 row) openGauss=# SELECT regexp_replace('foobarbaz','b(..)', E'X\\1Y', 'g') AS RESULT; result ------------- fooXarYXazY (1 row) ``` * repexp\_replace(string text, pattern text \[, replacement text \[, position int \[, occurrence int \[, flags text]]]]) Description: Replaces substrings matching the POSIX regular expression. The source string is returned unchanged if there is no match to the pattern. If there is a match, the source string is returned with the replacement string substituted for the matching substring. Parameter description: * **string**: source character string used for matching. * **pattern**: regular expression pattern string used for matching. * **replacement**:character string used to replace the matched substring. This parameter is optional. If no parameter value is specified or the parameter value is null, the parameter value is replaced with an empty string. * **position**: start character of the source string used for matching. This parameter is optional. The default value is **1**. * **occurrence**: sequence number of the matched substring to be replaced. This parameter is optional. The default value is **0**, indicating that all matched substrings are replaced. * **flags**: contains zero or multiple single-letter flags that change the matching behavior of the function. This parameter is optional. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the **'\n'** character by default. The meaning of option **n** is the same as that of option **m**. Return type: text Example: ``` openGauss=# SELECT regexp_replace('foobarbaz','b(..)', E'X\\1Y', 2, 2, 'n') AS RESULT; result ------------ foobarXazY (1 row) ``` * concat\_ws(sep text, str"any" \[, str"any" \[, ...] ]) Description: Uses the first parameter as the separator, which is associated with all following parameters. The **NULL** parameter is ignored. > \[!TIP]NOTICE > > * If the first parameter value is **NULL**, the returned result is **NULL**. > * If the first parameter is provided but the parameter value is an empty string ('') and the SQL compatibility mode of the database is set to **A**, the returned result is **NULL**. This is because the A compatibility mode treats the empty string ('') as **NULL**. To resolve this problem, you can change the SQL compatibility mode of the database to **B**, **C**, or **PG**. Return type: text Example: ``` openGauss=# SELECT concat_ws(',', 'ABCDE', 2, NULL, 22); concat_ws ------------ ABCDE,2,22 (1 row) ``` * nlssort(string text, sort\_method text) Description: Returns the encoding value of a string in the sorting mode specified by **sort\_method**. The encoding value can be used for sorting and determines the sequence of the string in the sorting mode. Currently, **sort\_method** can be set to **nls\_sort=schinese\_pinyin\_m** or **nls\_sort=generic\_m\_ci**. **nls\_sort=generic\_m\_ci** supports only the case-insensitive order for English characters. String type: text sort\_method type: text Return type: text Example: ``` openGauss=# SELECT nlssort('A', 'nls_sort=schinese_pinyin_m'); nlssort ---------------- 01EA0000020006 (1 row) openGauss=# SELECT nlssort('A', 'nls_sort=generic_m_ci'); nlssort ---------------- 01EA000002 (1 row) ``` * convert(string bytea, src\_encoding name, dest\_encoding name) Description: Converts the bytea string to **dest\_encoding**. **src\_encoding** specifies the source code encoding. The string must be valid in this encoding. Return type: bytea Example: ``` openGauss=# SELECT convert('text_in_utf8', 'UTF8', 'GBK'); convert ---------------------------- \x746578745f696e5f75746638 (1 row) ``` > \[!NOTE]NOTE > > If the rule for converting between source to target encoding (for example, GBK and LATIN1) does not exist, the string is returned without conversion. See the **pg\_conversion** system catalog for details. > Example: > ```` >``` ```` ```` >openGauss=# show server_encoding; > server_encoding >----------------- > LATIN1 >(1 row) >openGauss=# SELECT convert_from('some text', 'GBK'); > convert_from >-------------- > some text >(1 row) >db_latin1=# SELECT convert_to('some text', 'GBK'); > convert_to >---------------------- > \x736f6d652074657874 >(1 row) >db_latin1=# SELECT convert('some text', 'GBK', 'LATIN1'); > convert >---------------------- > \x736f6d652074657874 >(1 row) >``` ```` * convert\_from(string bytea, src\_encoding name) Description: Converts the long bytea using the coding mode of the database. **src\_encoding** specifies the source code encoding. The string must be valid in this encoding. Return type: text Example: ``` openGauss=# SELECT convert_from('text_in_utf8', 'UTF8'); convert_from -------------- text_in_utf8 (1 row) ``` * convert\_to(string text, dest\_encoding name) Description: Converts a string to **dest\_encoding**. Return type: bytea Example: ``` openGauss=# SELECT convert_to('some text', 'UTF8'); convert_to ---------------------- \x736f6d652074657874 (1 row) ``` * string \[NOT] LIKE pattern \[ESCAPE escape-character] Description: Specifies the pattern matching function. If the pattern does not include a percentage sign (%) or an underscore (\_), this mode represents itself only. In this case, the behavior of LIKE is the same as the equal operator. The underscore (\_) in the pattern matches any single character while one percentage sign (%) matches no or multiple characters. To match with underscores (\_) or percent signs (%), corresponding characters in **pattern** must lead escape characters. The default escape character is a backward slash (\\) and can be specified using the **ESCAPE** clause. To match with escape characters, enter two escape characters. Return type: Boolean Example: ``` openGauss=# SELECT 'AA_BBCC' LIKE '%A@_B%' ESCAPE '@' AS RESULT; result -------- t (1 row) ``` ``` openGauss=# SELECT 'AA_BBCC' LIKE '%A@_B%' AS RESULT; result -------- f (1 row) ``` ``` openGauss=# SELECT 'AA@_BBCC' LIKE '%A@_B%' AS RESULT; result -------- t (1 row) ``` * REGEXP\_LIKE(source\_string, pattern \[, match\_parameter]) Description: Indicates the mode matching function of a regular expression. **source\_string** indicates the source string and **pattern** indicates the matching pattern of the regular expression. **match\_parameter** indicates the matching items and the values are as follows: * 'i': case-insensitive * 'c': case-sensitive * 'n': allowing the metacharacter "." in a regular expression to be matched with a linefeed. * 'm': allows **source\_string** to be regarded as multiple rows. If **match\_parameter** is ignored, **case-sensitive** is enabled by default, "." is not matched with a linefeed, and **source\_string** is regarded as a single row. Return type: Boolean Example: ``` openGauss=# SELECT regexp_like('ABC', '[A-Z]'); regexp_like ------------- t (1 row) ``` ``` openGauss=# SELECT regexp_like('ABC', '[D-Z]'); regexp_like ------------- f (1 row) ``` ``` openGauss=# SELECT regexp_like('ABC', '[a-z]','i'); regexp_like ------------- t (1 row) ``` * format(formatstr text \[, str"any" \[, ...] ]) Description: Formats a string. Return type: text Example: ``` openGauss=# SELECT format('Hello %s, %1$s', 'World'); format -------------------- Hello World, World (1 row) ``` * md5(string) Description: Encrypts a string in MD5 mode and returns a value in hexadecimal form. > \[!NOTE]NOTE > > The MD5 encryption algorithm is not recommended because it has lower security and poses security risks. Return type: text Example: ``` openGauss=# SELECT md5('ABC'); md5 ---------------------------------- 902fbdd2b1df0c4f70b4a5d23525e932 (1 row) ``` * sha(string) / sha1(string) Description: Encrypts a string using SHA1 and returns a hexadecimal number. The sha and sha1 functions are the same. > \[!NOTE]NOTE > > The SHA1 encryption algorithm is not recommended because it has lower security and poses security risks. > This function is valid only when openGauss is compatible with the MY type (that is, sql\_compatibility = 'B'). Return type: text Example: ``` openGauss=# select sha('ABC'); sha ------------------------------------------ 3c01bdbb26f358bab27f267924aa2c9a03fcfdb8 (1 row) openGauss=# select sha1('ABC'); sha1 ------------------------------------------ 3c01bdbb26f358bab27f267924aa2c9a03fcfdb8 (1 row) ``` * sha2(string, hash\_length) Description: Encrypts a string in SHA2 mode and returns a value in hexadecimal form. **hash\_length**: corresponds to a SHA2 algorithm. The value can be **0**(SHA-256), **224**(SHA-224), **256**(SHA-256), **384**(SHA-384), or **512**(SHA-512). For other values, **NULL** is returned. > \[!NOTE]NOTE > > The SHA224 encryption algorithm is not recommended because it has lower security and poses security risks. > The SHA2 function records hash plaintext in logs. Therefore, you are not advised to use this function to encrypt sensitive information such as keys. > This function is valid only when openGauss is compatible with the MY type (that is, sql\_compatibility = 'B'). Return type: text Example: ``` openGauss=# select sha2('ABC',224); sha2 ---------------------------------------------------------- 107c5072b799c4771f328304cfe1ebb375eb6ea7f35a3aa753836fad (1 row) openGauss=# select sha2('ABC',256); sha2 ------------------------------------------------------------------ b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78 (1 row) openGauss=# select sha2('ABC',0); sha2 ------------------------------------------------------------------ b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78 (1 row) ``` * decode(string text, format text) Description: Decodes binary data from textual representation. Return type: bytea Example: ``` openGauss=# SELECT decode('MTIzAAE=', 'base64'); decode -------------- \x3132330001 (1 row) ``` * similar\_escape(pat text, esc text) Description: Converts a regular expression of the SQL:2008 style to the POSIX style. Return type: text Example: ``` openGauss=# select similar_escape('\s+ab','2'); similar_escape ---------------- ^(?:\\s+ab)$ (1 row) ``` * svals(hstore) Description: Obtains the value of the hstore type. Return type: SETOF text Example: ``` openGauss=# select svals('"aa"=>"bb"'); svals ------- bb (1 row) ``` * tconvert(key text, value text) Description: Converts character strings to the hstore format. Return type: hstore Example: ``` openGauss=# select tconvert('aa', 'bb'); tconvert ------------ "aa"=>"bb" (1 row) ``` * find\_in\_set(text, set) Description: Finds the position of a given member in a set, counting from 1. If no record is found, 0 is returned. Return type: int2 Example: ``` openGauss=# select site, find_in_set('wuhan', site) from employee; site | find_in_set -----------------+------------- beijing,nanjing | 0 beijing,wuhan | 2 (2 rows) ``` * encode(data bytea, format text) Description: Encodes binary data into a textual representation. Return type: text Example: ``` openGauss=# SELECT encode(E'123\\000\\001', 'base64'); encode ---------- MTIzAAE= (1 row) ``` > \[!NOTE]NOTE > > * For a string containing newline characters, for example, a string consisting of a newline character and a space, the value of **length** and **lengthb** in openGauss is 2. > * In openGauss, *n\_ in the CHAR(n) type indicates the number of characters. Therefore, for multiple-octet coded character sets, the length returned by the LENGTHB function may be longer than \_n*. > * openGauss supports multiple types of databases, including A, B, C, and PG. If the database type is not specified, A is used by default. The lexical analyzer of A database is different from that of the other three databases. In A database, an empty character string is considered as **NULL**. Therefore, when a type A database is used, if a **NULL** character string is used as a parameter in the preceding character operation function, no output is displayed. For example: > > ``` > openGauss=# SELECT translate('12345','123',''); > translate > ----------- > (1 row) > ``` > > This is because the kernel checks whether the input parameter contains **NULL** before calling the corresponding function. If yes, the kernel does not call the corresponding function. As a result, no output is displayed. In PG mode, the processing of character strings is the same as that of PostgreSQL. Therefore, the preceding problem does not occur. --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_character_processing_functions_and_operators.md --- # Character Processing Functions and Operators Compared with the original openGauss, Dolphin modifies character processing functions and operators as follows: 1. The regexp, not regexp, and rlike operators are added. 2. The locate, lcase, ucase, insert, bin, char, elt, field, find\_int\_set, hex, space, soundex, export\_set, ord, substring\_index, and from\_base64 functions are added. 3. The performance of the length, bit\_length, octet\_length, convert, and format functions are modified. 4. The XOR function of the `^` operator is added, and the `LIKE BINARY/NOT LIKE BINARY` operator is added. 5. The `LIKE/NOT LIKE` operator is modified. 6. The `COMPRESS` function is added. 7. THe `UNCOMPRESS` function is added. 8. THe `UNCOMPRESSED_LENGTH` function is added. 9. THe `WEIGHT_STRING` function is added. * bit\_length(string) Description: Specifies the number of bits in a string. For binary input, the value is padded up to a multiple of 8. Return type: int Example: ``` openGauss=# SELECT bit_length('world'); bit_length ------------ 40 (1 row) openGauss=# SELECT bit_length(b'010'); bit_length ------------ 8 (1 row) ``` * insert(des text, start int, length int, src text) Description: Inserts a new string at a specified position of the original string and replaces a certain number of characters in the original string from the specified position. Return type: text Example: ``` openGauss=# select insert('abcdefg', 2, 4, 'yyy'); insert -------- ayyyfg (1 row) ``` * lcase(string) Description: Converts a string to lowercase, equivalent to **lower**. Return type: varchar Example: ``` openGauss=# SELECT lcase('TOM'); lcase ------- tom (1 row) ``` * length(string) Description: Obtains the number of characters in a string. For multi-character encoding (such as Chinese), the number of bytes is returned. Return type: integer Example: ``` openGauss=# SELECT length('abcd'); length -------- 4 (1 row) openGauss=# SELECT length ('中文'); length -------- 6 (1 row) ``` * format(val number, dec\_num int \[,locale string]) Description: Returns **val** in the format of x,xxx,xxx.xx. The **val** will retain *dec\_num* decimal places. A maximum of 32 decimal places can be reserved. If **dec\_num** is greater than 32, 32 decimal places are reserved. If **dec\_num** is set to 0, the returned content does not contain the decimal point or decimal part. The third parameter is optional. You can specify the format of the decimal point and thousands separator in the returned content based on locale. If the third parameter is not specified or the value of the third parameter is invalid, the default value **en\_US** is used. Note: This format function is used for B-compatible databases and has different semantics from the original format function of openGauss. To use this semantics, create a B-compatible database, enable the B-compatible SQL engine plug-in, and set **B\_COMPATIBILITY\_MODE** to **TRUE**. Return type: text Example: ``` openGauss=# CREATE DATABASE B_COMPATIBILITY_DATABASE DBCOMPATIBILITY 'B'; CREATE DATABASE openGauss=# \c B_COMPATIBILITY_DATABASE b_compatibility_database=# CREATE EXTENSION dolphin; CREATE EXTENSION b_compatibility_database=# SET B_COMPATIBILITY_MODE = TRUE; SET b_compatibility_database=# select format(1234.4567,2); format ----------- 1,234.46 (1 row) b_compatibility_database=# select format(1234.5,4); format ----------- 1,234.5000 (1 row) b_compatibility_database=# select format(1234.5,0); format ----------- 1,235 (1 row) b_compatibility_database=# select format(1234.5,2,'de_DE'); format ----------- 1.234,50 (1 row) ``` * hex(number or string or bytea or bit) Description: Converts a number, character, binary character type, or bit string type to a hexadecimal format. Note: The openGauss considers the backslash () as a character. Therefore, the length of the character string **\n** is 2. Return type: text Example: ``` openGauss=# SELECT hex(256); hex ----- 100 (1 row) openGauss=# select hex('abc'); hex -------- 616263 (1 row) openGauss=# select hex('abc'::bytea); hex -------- 616263 (1 row) openGauss=# select hex(b'1111'); hex ----- 0F (1 row) openGauss=# select hex('\n'); hex ------- 5C6E (1 row) ``` * locate(substring, string \[,position]) Description: From the specified **position** (**1** by default) in the string on, queries and returns the value of **position** where the substring occurs for the first time. Parameters are case-sensitive. * If the value of **position** is **0**, 0 is returned. * If the value of **position** is negative, the search is performed backwards from the last *n*th character in the string, in which *n* indicates the absolute value of **position**. Return type: integer. If the character string does not exist, **0** is returned. Example: ``` openGauss=# SELECT locate('ing', 'string'); locate -------- 4 (1 row) openGauss=# SELECT locate('ing', 'string', 0); locate -------- 0 (1 row) openGauss=# SELECT locate('ing', 'string', 5); locate -------- 0 (1 row) ``` * octet\_length(string) Description: It is equivalent to **length**. Return type: int Example: ``` openGauss=# SELECT octet_length ('中文'); octet_length -------------- 6 (1 row) ``` * source\_string regexp pattern Description: Indicates the pattern matching operator of a regular expression. **source\_string** indicates the source string and **pattern** indicates the matching pattern of the regular expression. Return type: integer (0 or 1) Example: ``` openGauss=# SELECT 'str' regexp '[ac]' AS RESULT; result -------- 0 (1 row) ``` * source\_string not regexp pattern Description: Reverses the result of regexp. **source\_string** indicates the source string and **pattern** indicates the matching pattern of the regular expression. Return type: integer (0 or 1) Example: ``` openGauss=# SELECT 'str' not regexp '[ac]' AS RESULT; result -------- 1 (1 row) ``` * source\_string rlike pattern Description: It is equivalent to **regexp**. **source\_string** indicates the source string and **pattern** indicates the matching pattern of the regular expression. Return type: integer (0 or 1) Example: ``` openGauss=# SELECT 'str' rlike '[ac]' AS RESULT; result -------- 0 (1 row) ``` * ucase(string) Description: Converts the string into the uppercase. It is equivalent to **upper**. Return type: varchar Example: ``` openGauss=# SELECT ucase('tom'); ucase ------- TOM (1 row) ``` * bin(number or string) Description: Returns a binary string of N integers or numeric characters. For Chinese characters, 0 is returned. Return type: text Example: ``` b_compatibility_database=# SELECT bin('309'); bin ------------ 100110101 (1 row) b_compatibility_database=# SELECT bin('你好'); bin --- 0 (1 row) ``` * char(any) Description: Converts multiple digits into multiple characters based on ASCII codes. Return type: text Example: ``` b_compatibility_database=# select char(77,77.3,'77.3','78.8',78.8); char ------- MMMNO (1 row) ``` * char\_length (string) or character\_leng (string) Description: Specifies the number of characters in a character string. The length of a Chinese character is 1. The binary type is supported. Return type: int Example: ``` openGauss=# SELECT char_length('hello'); char_length ------------- 5 (1 row) b_compatibility_database=# SELECT char_length(B'101'); char_length ------------- 1 (1 row) ``` * convert(expr using transcoding\_name) Description: Converts expr based on the encoding mode specified by transcoding\_name. Note: By default, the database supports the following format: convert(string bytea, src\_encoding name, dest\_encoding name), where the bytea is converted using the encoding mode specified by dest\_encoding. In Dolphin, transcoding\_name after USING can be used to specify the encoding mode to convert expr, and the preceding three parameters are not supported. Return type: text Example: ``` b_compatibility_database=# select convert('a' using 'utf8'); convert --------- a (1 row) b_compatibility_database=# select convert('a' using utf8); convert --------- a (1 row) ``` * elt(number, str1,str2,str3,...) Description: Returns the *N*th string. Return type: text Example: ``` b_compatibility_database=# select elt(3,'wo','ceshi','disange'); elt --------- disange (1 row) ``` * field(str, str1,str2,str3,...) Description: Obtains the position of str in strn. The position is case insensitive. Return type: int Example: ``` b_compatibility_database=# select field('ceshi','wo','ceshi','disange'); field ------- 2 (1 row) ``` * find\_in\_set(str, strlist) Description: Obtains the position of str in strlist. The position is case insensitive and is separated by commas (,). Return type: int Example: ``` b_compatibility_database=# select find_in_set('ceshi','wo','ceshi,ni,wo,ta'); find_in_set ------------- 3 (1 row) ``` * space(number) Description: Returns *N* spaces. Return type: text Example: ``` b_compatibility_database=# select space('5'); space ------- (1 row) ``` * soundex(str) Description: Returns the algorithm that describes the alphanumeric pattern of the speech representation of the specified string. Return type: text Example: ``` b_compatibility_database=# select soundex('abcqwcaa'); soundex --------- A120 (1 row) ``` * make\_set(number, string1, string2, ...) Description: Returns a set value (a string containing substrings separated by commas) consisting of a string with the corresponding bit set in number. string1 corresponds to bit 0, string2 corresponds to bit 1, and so on. NULL values in string1, string2, ... are not added to the result. Return type: text ```sql select make_set(1|4, 'one', 'two', NULL, 'four'); make_set ---------- one (1 row) ``` * ^ Description: Implements the XOR function of two character strings. The content before the first non-numeric symbol is truncated for XOR. Return type: INT Example: ``` openGauss=# SELECT '123a'^'123'; ?column? --------- 0 (1 row) ``` * like/not like Description: Specifies whether the string matches the pattern string following LIKE. In the source version, LIKE of openGauss is case sensitive. In this version, when `b_compatibility_mode` is set to `TRUE`, LIKE is case insensitive. When `b_compatibility_mode` is set to `FALSE`, LIKE is case sensitive. If the string matches the provided pattern, the LIKE expression returns true (the ILIKE expression returns false). Return type: Boolean Example: ``` openGauss=# SELECT 'a' like 'A' as result; result ------------ t (1 row) openGauss=# SELECT 'abc' like 'a' as result; result ------------ f (1 row) openGauss=# SELECT 'abc' like 'A%' as result; result ------------ t (1 row) ``` * like binary/not like binary Description: Determines whether a string can match the pattern string after LIKE BINARY. LIKE BINARY uses case-sensitive pattern matching. If the pattern is matched, true is returned (NOT LIKE BINARY returns false). If the pattern is not matched, false is returned (NOT LIKE BINARY returns true). Return type: Boolean Example: ``` openGauss=# SELECT 'a' like binary 'A' as result; result ------------ f (1 row) openGauss=# SELECT 'a' like binary 'a' as result; result ------------ t (1 row) openGauss=# SELECT 'abc' like binary 'a' as result; result ------------ f (1 row) openGauss=# SELECT 'abc' like binary 'a%' as result; result ------------ t (1 row) ``` * substring\_index(str, delim, count) Description: Returns the substring between the start position of **str** and the position where **delim** is matched for **count** times. **count** indicates the number of matching times. If **count** is a positive number, the matching starts from the left of **str** and the substring on the left of the matching position is returned. If **count** is a negative number, the matching starts from the right of **str** and the substring on the right of the matching position is returned. The value of **count** ranges from INT64\_MIN to INT64\_MAX. Return type: text Example: ``` openGauss=# SELECT instr('abcdabcdabcd', 'bcd', 2); substring_index ----------------- abcda (1 row) ``` * export\_set(bits, on, off, separator, number of bits) Description: Returns a string that will display the number of digits. This function requires five independent variables to work. This function converts the first parameter (integer) to a binary number. If the binary number is 1, **on** is returned. If the binary number is 0, **off** is returned. Return type: text Example: ```sql openGauss=# SELECT EXPORT_SET(5,'Y','N',',',5); export_set ------------- Y,N,Y,N,N (1 row) ``` * FROM\_BASE64 Description: Decodes a BASE64-encoded character string based on BASE64 encoding rules and returns the decoding result. Return type: text Encoding rules: * Every three bytes (24 bits) are converted into four bytes (32 bits). Six bits form a group, and two 0s are padded to the most significant bits to form a byte. In this way, three bytes can be padded into four bytes, and each byte corresponds to only 0(00000000) to 63(00111111). * Add a newline character for every 76 characters. * The codes from 0(00000000) to 61(00111111) correspond to 62 characters from A to Z, a to z, and 0 to 9. The code of 62(00111110) is '+', and the code of 63(00111111) is '/'. * If the number of bytes in the input character string is not a multiple of three, the remaining bytes are converted according to the encoding rule. If a byte is less than eight bits, 0s are padded to the least significant bits to fill eight bits, and '=' is used to fill four bytes in the conversion result. If the last group contains only two bytes, every six bits form a group, and the third group contains only four bits, pad two 0s to the least significant bits, pad two 0s to the most significant bits of the three groups, convert the three groups into three characters, and add an equal sign (=) to the end of the three groups. If the last group contains only one byte, every six bits form a group, and the second group contains only two bits, four 0s need to be padded to the lower bits. Then, two 0s need to be padded to the upper bits of the two groups to convert the two groups into two characters, and two equal signs (=) need to be added to the end of the two groups. Decoding rules: * Represent the input string in binary mode and remove the two 0s from the high-order bits of each byte. * According to the encoding rule, the number of correct encoding bytes must be a multiple of 4. If there is an equal sign (=) at the end, 0s in the least significant bits of the last byte except the equal sign (=) are removed based on the number of equal signs (=). If there is an equal sign (=) at the end, that is, the last four bytes are '\*\*\*=', convert the first three bytes into binary and delete the last two zeros. If there are two equal signs (=) at the end, that is, the last four bytes are '\*\*==', in this case, the first two bytes are converted into binary digits and then the last four 0s are deleted. * The bytes after the high-order 0s are removed are combined in sequence, and every eight bits are converted into a character. Example 1: YWJj 1. The character string is expressed as 00011000(Y)00010110(W)00001001(J)00100011(j) in binary mode. 2. After the two 0s are removed from the most significant bits of each byte, the value becomes 011000 010110 001001 100011. 3. Combine the bytes without the most significant bit 0 into 01100001(a)01100010(b)01100011(c) in sequence. 4. Therefore, the decoding result is abc. Example 2: YWI= 1. The character string is expressed as 00011000(Y)00010110(W)00001000(I) in binary mode. 2. After the two 0s are removed from the most significant bits of each byte, the value becomes 011000 010110 001000. 3. Because there is an equal sign (=) at the end of the third byte, 0 at the end of the third byte must be removed and then combined, for example, 01100001 01100010. 4. Therefore, the decoding result is ab. Example: ``` openGauss=# SELECT FROM_BASE64('YWJj'); from_base64 ------------- abc (1 row) ``` * ORD(str) Description: Returns the value of the leftmost character of **str** and use the following formula to calculate the value of the byte formed by the character: ``` (1st byte code) + (2nd byte code 256) + (3rd byte code 256^2) ... ``` Return type: INT Example: ```sql -- test 1 byte openGauss=# select ord('1111'); ord ----- 49 (1 row) openGauss=# select ord('sss111'); ord ----- 115 (1 row) -- test 2 byte openGauss=# select ord('Ŷ1111'); ord ------- 50614 (1 row) openGauss=# select ord('߷1111'); ord ------- 57271 (1 row) -- test 3 byte openGauss=# select ord('অ1111'); ord ---------- 14722693 (1 row) openGauss=# select ord('ꬤ1111'); ord ---------- 15379620 (1 row) -- test 4 byte openGauss=# select ord('��1111'); ord ------------ 4036133270 (1 row) openGauss=# select ord('��1111'); ord ------------ 4036199316 (1 row) ``` * TO\_BASE64(str) Description: Encodes a character string into BASE64 format based on BASE64 encoding rules and returns the encoding result. The encoding and decoding rules are the same as those of the FROM\_BASE64 function. Return type: text Precautions * If NULL is entered, NULL is returned. * The encoding and decoding rules are the same as those of the FROM\_BASE64 function. Example 1: abc 1. Represent a character string in binary mode: 01100001(a)01100010(b)01100011(c) 2. Split the binary string into 6-bit groups: 011000 010110 001001 100011 3. Pad the upper bits with two 0s: 00011000 00010110 00001001 00100011 4. Search for the BASE64 code conversion table and find out that characters corresponding to 00011000, 00010110, 00001001, and 00100011 are Y, W, J, and j. 5. Therefore, the encoding result is YWJj. Example 2: ab 1. Represent a character string in binary mode: 01100001(a)01100010(b) 2. Split the binary string into 6-bit groups. The lower bits of the last group are padded with two 0s to ensure that the last group contains six bits: 011000 010110 0010(00) 3. Pad the upper bits with two 0s: 00011000 00010110 00001000 4. Search for the BASE64 code conversion table and find out that characters corresponding to 00011000, 00010110, and 00001000 are Y, W, and I. 5. The number of bytes in the input character string is not a multiple of 3. As a result, the number of characters after conversion is not a multiple of 4. You need to add an equal sign (=) to ensure that the final encoding result contains 4 bytes, that is YWI=. Example: ```sql SELECT TO_BASE64('to_base64'); to_base64 -------------- dG9fYmFzZTY0 (1 row) SELECT TO_BASE64('123456'); to_base64 ----------- MTIzNDU2 (1 row) SELECT TO_BASE64('12345'); to_base64 ----------- MTIzNDU= (1 row) SELECT TO_BASE64('1234'); to_base64 ----------- MTIzNA== (1 row) ``` * UNHEX(str) Description: Decodes a hexadecimal-encoded string. A hexadecimal character is decoded into a four-bit binary character, and two hexadecimal characters (eight bits) are decoded into one character. The decoding result of the string is returned. If the number of characters in the hexadecimal string is not an even number, pad the upper bits with 0. If a binary string is entered, NULL is returned. Return type: text Precautions * If the input is NULL or contains non-hexadecimal characters, NULL is returned. * If a number is entered, the number is converted into a character string and then decoded. If a hexadecimal number needs to be converted into a decimal number, other functions are required. * The encoding and decoding rules are the same as those of the HEX function. Example 1: 4142 1. Represent each hexadecimal character in 4-bit binary mode. If the number of characters in the hexadecimal string is not an even number, pad the upper bits with 0: 0100(4)0001(1)0100(4)0010(2) 2. Every eight bit form a character: 01000001 01000010 3. Therefore, the decoding result is AB. Example: ```sql SELECT UNHEX('6f70656e4761757373'); unhex ----------- openGauss (1 row) SELECT UNHEX(HEX('string')); unhex -------- string (1 row) SELECT HEX(UNHEX('1267')); hex ------ 1267 (1 row) ``` * compress(text) Description: The purpose of the COMPRESS function is to compress the given string to save storage space. Return type: bytea Example: ``` SELECT HEX(COMPRESS('2022-05-12 10:30:00')); hex ---------------------------------------------------------------- 13000000789C33323032D23530D53534523034B03236B032300000240B03A1 (1 row) ``` * uncompress(bytea) Description: The purpose of the UNCOMPRESS function is to decompress the compressed binary data and return the original data. Return type: text Example: ``` SELECT UNCOMPRESS(COMPRESS('2022-05-12 10:30:00')); uncompress --------------------- 2022-05-12 10:30:00 (1 row) ``` * uncompressed\_length(bytea) Description: The purpose of the UNCOMPRESSED\_LENGTH function is to return the length of the data after decompression. Return type: integer Example: ``` SELECT UNCOMPRESSED_LENGTH(COMPRESS('2022-05-12 10:30:00')); uncompressed_length --------------------- 19 (1 row) ``` * weight\_string(str \[as {char|binary}(n)] \[level levels]) levels: n \[asc|desc|reverse] \[, n \[asc|desc|reverse]] ... Description: The WEIGHT\_STRING function is an internal function used for testing and debugging character set sorting rules. It is used to get the weight of a string. It returns a binary string for comparing and sorting strings. str is the input string. The AS clause can convert the input string to `CHAR(N)` or `BINARY(N)`. If the input string exceeds N, it will be truncated. If it is less than N, it will be padded with spaces (`AS CHAR`) or 0 (`AS BINARY`). The LEVEL clause specifies how to modify the calculation of the string. Only `AS CHAR` supports the LEVEL clause. After the LEVEL clause, three modifiers can be added: `ASC`, `DESC` (bit inversion), `REVERSE` (byte order reversal). Only `LEVEL 1 DESC` and `LEVEL 1 REVERSE` are valid. LEVEL 2 to LEVEL 6 do not process the calculation string. Return type: bytea Example: ``` select hex(weight_string('abc' as binary(2))); hex ------ 6162 (1 row) select hex(weight_string('abc' as char(2) LEVEL 1 )); hex ---------- 00410042 (1 row) select hex(weight_string('abc' as char(2) LEVEL 1 DESC)); hex ---------- FFBEFFBD (1 row) select hex(weight_string('abc' as char(2) LEVEL 1 REVERSE)); hex ---------- 42004100 (1 row) ``` --- --- url: /en/docs/latest/sql_reference/character_processing_functions_and_operators.md --- # Character Processing Functions and Operators String functions and operators provided by openGauss are for concatenating strings with each other, concatenating strings with non-strings, and matching the patterns of strings. Note: Except length-related functions, other functions and operators of string processing functions do not support parameters greater than 1 GB. * bit\_length(string) Description: Specifies the number of bits occupied by a string. Return type: int Example: ``` openGauss=# SELECT bit_length('world'); bit_length ------------ 40 (1 row) ``` * btrim(string text \[, characters text]) Description: Removes the longest string consisting only of characters in **characters** (a space by default) from the start and end of **string**. Return type: text Example: ``` openGauss=# SELECT btrim('sring' , 'ing'); btrim ------- sr (1 row) ``` * char\_length(string) or character\_length(string) Description: Specifies the number of characters in a string. Return type: int Example: ``` openGauss=# SELECT char_length('hello'); char_length ------------- 5 (1 row) ``` * instr(text,text,int,int) Description: **instr(string1,string2,int1,int2)** returns the text from **int1** to **int2** in **string1**. The first **int** indicates the start position for matching, and the second **int** indicates the number of matching times. Return type: int Example: ``` openGauss=# SELECT instr( 'abcdabcdabcd', 'bcd', 2, 2 ); instr ------- 6 (1 row) ``` * instrb(searchstr text, substring text, int64 position, int64 occurrence) Description: Returns the position of the first byte of the specified occurrence of a substring in a string. Return type: int64 Example: ``` openGauss=# select INSTRB('123456123', '123', 4); instrb -------- 7 (1 row) ``` * insert(str,pos,len,newstr) Description: Returns a string (**str**), in which *len* characters are replaced by a string (**newstr**) from *pos*. Return type: string Example: ``` openGauss=# SELECT INSERT("begtut.com", 1, 6, "Example"); -------- Example.com (1 row) ``` > \[!NOTE]NOTE If **pos** is not within the length of the string, the original string is returned. If *len* is not within the length range of the rest of the string, replace the rest of the string from *pos*. If the parameter is null, NULL is returned. * lengthb(text/bpchar) Description: Obtains the number of bytes of a specified string. Return type: int Example: ``` openGauss=# SELECT lengthb('hello'); lengthb --------- 5 (1 row) ``` * left(str text, n int) Description: Returns the first *n\_ characters in a string. When \_n* is negative, all but the last **|n|** characters are returned. Return type: text Example: ``` openGauss=# SELECT left('abcde', 2); left ------ ab (1 row) ``` * length(string bytea, encoding name ) Description: Specifies the number of characters in **string** in the given **encoding**. **string** must be valid in this encoding. Return type: int Example: ``` openGauss=# SELECT length('jose', 'UTF8'); length -------- 4 (1 row) ``` > \[!NOTE]NOTE > If the length of the bytea type is queried and UTF8 encoding is specified, the maximum length can only be **536870888**. * lpad(string text, length int \[, fill text]) Description: Fills up **string** to **length** by appending the characters **fill** (a space by default). If **string** is already longer than **length**, then it is truncated. Return type: text Example: ``` openGauss=# SELECT lpad('hi', 5, 'xyza'); lpad ------- xyzhi (1 row) ``` * nls\_charset\_id(p1 name, p2 name default 'SQL\_ASCII', P3 name default "SQL\_ASCII") Description: Returns the ID corresponding to the specified character set **p1**. Return type: integer Example: ``` openGauss=# SELECT NLS_CHARSET_ID('gbk'); nls_charset_id ---------------- 6 (1 row) ``` * nls\_charset\_name(p1 integer, p2 integer default 0) Description: Returns the name of the character set corresponding to the ID. Return type: name Example: ``` openGauss=# SELECT NLS_CHARSET_NAME(6); nls_charset_name ------------------ GBK (1 row) ``` * nls\_lower Description: Returns all letters in lowercase. Return type: string Example: ``` openGauss=# SET search_path to whale; openGauss=# SELECT NLS_LOWER('AbC') FROM dual; ------- abc (1 row) ``` * nls\_upper Description: Returns all letters in uppercase. Return type: string Example: ``` openGauss=# SET search_path to whale; openGauss=# SELECT NLS_UPPER('AbC') FROM dual; ------- ABC (1 row) ``` * notlike(x bytea name text, y bytea text) Description: Compares x and y to check whether they are inconsistent. Return type: Boolean Example: ``` openGauss=# SELECT notlike(1,2); notlike -------------- t (1 row) openGauss=# SELECT notlike(1,1); notlike -------------- f (1 row) ``` * octet\_length(string) Description: Specifies the number of bytes in a string. Return type: int Example: ``` openGauss=# SELECT octet_length('jose'); octet_length -------------- 4 (1 row) ``` * overlay(string placing string FROM int \[for int]) Description: Replaces substrings. **FROM int** indicates the start position of the replacement in the first string. **for int** indicates the number of characters replaced in the first string. Return type: text Example: ``` openGauss=# SELECT overlay('hello' placing 'world' from 2 for 3 ); overlay --------- hworldo (1 row) ``` * position(substring in string) Description: Specifies the position of a substring. Parameters are case-sensitive. Return type: int. If the character string does not exist, **0** is returned. Example: ``` openGauss=# SELECT position('ing' in 'string'); position ---------- 4 (1 row) ``` * pg\_client\_encoding() Description: Specifies the current client encoding name. Return type: name Example: ``` openGauss=# SELECT pg_client_encoding(); pg_client_encoding -------------------- UTF8 (1 row) ``` * quote\_ident(string text) Description: Returns the given string suitably quoted to be used as an identifier in an SQL statement string (quotation marks are used as required). Quotation marks are added only if necessary (that is, if the string contains non-identifier characters or would be case-folded). Embedded quotation marks are properly doubled. Return type: text Example: ``` openGauss=# SELECT quote_ident('hello world'); quote_ident -------------- "hello world" (1 row) ``` * quote\_literal(string text) Description: Returns the given string suitably quoted to be used as a string literal in an SQL statement string (quotation marks are used as required). Return type: text Example: ``` openGauss=# SELECT quote_literal('hello'); quote_literal --------------- 'hello' (1 row) ``` If a command similar to the following exists, the text will be escaped. ``` openGauss=# SELECT quote_literal(E'O\'hello'); quote_literal --------------- 'O''hello' (1 row) ``` If a command similar to the following exists, the backslash will be properly doubled. ``` openGauss=# SELECT quote_literal('O\hello'); quote_literal --------------- E'O\\hello' (1 row) ``` If the parameter is null, **NULL** is returned. If the parameter may be null, you are advised to use **quote\_nullable**. ``` openGauss=# SELECT quote_literal(NULL); quote_literal --------------- (1 row) ``` * quote\_literal(value anyelement) Description: Converts the given value to text and then quotes it as a literal. Return type: text Example: ``` openGauss=# SELECT quote_literal(42.5); quote_literal --------------- '42.5' (1 row) ``` If a command similar to the following exists, the given value will be escaped. ``` openGauss=# SELECT quote_literal(E'O\'42.5'); quote_literal --------------- '0''42.5' (1 row) ``` If a command similar to the following exists, the backslash will be properly doubled. ``` openGauss=# SELECT quote_literal('O\42.5'); quote_literal --------------- E'O\\42.5' (1 row) ``` * quote\_nullable(string text) Description: Returns the given string suitably quoted to be used as a string literal in an SQL statement string (quotation marks are used as required). Return type: text Example: ``` openGauss=# SELECT quote_nullable('hello'); quote_nullable ---------------- 'hello' (1 row) ``` If a command similar to the following exists, the text will be escaped. ``` openGauss=# SELECT quote_nullable(E'O\'hello'); quote_nullable ---------------- 'O''hello' (1 row) ``` If a command similar to the following exists, the backslash will be properly doubled. ``` openGauss=# SELECT quote_nullable('O\hello'); quote_nullable ---------------- E'O\\hello' (1 row) ``` If the parameter is null, **NULL** is returned. ``` openGauss=# SELECT quote_nullable(NULL); quote_nullable ---------------- NULL (1 row) ``` * quote\_nullable(value anyelement) Description: Converts the given value to text and then quotes it as a literal. Return type: text Example: ``` openGauss=# SELECT quote_nullable(42.5); quote_nullable ---------------- '42.5' (1 row) ``` If a command similar to the following exists, the given value will be escaped. ``` openGauss=# SELECT quote_nullable(E'O\'42.5'); quote_nullable ---------------- 'O''42.5' (1 row) ``` If a command similar to the following exists, the backslash will be properly doubled. ``` openGauss=# SELECT quote_nullable('O\42.5'); quote_nullable ---------------- E'O\\42.5' (1 row) ``` If the parameter is null, **NULL** is returned. ``` openGauss=# SELECT quote_nullable(NULL); quote_nullable ---------------- NULL (1 row) ``` * substring\_inner(string \[from int] \[for int]) Description: Extracts a substring. **from int** indicates the start position of the truncation. **for int** indicates the number of characters truncated. Return type: text Example: ``` openGauss=# select substring_inner('adcde', 2,3); substring_inner ----------------- dcd (1 row) ``` * substring(string \[from int] \[for int]) Description: Extracts a substring. **from int** indicates the start position of the truncation. **for int** indicates the number of characters truncated. Return type: text Example: ``` openGauss=# SELECT substring('Thomas' from 2 for 3); substring ----------- hom (1 row) ``` * substring(string from *pattern*) Description: Extracts substrings matching the POSIX regular expression. It returns the text that matches the pattern. If no match record is found, a null value is returned. Return type: text Example: ``` openGauss=# SELECT substring('Thomas' from '...$'); substring ----------- mas (1 row) openGauss=# SELECT substring('foobar' from 'o(.)b'); result -------- o (1 row) openGauss=# SELECT substring('foobar' from '(o(.)b)'); result -------- oob (1 row) ``` > \[!NOTE]NOTE > If the POSIX pattern contains any parentheses, the portion of the text that matched the first parenthesized sub-expression (the one whose left parenthesis comes first) is returned. You can put parentheses around the whole expression if you want to use parentheses within it without triggering this exception. * substring(string from *pattern* for *escape*) Description: Extracts substrings matching the SQL regular expression. The declared schema must match the entire data string; otherwise, the function fails and returns a null value. To indicate the part of the pattern that should be returned on success, the pattern must contain two occurrences of the escape character followed by a double quotation mark ("). The text matching the portion of the pattern between these marks is returned. Return type: text Example: ``` openGauss=# SELECT substring('Thomas' from '%#"o_a#"_' for '#'); substring ----------- oma (1 row) ``` * rawcat(raw,raw) Description: Indicates the string concatenation function. Return type: raw Example: ``` openGauss=# SELECT rawcat('ab','cd'); rawcat -------- ABCD (1 row) ``` * regexp\_like(text,text,text) Description: Indicates the mode matching function of a regular expression. Return type: Boolean Example: ``` openGauss=# SELECT regexp_like('str','[ac]'); regexp_like ------------- f (1 row) ``` * regexp\_substr(string text, pattern text \[, position int \[, occurrence int \[, flags text]]]) Description: Extracts substrings from a regular expression. Its function is similar to **substr**. When a regular expression contains multiple parallel brackets, it also needs to be processed. Parameter description: * **string**: source character string used for matching. * **pattern**: regular expression pattern string used for matching. * **position**: start character of the source string used for matching. This parameter is optional. The default value is **1**. * **occurrence**: sequence number of the matched substring to be extracted. This parameter is optional. The default value is **1**. * **flags**: contains zero or multiple single-letter flags that change the matching behavior of the function. This parameter is optional. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the **'\n'** character by default. The meaning of option **n** is the same as that of option **m**. Return type: text Example: ``` openGauss=# SELECT regexp_substr('str','[ac]'); regexp_substr --------------- (1 row) openGauss=# SELECT regexp_substr('foobarbaz', 'b(..)', 3, 2) AS RESULT; result -------- baz (1 row) ``` * regexp\_count(string text, pattern text \[, position int \[, flags text]]) Description: obtains the number of substrings used for matching. Parameter description: * **string**: source character string used for matching. * **pattern**: regular expression pattern string used for matching. * **position**: sequence number of the character to be matched from the source character string. This parameter is optional. The default value is **1**. * **flags**: contains zero or multiple single-letter flags that change the matching behavior of the function. This parameter is optional. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the \*\*'\n'\*\*character by default. The meaning of option **n** is the same as that of option **m**. Return type: int Example: ``` openGauss=# SELECT regexp_count('foobarbaz','b(..)', 5) AS RESULT; result -------- 1 (1 row) ``` * regexp\_instr(string text, pattern text \[, position int \[, occurrence int \[, return\_opt int \[, flags text]]]]) Description: obtains the position (starting from 1) of the substring that meets the matching condition. If no substring is matched, **0** is returned. Parameter description: * **string**: source character string used for matching. * **pattern**: regular expression pattern string used for matching. * **position**: start character of the source string used for matching. This parameter is optional. The default value is **1**. * **occurrence**: sequence number of the matched substring to be replaced. This parameter is optional. The default value is **1**. * **return\_opt**: specifies whether to return the position of the first or last character of the matched substring. This parameter is optional. If the value is **0**, the position of the first character (starting from 1) of the matched substring is returned. If the value is greater than 0, the position of the next character of the end character of the matched substring is returned. The default value is **0**. * **flags**: contains zero or multiple single-letter flags that change the matching behavior of the function. This parameter is optional. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the **'\n'** character by default. The meaning of option **n** is the same as that of option **m**. Return type: int Example: ``` openGauss=# SELECT regexp_instr('foobarbaz','b(..)', 1, 1, 0) AS RESULT; result -------- 4 (1 row) openGauss=# SELECT regexp_instr('foobarbaz','b(..)', 1, 2, 0) AS RESULT; result -------- 7 (1 row) ``` * regexp\_matches(string text, pattern text \[, flags text]) Description: Returns all captured substrings resulting from matching a POSIX regular expression against **string**. If the pattern does not match, the function returns no rows. If the pattern contains no parenthesized sub-expressions, then each row returned is a single-element text array containing the substring matching the whole pattern. If the pattern contains parenthesized sub-expressions, the function returns a text array whose *n\_th element is the substring matching the \_n*th parenthesized sub-expression of the pattern. The optional **flags** argument contains zero or multiple single-letter flags that change function behavior. **i** indicates that the matching is not related to uppercase and lowercase. **g** indicates that each matched substring is replaced, instead of replacing only the first one. > \[!TIP]NOTICE > If the last parameter is provided but the parameter value is an empty string ('') and the SQL compatibility mode of the database is set to A, the returned result is an empty set. This is because the A compatibility mode treats the empty string ('') as **NULL**. To resolve this problem, you can: > > * Change the database SQL compatibility mode to C. > * Do not provide the last parameter or do not set the last parameter to an empty string. Return type: SETOF text\[] Example: ``` openGauss=# SELECT regexp_matches('foobarbequebaz', '(bar)(beque)'); regexp_matches ---------------- {bar,beque} (1 row) openGauss=# SELECT regexp_matches('foobarbequebaz', 'barbeque'); regexp_matches ---------------- {barbeque} (1 row) openGauss=# SELECT regexp_matches('foobarbequebazilbarfbonk', '(b[^b]+)(b[^b]+)', 'g'); result -------------- {bar,beque} {bazil,barf} (2 rows) ``` * regexp\_split\_to\_array(string text, pattern text \[, flags text ]) Description: Splits **string** using a POSIX regular expression as the delimiter. The **regexp\_split\_to\_array** function behaves the same as **regexp\_split\_to\_table**, except that **regexp\_split\_to\_array** returns its result as an array of text. Return type: text\[] Example: ``` openGauss=# SELECT regexp_split_to_array('hello world', E'\\s+'); regexp_split_to_array ----------------------- {hello,world} (1 row) ``` * regexp\_split\_to\_table(string text, pattern text \[, flags text]) Description: Splits **string** using a POSIX regular expression as the delimiter. If there is no match to the pattern, the function returns the string. If there is at least one match, for each match it returns the text from the end of the last match (or the beginning of the string) to the beginning of the match. When there are no more matches, it returns the text from the end of the last match to the end of the string. The **flags** parameter is a text string containing zero or more single-letter flags that change the function's behavior. **i** indicates case-insensitive matching. Return type: SETOF text Example: ``` openGauss=# SELECT regexp_split_to_table('hello world', E'\\s+'); regexp_split_to_table ----------------------- hello world (2 rows) ``` * repeat(string text, number int ) Description: Repeats **string** the specified number of times. Return type: text Example: ``` openGauss=# SELECT repeat('Pg', 4); repeat ---------- PgPgPgPg (1 row) ``` > \[!NOTE]NOTE > The maximum size of memory allocated at a time cannot exceed 1 GB due to the memory allocation mechanism of the database. Therefore, the maximum value of **number** cannot exceed (1 GB – **x**)/**lengthb** (**string**) – 1. **x** indicates the length of the header information, which is usually greater than 4 bytes. The value varies among different scenarios. * replace(string text, from text, to text) Description: Replaces all occurrences in **string** of substring **from** with substring **to**. Return type: text Example: ``` openGauss=# SELECT replace('abcdefabcdef', 'cd', 'XXX'); replace ---------------- abXXXefabXXXef (1 row) ``` * replace(string, substring) Description: Deletes all substrings in a string. String type: text Substring type: text Return type: text Example: ``` openGauss=# SELECT replace('abcdefabcdef', 'cd'); replace ---------------- abefabef (1 row) ``` * replace(string, null) Description: Returns the original string. String type: text Return type: text Example: ``` openGauss=# select replace('abcd', null); replace --------- abcd (1 row) ``` * reverse(str) Description: Returns the reversed string. Return type: text Example: ``` openGauss=# SELECT reverse('abcde'); reverse --------- edcba (1 row) ``` * right(str text, n int) Description: Returns the last *n\_ characters in a string. When \_n* is negative, all but the first **|n|** characters are returned. Return type: text Example: ``` openGauss=# SELECT right('abcde', 2); right ------- de (1 row) openGauss=# SELECT right('abcde', -2); right ------- cde (1 row) ``` * rpad(string text, length int \[, fill text]) Description: Fills up **string** to **length** by appending the characters **fill** (a space by default). If **string** is already longer than **length**, then it is truncated. Return type: text Example: ``` openGauss=# SELECT rpad('hi', 5, 'xy'); rpad ------- hixyx (1 row) ``` * rtrim(string text \[, characters text]) Description: Removes the longest string containing only characters from characters (a space by default) from the end of string. Return type: text Example: ``` openGauss=# SELECT rtrim('trimxxxx', 'x'); rtrim ------- trim (1 row) ``` * substrb(text,int,int) Description: Extracts a substring. The first **int**indicates the start position of the subtraction. The second **int** indicates the number of characters extracted. Return type: text Example: ``` openGauss=# SELECT substrb('string',2,3); substrb --------- tri (1 row) ``` * substrb(text,int) Description: Extracts a substring. **int** indicates the start position of the extraction. Return type: text Example: ``` openGauss=# SELECT substrb('string',2); substrb --------- tring (1 row) ``` * substr(bytea,from,count) Description: Extracts a substring from **bytea**. **from** specifies the position where the extraction starts. **count** specifies the length of the extracted substring. Return type: text Example: ``` openGauss=# SELECT substr('string',2,3); substr -------- tri (1 row) ``` * string || string Description: Concatenates strings. Return type: text Example: ``` openGauss=# SELECT 'MPP'||'DB' AS RESULT; result -------- MPPDB (1 row) ``` * string || non-string or non-string || string Description: Concatenates strings and non-strings. Return type: text Example: ``` openGauss=# SELECT 'Value: '||42 AS RESULT; result ----------- Value: 42 (1 row) ``` * split\_part(string text, delimiter text, field int) Description: Splits **string** on **delimiter** and returns the **field**th column (counting from text of the first appeared delimiter). Return type: text Example: ``` openGauss=# SELECT split_part('abc~@~def~@~ghi', '~@~', 2); split_part ------------ def (1 row) ``` * strpos(string, substring) Description: Specifies the position of a substring. It is the same as **position(substring in string)**. However, the parameter sequences of them are reversed. Return type: int Example: ``` openGauss=# SELECT strpos('source', 'rc'); strpos -------- 4 (1 row) ``` * to\_hex(number int or bigint) Description: Converts a number to a hexadecimal expression. Return type: text Example: ``` openGauss=# SELECT to_hex(2147483647); to_hex ---------- 7fffffff (1 row) ``` * translate(string text, from text, to text) Description: Any character in **string** that matches a character in the **from** set is replaced by the corresponding character in the **to** set. If **from** is longer than **to**, extra characters occurred in **from** are removed. Return type: text Example: ``` openGauss=# SELECT translate('12345', '143', 'ax'); translate ----------- a2x5 (1 row) ``` * length(string) Description: Obtains the number of characters in a string. Return type: integer Example: ``` openGauss=# SELECT length('abcd'); length -------- 4 (1 row) ``` * lengthb(string) Description: Obtains the number of characters in a string. The value depends on character sets (GBK and UTF8). Return type: integer Example: ``` openGauss=# SELECT lengthb('Chinese'); lengthb --------- 7 (1 row) ``` * substr(string,from) Description: Extracts substrings from a string. **from** indicates the start position of the extraction. * If **from** starts at 0, the value **1** is used. * If the value of **from** is positive, all characters from **from** to the end are extracted. * If the value of **from** is negative, the last *n* characters in the string are extracted, in which **n** indicates the absolute value of **from**. Return type: varchar Example: If the value of **from** is positive: ``` openGauss=# SELECT substr('ABCDEF',2); substr -------- BCDEF (1 row) ``` If the value of **from** is negative: ``` openGauss=# SELECT substr('ABCDEF',-2); substr -------- EF (1 row) ``` * substr(string,from,count) Description: Extracts substrings from a string. **from** indicates the start position of the extraction. **count** indicates the length of the extracted substring. * If **from** starts at 0, the value **1** is used. * If the value of **from** is positive, extract **count** characters starting from **from**. * If the value of **from** is negative, extract the last **n** **count** characters in the string, in which **n** indicates the absolute value of **from**. * If the value of **count** is smaller than **1**, **null** is returned. Return type: varchar Example: If the value of **from** is positive: ``` openGauss=# SELECT substr('ABCDEF',2,2); substr -------- BC (1 row) ``` If the value of **from** is negative: ``` openGauss=# SELECT substr('ABCDEF',-3,2); substr -------- DE (1 row) ``` * substrb(string,from) Description: The functionality of this function is the same as that of **SUBSTR(string,from)**. However, the calculation unit is byte. Return type: bytea Example: ``` openGauss=# SELECT substrb('ABCDEF',-2); substrb --------- EF (1 row) ``` * substrb(string,from,count) Description: The functionality of this function is the same as that of **SUBSTR(string,from,count)**. However, the calculation unit is byte. Return type: bytea Example: ``` openGauss=# SELECT substrb('ABCDEF',2,2); substrb --------- BC (1 row) ``` * trim(\[leading |trailing |both] \[characters] from string) Description: Removes the longest string containing only the characters (a space by default) from the start/end/both ends of the string. Return type: text Example: ``` openGauss=# SELECT trim(BOTH 'x' FROM 'xTomxx'); btrim ------- Tom (1 row) ``` ``` openGauss=# SELECT trim(LEADING 'x' FROM 'xTomxx'); ltrim ------- Tomxx (1 row) ``` ``` openGauss=# SELECT trim(TRAILING 'x' FROM 'xTomxx'); rtrim ------- xTom (1 row) ``` * rtrim(string \[, characters]) Description: Removes the longest string containing only characters from characters (a space by default) from the end of string. Return type: text Example: ``` openGauss=# SELECT rtrim('TRIMxxxx','x'); rtrim ------- TRIM (1 row) ``` * ltrim(string \[, characters]) Description: Removes the longest string containing only characters from characters (a space by default) from the start of string. Return type: text Example: ``` openGauss=# SELECT ltrim('xxxxTRIM','x'); ltrim ------- TRIM (1 row) ``` * upper(string) Description: Converts the string into the uppercase. Return type: text Example: ``` openGauss=# SELECT upper('tom'); upper ------- TOM (1 row) ``` * lower(string) Description: Converts the string into the lowercase. Return type: text Example: ``` openGauss=# SELECT lower('TOM'); lower ------- tom (1 row) ``` * rpad(string varchar, length int \[, fill varchar]) Description: Fills up **string** to **length** by appending the characters **fill** (a space by default). If **string** is already longer than **length**, then it is truncated. **length** in openGauss indicates the character length. One Chinese character is counted as one character. Return type: varchar Example: ``` openGauss=# SELECT rpad('hi',5,'xyza'); rpad ------- hixyz (1 row) ``` ``` openGauss=# SELECT rpad('hi',5,'abcdefg'); rpad ------- hiabc (1 row) ``` * instr(string,substring\[,position,occurrence]) Description: Queries and returns the value of the substring position that occurs the **occurrence** (1 by default) times from the **position** (1 by default) in the string. * If the value of **position** is **0**, **0** is returned. * If the value of **position** is negative, the search is performed backwards from the last *n\_th character in the string, in which \_n* indicates the absolute value of **position**. In this function, the calculation unit is character. One Chinese character is one character. Return type: integer Example: ``` openGauss=# SELECT instr('corporate floor','or', 3); instr ------- 5 (1 row) ``` ``` openGauss=# SELECT instr('corporate floor','or',-3,2); instr ------- 2 (1 row) ``` * initcap(string) Description: Converts the first letter of each word in the string into the uppercase and the other letters into the lowercase. Return type: text Example: ``` openGauss=# SELECT initcap('hi THOMAS'); initcap ----------- Hi Thomas (1 row) ``` * ascii(string) Description: Indicates the ASCII code of the first character in the string. Return type: integer Example: ``` openGauss=# SELECT ascii('xyz'); ascii ------- 120 (1 row) ``` * replace(string varchar, search\_string varchar, replacement\_string varchar) Description: Replaces all **search\_string** in the string with **replacement\_string**. Return type: varchar Example: ``` openGauss=# SELECT replace('jack and jue','j','bl'); replace ---------------- black and blue (1 row) ``` * lpad(string varchar, length int\[, repeat\_string varchar]) Description: Adds a series of **repeat\_string** (a space by default) on the left of the string to generate a new string with the total length of *n*. If the length of the string is longer than the specified length, the function truncates the string and returns the substrings with the specified length. Return type: varchar Example: ``` openGauss=# SELECT lpad('PAGE 1',15,'*.'); lpad ----------------- *.*.*.*.*PAGE 1 (1 row) ``` ``` openGauss=# SELECT lpad('hello world',5,'abcd'); lpad ------- hello (1 row) ``` * concat(str1,str2) Description: Connects str1 and str2 and returns the string. > \[!TIP]NOTICE > If the SQL compatibility mode is set to **MY** and **str1** or **str2** is set to **NULL**, **NULL** will be returned. Return type: varchar Example: ``` openGauss=# SELECT concat('Hello', ' World!'); concat -------------- Hello World! (1 row) openGauss=# SELECT concat('Hello', NULL); concat -------- Hello (1 row) ``` * chr(integer) Description: Specifies the character of the ASCII code. Return type: varchar Example: ``` openGauss=# SELECT chr(65); chr ----- A (1 row) ``` * regexp\_substr(source\_char, pattern) Description: Extracts substrings from a regular expression. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the period (.) cannot match the **'\n'** character. If **aformat\_regexp\_match** is not contained, the period (.) matches the **'\n'** character by default. Return type: text Example: ``` openGauss=# SELECT regexp_substr('500 Hello World, Redwood Shores, CA', ',[^,]+,') "REGEXPR_SUBSTR"; REGEXPR_SUBSTR ------------------- , Redwood Shores, (1 row) ``` * regexp\_replace(string, pattern, replacement \[,flags ]) Description: Replaces substrings matching the POSIX regular expression. The source string is returned unchanged if there is no match to the pattern. If there is a match, the source string is returned with the replacement string substituted for the matching substring. The replacement string can contain **\n**, where **n** is 1 through 9, to indicate that the source substring matching the *n*th parenthesized sub-expression of the pattern should be inserted, and it can contain **\\&** to indicate that the substring matching the entire pattern should be inserted. The optional **flags** argument contains zero or multiple single-letter flags that change the function behavior. **i** indicates that the matching is not related to uppercase and lowercase. **g** indicates that each matched substring is replaced, instead of replacing only the first one. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the **'\n'** character by default. The meaning of option **n** is the same as that of option **m**. Return type: varchar Example: ``` openGauss=# SELECT regexp_replace('Thomas', '.[mN]a.', 'M'); regexp_replace ---------------- ThM (1 row) openGauss=# SELECT regexp_replace('foobarbaz','b(..)', E'X\\1Y', 'g') AS RESULT; result ------------- fooXarYXazY (1 row) ``` * repexp\_replace(string text, pattern text \[, replacement text \[, position int \[, occurrence int \[, flags text]]]]) Description: Replaces substrings matching the POSIX regular expression. The source string is returned unchanged if there is no match to the pattern. If there is a match, the source string is returned with the replacement string substituted for the matching substring. Parameter description: * **string**: source character string used for matching. * **pattern**: regular expression pattern string used for matching. * **replacement**:character string used to replace the matched substring. This parameter is optional. If no parameter value is specified or the parameter value is null, the parameter value is replaced with an empty string. * **position**: start character of the source string used for matching. This parameter is optional. The default value is **1**. * **occurrence**: sequence number of the matched substring to be replaced. This parameter is optional. The default value is **0**, indicating that all matched substrings are replaced. * **flags**: contains zero or multiple single-letter flags that change the matching behavior of the function. This parameter is optional. **m** indicates multi-line matching. If the SQL syntax is compatible with products A and B and the value of the GUC parameter **behavior\_compat\_options** contains **aformat\_regexp\_match**, the option **n** indicates that the period (.) can match the **'\n'** character. If **n** is not specified in flags, the period (.) cannot match the **'\n'** character by default. If the value does not contain **aformat\_regexp\_match**, the period (.) matches the **'\n'** character by default. The meaning of option **n** is the same as that of option **m**. Return type: text Example: ``` openGauss=# SELECT regexp_replace('foobarbaz','b(..)', E'X\\1Y', 2, 2, 'n') AS RESULT; result ------------ foobarXazY (1 row) ``` * concat\_ws(sep text, str"any" \[, str"any" \[, ...] ]) Description: Uses the first parameter as the separator, which is associated with all following parameters. The **NULL** parameter is ignored. > \[!TIP]NOTICE > > * If the first parameter value is **NULL**, the returned result is **NULL**. > * If the first parameter is provided but the parameter value is an empty string ('') and the SQL compatibility mode of the database is set to **A**, the returned result is **NULL**. This is because the A compatibility mode treats the empty string ('') as **NULL**. To resolve this problem, you can change the SQL compatibility mode of the database to **B**, **C**, or **PG**. Return type: text Example: ``` openGauss=# SELECT concat_ws(',', 'ABCDE', 2, NULL, 22); concat_ws ------------ ABCDE,2,22 (1 row) ``` * nlssort(string text, sort\_method text) Description: Returns the encoding value of a string in the sorting mode specified by **sort\_method**. The encoding value can be used for sorting and determines the sequence of the string in the sorting mode. Currently, **sort\_method** can be set to **nls\_sort=schinese\_pinyin\_m** or **nls\_sort=generic\_m\_ci**. **nls\_sort=generic\_m\_ci** supports only the case-insensitive order for English characters. String type: text sort\_method type: text Return type: text Example: ``` openGauss=# SELECT nlssort('A', 'nls_sort=schinese_pinyin_m'); nlssort ---------------- 01EA0000020006 (1 row) openGauss=# SELECT nlssort('A', 'nls_sort=generic_m_ci'); nlssort ---------------- 01EA000002 (1 row) ``` * convert(string bytea, src\_encoding name, dest\_encoding name) Description: Converts the bytea string to **dest\_encoding**. **src\_encoding** specifies the source code encoding. The string must be valid in this encoding. Return type: bytea Example: ``` openGauss=# SELECT convert('text_in_utf8', 'UTF8', 'GBK'); convert ---------------------------- \x746578745f696e5f75746638 (1 row) ``` > \[!NOTE]NOTE > If the rule for converting between source to target encoding (for example, GBK and LATIN1) does not exist, the string is returned without conversion. See the **pg\_conversion** system catalog for details. > Example: > ```` > ```sql ```` ```` >openGauss=# show server_encoding; > server_encoding > ----------------- > LATIN1 > (1 row) > openGauss=# SELECT convert_from('some text', 'GBK'); > convert_from > -------------- > some text > (1 row) > db_latin1=# SELECT convert_to('some text', 'GBK'); > convert_to > ---------------------- > \x736f6d652074657874 > (1 row) > db_latin1=# SELECT convert('some text', 'GBK', 'LATIN1'); > convert > ---------------------- > \x736f6d652074657874 > (1 row) > ``` ```` * convert\_from(string bytea, src\_encoding name) Description: Converts the long bytea using the coding mode of the database. **src\_encoding** specifies the source code encoding. The string must be valid in this encoding. Return type: text Example: ``` openGauss=# SELECT convert_from('text_in_utf8', 'UTF8'); convert_from -------------- text_in_utf8 (1 row) ``` * convert\_to(string text, dest\_encoding name) Description: Converts a string to **dest\_encoding**. Return type: bytea Example: ``` openGauss=# SELECT convert_to('some text', 'UTF8'); convert_to ---------------------- \x736f6d652074657874 (1 row) ``` * string \[NOT] LIKE pattern \[ESCAPE escape-character] Description: Specifies the pattern matching function. If the pattern does not include a percentage sign (%) or an underscore (\_), this mode represents itself only. In this case, the behavior of LIKE is the same as the equal operator. The underscore (\_) in the pattern matches any single character while one percentage sign (%) matches no or multiple characters. To match with underscores (\_) or percent signs (%), corresponding characters in **pattern** must lead escape characters. The default escape character is a backward slash (\\) and can be specified using the **ESCAPE** clause. To match with escape characters, enter two escape characters. Return type: Boolean Example: ``` openGauss=# SELECT 'AA_BBCC' LIKE '%A@_B%' ESCAPE '@' AS RESULT; result -------- t (1 row) ``` ``` openGauss=# SELECT 'AA_BBCC' LIKE '%A@_B%' AS RESULT; result -------- f (1 row) ``` ``` openGauss=# SELECT 'AA@_BBCC' LIKE '%A@_B%' AS RESULT; result -------- t (1 row) ``` * REGEXP\_LIKE(source\_string, pattern \[, match\_parameter]) Description: Indicates the mode matching function of a regular expression. **source\_string** indicates the source string and **pattern** indicates the matching pattern of the regular expression. **match\_parameter** indicates the matching items and the values are as follows: * 'i': case-insensitive * 'c': case-sensitive * 'n': allowing the metacharacter "." in a regular expression to be matched with a linefeed. * 'm': allows **source\_string** to be regarded as multiple rows. If **match\_parameter** is ignored, **case-sensitive** is enabled by default, "." is not matched with a linefeed, and **source\_string** is regarded as a single row. Return type: Boolean Example: ``` openGauss=# SELECT regexp_like('ABC', '[A-Z]'); regexp_like ------------- t (1 row) ``` ``` openGauss=# SELECT regexp_like('ABC', '[D-Z]'); regexp_like ------------- f (1 row) ``` ``` openGauss=# SELECT regexp_like('ABC', '[a-z]','i'); regexp_like ------------- t (1 row) ``` * format(formatstr text \[, str"any" \[, ...] ]) Description: Formats a string. Return type: text Example: ``` openGauss=# SELECT format('Hello %s, %1$s', 'World'); format -------------------- Hello World, World (1 row) ``` * md5(string) Description: Encrypts a string in MD5 mode and returns a value in hexadecimal form. > \[!NOTE]NOTE > The MD5 encryption algorithm is not recommended because it has lower security and poses security risks. Return type: text Example: ``` openGauss=# SELECT md5('ABC'); md5 ---------------------------------- 902fbdd2b1df0c4f70b4a5d23525e932 (1 row) ``` * sha(string) / sha1(string) Description: Encrypts a string using SHA1 and returns a hexadecimal number. The sha and sha1 functions are the same. > \[!NOTE]NOTE > The SHA1 encryption algorithm is not recommended because it has lower security and poses security risks. > This function is valid only when openGauss is compatible with the MY type (that is, sql\_compatibility = 'B'). Return type: text Example: ``` openGauss=# select sha('ABC'); sha ------------------------------------------ 3c01bdbb26f358bab27f267924aa2c9a03fcfdb8 (1 row) openGauss=# select sha1('ABC'); sha1 ------------------------------------------ 3c01bdbb26f358bab27f267924aa2c9a03fcfdb8 (1 row) ``` * sha2(string, hash\_length) Description: Encrypts a string in SHA2 mode and returns a value in hexadecimal form. **hash\_length**: corresponds to the SHA2 algorithm. The value can be **0**(SHA-256), **224**(SHA-224), **256**(SHA-256), **384**(SHA-384), or **512**(SHA-512). For other values, **NULL** is returned. > \[!NOTE]NOTE > The SHA224 encryption algorithm is not recommended because it has lower security and poses security risks. > The SHA2 function records hash plaintext in logs. Therefore, you are not advised to use this function to encrypt sensitive information such as keys. > This function is valid only when openGauss is compatible with the MY type (that is, sql\_compatibility = 'B'). Return type: text Example: ``` openGauss=# select sha2('ABC',224); sha2 ---------------------------------------------------------- 107c5072b799c4771f328304cfe1ebb375eb6ea7f35a3aa753836fad (1 row) openGauss=# select sha2('ABC',256); sha2 ------------------------------------------------------------------ b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78 (1 row) openGauss=# select sha2('ABC',0); sha2 ------------------------------------------------------------------ b5d4045c3f466fa91fe2cc6abe79232a1a57cdf104f7a26e716e0a1e2789df78 (1 row) ``` * decode(string text, format text) Description: Decodes binary data from textual representation. Return type: bytea Example: ``` openGauss=# SELECT decode('MTIzAAE=', 'base64'); decode -------------- \x3132330001 (1 row) ``` * similar\_escape(pat text, esc text) Description: Converts a regular expression of the SQL:2008 style to the POSIX style. Return type: text Example: ``` openGauss=# select similar_escape('\s+ab','2'); similar_escape ---------------- ^(?:\\s+ab)$ (1 row) ``` * svals(hstore) Description: Obtains the value of the hstore type. Return type: SETOF text Example: ``` openGauss=# select svals('"aa"=>"bb"'); svals ------- bb (1 row) ``` * tconvert(key text, value text) Description: Converts character strings to the hstore format. Return type: hstore Example: ``` openGauss=# select tconvert('aa', 'bb'); tconvert ------------ "aa"=>"bb" (1 row) ``` * find\_in\_set(text, set) Description: Finds the position of a given member in a set, counting from 1. If no record is found, 0 is returned. Return type: int2 Example: ``` openGauss=# select site, find_in_set('wuhan', site) from employee; site | find_in_set -----------------+------------- beijing,nanjing | 0 beijing,wuhan | 2 (2 rows) ``` * encode(data bytea, format text) Description: Encodes binary data into a textual representation. Return type: text Example: ``` openGauss=# SELECT encode(E'123\\000\\001', 'base64'); encode ---------- MTIzAAE= (1 row) ``` > \[!NOTE]NOTE > > * For a string containing newline characters, for example, a string consisting of a newline character and a space, the value of **length** and **lengthb** in openGauss is 2. > * In openGauss, *n\_ in the CHAR(n) type indicates the number of characters. Therefore, for multiple-octet coded character sets, the length returned by the LENGTHB function may be longer than \_n*. > * openGauss supports multiple types of databases, including A, B, C, and PG. If the database type is not specified, A is used by default. The lexical analyzer of A database is different from that of the other three databases. In A database, an empty character string is considered as **NULL**. Therefore, when a type A database is used, if a **NULL** character string is used as a parameter in the preceding character operation function, no output is displayed. For example: > > ``` > openGauss=# SELECT translate('12345','123',''); > translate > ----------- > (1 row) > ``` > > This is because the kernel checks whether the input parameter contains **NULL** before calling the corresponding function. If yes, the kernel does not call the corresponding function. As a result, no output is displayed. In PG mode, the processing of character strings is the same as that of PostgreSQL. Therefore, the preceding problem does not occur. --- --- url: /en/docs/latest-lite/sql_reference/character_types.md --- # Character Types [Table 1](#en-us_topic_0283136755_en-us_topic_0237121950_en-us_topic_0059777889_en-us_topic_0058966269_table29186418) lists the character data types supported by openGauss. For string operators and related built-in functions, see [Character Processing Functions and Operators](character_processing_functions_and_operators.md). **Table 1** Character types > \[!NOTE]NOTE > > 1. In addition to the restriction on the size of each column, the total size of each tuple cannot exceed 1 GB minus 1 byte and is affected by the control header information of the column, the control header information of the tuple, and whether null fields exist in the tuple. > 2. NCHAR is the alias of the bpchar type, and NCHAR(n) is the alias of the VARCHAR(n) type. > 3. Only advanced packages related to dbe\_lob support CLOBs whose size is greater than 1 GB. System functions do not support CLOBs whose size is greater than 1 GB. In openGauss, there are two other fixed-length character types, as shown in [Table 2](#en-us_topic_0283136755_en-us_topic_0237121950_en-us_topic_0059777889_tf74658686f5e4d979adf0ac04769ea16). The **name** type exists only for the storage of identifiers in the internal system catalogs and is not intended for use by general users. Its length is currently defined as 64 bytes (63 usable characters plus terminator). The type **"char"** only uses one byte of storage. It is internally used in the system catalogs as a simplistic enumeration type. **Table 2** Special character types ## Examples ``` -- Create a table. openGauss=# CREATE TABLE char_type_t1 ( CT_COL1 CHARACTER(4) ); -- Insert data. openGauss=# INSERT INTO char_type_t1 VALUES ('ok'); -- Query data in the table. openGauss=# SELECT ct_col1, char_length(ct_col1) FROM char_type_t1; ct_col1 | char_length ---------+------------- ok | 4 (1 row) -- Delete the table. openGauss=# DROP TABLE char_type_t1; -- Create a table. openGauss=# CREATE TABLE char_type_t2 ( CT_COL1 VARCHAR(5) ); -- Insert data. openGauss=# INSERT INTO char_type_t2 VALUES ('ok'); openGauss=# INSERT INTO char_type_t2 VALUES ('good'); -- Specify the type length. An error is reported if an inserted string exceeds this length. openGauss=# INSERT INTO char_type_t2 VALUES ('too long'); ERROR: value too long for type character varying(5) CONTEXT: referenced column: ct_col1 -- Specify the type length. A string exceeding this length is truncated. openGauss=# INSERT INTO char_type_t2 VALUES ('too long'::varchar(5)); -- Query data. openGauss=# SELECT ct_col1, char_length(ct_col1) FROM char_type_t2; ct_col1 | char_length ---------+------------- ok | 2 good | 4 too l | 5 (3 rows) -- Delete data. openGauss=# DROP TABLE char_type_t2; ``` --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_character_types.md --- # Character Types Compared with the original openGauss, Dolphin modifies the character types as follows: 1. The meaning of **n** of the CHARACTER/NCHAR type is modified. **n** indicates the character length instead of the byte length. 2. During comparison of all character data types, spaces at the end are ignored, for example, in the WHERE and JOIN scenarios. For example, **'a'::text = 'a'::text** is true. For the VARCHAR, VARCHAR2, NVARCHAR2, NVARCHAR, TEXT, and CLOB types, HASH JOIN and HASH AGG ignore spaces at the end only when **string\_hash\_compatible** is set to **on**. 3. The optional modifier (n) is added for TEXT. That is, the usage of TEXT(n) is supported. **n** is meaningless and does not affect any performance. 4. The TINYTEXT(n)/MEDIUMTEXT(n)/LONGTEXT(n) data type is added, which is the alias of TEXT. **n** is meaningless and does not affect any performance. **Table 1** Character types Example: ``` --Create a table. openGauss=# CREATE TABLE char_type_t1 ( CT_COL1 CHARACTER(4), CT_COL2 TEXT(10), CT_COL3 TINYTEXT(11), CT_COL4 MEDIUMTEXT(12), CT_COL5 LONGTEXT(13) ); --View a table structure. openGauss=# \d char_type_t1 Table "public.char_type_t1" Column | Type | Modifiers ---------+--------------+----------- ct_col1 | character(4) | ct_col2 | text | ct_col3 | text | ct_col4 | text | ct_col5 | text | --Insert data. openGauss=# INSERT INTO char_type_t1 VALUES ('Four characters'); openGauss=# INSERT INTO char_type_t1 VALUES('e '); --View data. openGauss=# SELECT CT_COL1,length(CT_COL1) FROM char_type_t1; ct_col1 | length ----------+-------- Four characters | 4 e | 1 (2 rows) --Filter data. openGauss=# SELECT CT_COL1 FROM char_type_t1 WHERE CT_COL1 = 'e'; ct_col1 --------- e (1 row) openGauss=# SELECT CT_COL1 FROM char_type_t1 WHERE CT_COL1 = 'e '; ct_col1 --------- e (1 row) --Delete the table. openGauss=# DROP TABLE char_type_t1; ``` --- --- url: /en/docs/latest/sql_reference/character_types.md --- # Character Types [Table 1](#en-us_topic_0283136755_en-us_topic_0237121950_en-us_topic_0059777889_en-us_topic_0058966269_table29186418) lists the character data types supported by openGauss. For string operators and related built-in functions, see [Character Processing Functions and Operators](character_processing_functions_and_operators.md). **Table 1** Character types > \[!NOTE]NOTE > > 1. In addition to the restriction on the size of each column, the total size of each tuple cannot exceed 1 GB minus 1 byte and is affected by the control header information of the column, the control header information of the tuple, and whether null fields exist in the tuple. > 2. NCHAR is the alias of the bpchar type, and NCHAR(n) is the alias of the VARCHAR(n) type. > 3. Only advanced packages related to dbe\_lob support CLOBs whose size is greater than 1 GB. System functions do not support CLOBs whose size is greater than 1 GB. In openGauss, there are two other fixed-length character types, as shown in [Table 2](#en-us_topic_0283136755_en-us_topic_0237121950_en-us_topic_0059777889_tf74658686f5e4d979adf0ac04769ea16). The **name** type exists only for the storage of identifiers in the internal system catalogs and is not intended for use by general users. Its length is currently defined as 64 bytes (63 usable characters plus terminator). The type **"char"** only uses one byte of storage. It is internally used in the system catalogs as a simplistic enumeration type. **Table 2** Special character types ## Examples ``` -- Create a table. openGauss=# CREATE TABLE char_type_t1 ( CT_COL1 CHARACTER(4) ); -- Insert data. openGauss=# INSERT INTO char_type_t1 VALUES ('ok'); -- Query data in the table. openGauss=# SELECT ct_col1, char_length(ct_col1) FROM char_type_t1; ct_col1 | char_length ---------+------------- ok | 4 (1 row) -- Delete the table. openGauss=# DROP TABLE char_type_t1; -- Create a table. openGauss=# CREATE TABLE char_type_t2 ( CT_COL1 VARCHAR(5) ); -- Insert data. openGauss=# INSERT INTO char_type_t2 VALUES ('ok'); openGauss=# INSERT INTO char_type_t2 VALUES ('good'); -- Specify the type length. An error is reported if an inserted string exceeds this length. openGauss=# INSERT INTO char_type_t2 VALUES ('too long'); ERROR: value too long for type character varying(5) CONTEXT: referenced column: ct_col1 -- Specify the type length. A string exceeding this length is truncated. openGauss=# INSERT INTO char_type_t2 VALUES ('too long'::varchar(5)); -- Query data. openGauss=# SELECT ct_col1, char_length(ct_col1) FROM char_type_t2; ct_col1 | char_length ---------+------------- ok | 2 good | 4 too l | 5 (3 rows) -- Delete data. openGauss=# DROP TABLE char_type_t2; ``` --- --- url: /zh/docs/latest/ograc/sql_reference/character_types.md --- # Character Types **表 1** 字符类型 | 名称 | 描述 | 存储空间 | | :------------ | :------------ | :------------ | | CHAR(size \[BYTE | CHAR]) | 存储定长字节或者字符串1. BYTE表示字节(默认)2. CHAR表示字符串 | 1 ~ 8000字节 | | NCHAR(size) | 等同于CHAR(size CHAR),用于存储定长字符串 | 1 ~ 8000字节 | | NATIONAL CHARACTER(size) | 等同于CHAR(size CHAR),用于存储定长字符串,前提需要设置参数use\_bison\_parser=true | 1 ~ 8000字节 | | NATIONAL CHAR(size) | 等同于CHAR(size CHAR),用于存储定长字符串,前提需要设置参数use\_bison\_parser=true | 1 ~ 8000字节 | | CLOB/NCLOB/TEXT/LONGTEXT/LONG | 存储大对象变长字符串 | 0 ~ (4G-1) | | VARCHAR/VARCHAR2(size \[BYTE | CHAR]) | 存储变长字节或字符串1. size表示最大能容纳的字节或字符数2. BYTE表示字节(默认)3. CHAR表示字符串 | 1 ~ 8000字节 | | NVARCHAR/NVARCHAR2(size) | 等同于VARCHAR(size CHAR),用于存储变长字符串 | 1 ~ 8000字节 | | NATIONAL CHARACTER VARYING(size) | 等同于VARCHAR(size CHAR),用于存储变长字符串,前提需要设置参数use\_bison\_parser=true | 1 ~ 8000字节 | | NATIONAL CHAR VARYING(size) | 等同于VARCHAR(size CHAR),用于存储变长字符串,前提需要设置参数use\_bison\_parser=true | 1 ~ 8000字节 | | NCHAR VARYING(size) | 等同于VARCHAR(size CHAR),用于存储变长字符串,前提需要设置参数use\_bison\_parser=true | 1 ~ 8000字节 | | ROWID | 近似等同于CHAR(18),用于存储特定格式的字符串,仅由'A'-'Z','a'-'z','0'-'9','/','+'组成 | 18字节 | > **说明:** > > * 当前支持UTF-8和GBK字符集。UTF-8字符集中汉字和全角字符占2~6个字节,数字、英文字符等都是一个字节;GBK字符集中汉字和全角字符占2个字节,数字、英文字符等都是一个字节。 > * 当前支持N开头的字面量使用方法,例如`select N'1234'`,前提需要设置参数use\_bison\_parser=true。 * ROWID 合法的rowid数据类型由18个字符组成,Rowid可以被拆解成4段,从前往后的长度依次是6,3,6,3,名字依次简写表示为object,rfile,block,row。 其中每个字符可以理解成一个64进制的数字,其中: 'A'-'Z' 表示数字从0到25,'a'-z'表示数字从26到51,'0'-'9'表示52到61,'+'表示62,'/'表示63。 例如有rowid,AAAAA/AA/AAAAA/IAA, 则object是AAAAA/ ,rfile是AA/,block是AAAAA/,row是IAA 其中oject,rfile,block就表示数字63,row表示2^15 (001000 000000 000000)。 获得了rowid各个段的数值,需要检查值是否在范围内, 其中 0<= object < (2^32) , 0 <= rfile < (2^10) , 0 <= block < (2^22) , 0 <= row < (2^15) 上面的示例中row是2^15 (I表示数字8,IAA就是8\*2^12),无法用15位bit表示(row>=2^15),即是一个非法的row段,也就是非法的rowid格式。 例外的,由18个字符'A'组成的rowid属于非法值。 示例: ``` --创建具有定长和变长字符类型数据的表。 SQL> CREATE TABLE char_type_t1 ( a CHAR(5), b VARCHAR(5), c NCHAR(10), d CLOB, e NVARCHAR2(10) ); --插入数据。 SQL> INSERT INTO char_type_t1 VALUES ('ok', 'ok', 'abcdef', 'abcdef', 'abcdef'); SQL> INSERT INTO char_type_t1 VALUES ('good', 'good', 'good', 'good', 'good'); SQL> SELECT char_length(a), char_length(b), char_length(c), char_length(d), char_length(e) from char_type_t1; CHAR_LENGTH(A) CHAR_LENGTH(B) CHAR_LENGTH(C) CHAR_LENGTH(D) CHAR_LENGTH(F) -------------------- -------------------- -------------------- -------------------- -------------------- 5 2 10 6 6 5 4 10 4 4 2 rows fetched. --插入的数据长度超过类型规定的长度报错。 SQL> INSERT INTO char_type_t1(a, b) VALUES ('too long', 'too long'); CT-00698, The size(8) of value can't larger than defined size(5) of char --删除表。 SQL> DROP TABLE char_type_t1; SQL> CREATE TABLE test_clob(c1 clob, c2 nclob, c3 text, c4 longtext, c5 long); SQL> INSERT INTO test_clob values('abcdefg', 'abcdefg', 'abcdefg', 'abcdefg', 'abcdefg'); SQL> SELECT * FROM test_clob; C1 C2 C3 C4 C5 ---------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- abcdefg abcdefg abcdefg abcdefg abcdefg 1 rows fetched. SQL> SHOW CREATE TABLE test_clob; CREATE TABLE "TEST_CLOB" ( "C1" CLOB, "C2" CLOB, "C3" CLOB, "C4" CLOB, "C5" CLOB ) TABLESPACE "SYSTEM" INITRANS 2 MAXTRANS 255 PCTFREE 8 FORMAT ASF; SQL> ALTER SYSTEM SET use_bison_parser = true; SQL> CREATE TABLE test_char1 ( c1 national character varying(10), c2 national char varying(10), c3 nchar varying(10) ); SQL> SHOW CREATE TABLE test_char1; CREATE TABLE "TEST_CHAR1" ( "C1" VARCHAR(10 CHAR), "C2" VARCHAR(10 CHAR), "C3" VARCHAR(10 CHAR) ) TABLESPACE "SYSTEM" INITRANS 0 MAXTRANS 255 PCTFREE 0 FORMAT ASF; SQL> CREATE TABLE test_char2 ( c1 national character, c2 national char, c3 nchar ); SQL> SHOW CREATE TABLE test_char2; CREATE TABLE "TEST_CHAR2" ( "C1" CHAR(1 CHAR), "C2" CHAR(1 CHAR), "C3" CHAR(1 CHAR) ) TABLESPACE "SYSTEM" INITRANS 0 MAXTRANS 255 PCTFREE 0 FORMAT ASF; SQL> CREATE TABLE test_char3( c1 national character(10), c2 national char(10), c3 nchar(10) ); SQL> SHOW CREATE TABLE test_char3; CREATE TABLE "TEST_CHAR3" ( "C1" CHAR(10 CHAR), "C2" CHAR(10 CHAR), "C3" CHAR(10 CHAR) ) TABLESPACE "SYSTEM" INITRANS 0 MAXTRANS 255 PCTFREE 0 FORMAT ASF; SQL> SELECT n'abcd'; N'ABCD' ------- abcd 1 rows fetched. SQL> SELECT N'abcd'; N'ABCD' ------- abcd 1 rows fetched. SQL> SELECT n'1234'; N'1234' ------- 1234 1 rows fetched. SQL> SELECT N'1234'; N'1234' ------- 1234 1 rows fetched. SQL> ALTER SYSTEM SET use_bison_parser = false; ``` --- --- url: /zh/docs/latest-lite/sql_reference/character_sets.md --- # CHARACTER\_SETS 存储字符集相关的信息。 **表 1** CHARACTER\_SETS相比于PGXC/PG新增字段 --- --- url: /zh/docs/latest/sql_reference/character_sets.md --- # CHARACTER\_SETS 存储字符集相关的信息。 **表 1** CHARACTER\_SETS相比于PGXC/PG新增字段 --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-CHECK_CONSTRAINTS.md --- # CHECK\_CONSTRAINTS 返回CHECK约束相关的信息。 **表1** CHECK\_CONSTRAINTS --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-INFORMATION_SCHEMA_TSQL.CHECK_CONSTRAINTS.md --- # CHECK\_CONSTRAINTS CHECK\_CONSTRAINTS视图返回数据库中的检查约束信息。 **表1** CHECK\_CONSTRAINTS --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-CHECK_CONSTRAINTS.md --- # CHECK\_CONSTRAINTS 返回CHECK约束相关的信息。 **表1** CHECK\_CONSTRAINTS --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-INFORMATION_SCHEMA_TSQL.CHECK_CONSTRAINTS.md --- # CHECK\_CONSTRAINTS CHECK\_CONSTRAINTS视图返回数据库中的检查约束信息。 **表1** CHECK\_CONSTRAINTS --- --- url: /en/docs/latest-lite/performance_tuning_guide/checking_blocked_statements.md --- # Checking Blocked Statements During database running, query statements are blocked in some service scenarios and run for an excessively long time. In this case, you can forcibly terminate the faulty session. ## Procedure 1. Log in as the OS user **omm** to a database node. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 ``` **postgres** is the name of the database to be connected, and **8000** is the port number of the database node. If information similar to the following is displayed, the connection succeeds: ``` gsql((openGauss x.x.x build f521c606) compiled at 2021-09-16 14:55:22 commit 2935 last mr 6385 release) Non-SSL connection (SSL connection is recommended when requiring high-security) Type "help" for help. openGauss=# ``` 3. View blocked query statements and details about the tables and schemas that block the query statements. ``` SELECT w.query as waiting_query, w.pid as w_pid, w.usename as w_user, l.query as locking_query, l.pid as l_pid, l.usename as l_user, t.schemaname || '.' || t.relname as tablename from pg_stat_activity w join pg_locks l1 on w.pid = l1.pid and not l1.granted join pg_locks l2 on l1.relation = l2.relation and l2.granted join pg_stat_activity l on l2.pid = l.pid join pg_stat_user_tables t on l1.relation = t.relid where w.waiting; ``` The thread ID, user details, query status, as well as details about the tables and schemas that block the query statements are returned. 4. Run the following command to terminate the required session, where **139834762094352** is the thread ID: ``` SELECT PG_TERMINATE_BACKEND(139834762094352); ``` If information similar to the following is displayed, the session is successfully terminated: ``` PG_TERMINATE_BACKEND ---------------------- t (1 row) ``` If information similar to the following is displayed, a user is attempting to terminate the session, and the session will be reconnected rather than being terminated. ``` FATAL: terminating connection due to administrator command FATAL: terminating connection due to administrator command The connection to the server was lost. Attempting reset: Succeeded. ``` > \[!NOTE]NOTE > > If the **PG\_TERMINATE\_BACKEND** function is used to terminate the background threads of the session, the **gsql** client will be reconnected rather than be logged out. --- --- url: /en/docs/latest/performance_tuning_guide/checking_blocked_statements.md --- # Checking Blocked Statements During database running, query statements are blocked in some service scenarios and run for an excessively long time. In this case, you can forcibly terminate the faulty session. ## Procedure 1. Log in as the OS user **omm** to a database node. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 ``` **postgres** is the name of the database to be connected, and **8000** is the port number of the database node. If information similar to the following is displayed, the connection succeeds: ``` gsql ((openGauss 1.0 build 290d125f) compiled at 2020-05-08 02:59:43 commit 2143 last mr 131 Non-SSL connection (SSL connection is recommended when requiring high-security) Type "help" for help. postgres=# ``` 3. View blocked query statements and details about the tables and schemas that block the query statements. ``` SELECT w.query as waiting_query, w.pid as w_pid, w.usename as w_user, l.query as locking_query, l.pid as l_pid, l.usename as l_user, t.schemaname || '.' || t.relname as tablename from pg_stat_activity w join pg_locks l1 on w.pid = l1.pid and not l1.granted join pg_locks l2 on l1.relation = l2.relation and l2.granted join pg_stat_activity l on l2.pid = l.pid join pg_stat_user_tables t on l1.relation = t.relid where w.waiting; ``` The thread ID, user details, query status, as well as details about the tables and schemas that block the query statements are returned. 4. Run the following command to terminate the required session, where **139834762094352** is the thread ID: ``` SELECT PG_TERMINATE_BACKEND(139834762094352); ``` If information similar to the following is displayed, the session is successfully terminated: ``` PG_TERMINATE_BACKEND ---------------------- t (1 row) ``` If information similar to the following is displayed, a user is attempting to terminate the session, and the session will be reconnected rather than being terminated. ``` FATAL: terminating connection due to administrator command FATAL: terminating connection due to administrator command The connection to the server was lost. Attempting reset: Succeeded. ``` > \[!NOTE]NOTE\ > If the **PG\_TERMINATE\_BACKEND** function is used to terminate the background threads of the session, the **gsql** client will be reconnected rather than be logged out. --- --- url: >- /en/docs/latest-lite/database_administration_guide/checking_ledger_data_consistency.md --- # Checking Ledger Data Consistency ## Prerequisites The database is running properly, and a series of addition, deletion, and modification operations are performed on the tamper-proof database to ensure that operation records are generated in the ledger for query. ## Background * Currently, the ledger database provides two verification interfaces: [ledger\_hist\_check(text,...](../sql_reference/ledger_database_functions.md) and [ledger\_gchain\_check(text...](../sql_reference/ledger_database_functions.md). When a common user invokes a verification interface, only the tables that the user has the permission to access can be verified. * The interface for verifying the tamper-proof user table and user history table is **pg\_catalog.ledger\_hist\_check**. To verify a table, run the following command: ``` SELECT pg_catalog.ledger_hist_check(schema_name text,table_name text); ``` If the verification is successful, the function returns **t**. Otherwise, the function returns **f**. * The **pg\_catalog.ledger\_gchain\_check** interface is used to check whether the tamper-proof user table, user history table, and global blockchain table are consistent. To verify consistency, run the following command: ``` SELECT pg_catalog.ledger_gchain_check(schema_name text, table_name text); ``` If the verification is successful, the function returns **t**. Otherwise, the function returns **f**. ## Procedure 1. Check whether the tamper-proof user table **ledgernsp.usertable** is consistent with the corresponding user history table. ``` openGauss=# SELECT pg_catalog.ledger_hist_check('ledgernsp', 'usertable'); ``` The query result is as follows: ``` ledger_hist_check ------------------- t (1 row) ``` The query result shows that the results recorded in the tamper-proof user table and user history table are consistent. 2. Check whether the records in the tamper-proof **ledgernsp.usertable** table are the same as those in the corresponding user history table and global blockchain table. ``` openGauss=# SELECT pg_catalog.ledger_gchain_check('ledgernsp', 'usertable'); ``` The query result is as follows: ``` ledger_gchain_check --------------------- t (1 row) ``` The query result shows that the records of **ledgernsp.usertable** in the preceding three tables are consistent and no tampering occurs. --- --- url: >- /en/docs/latest/database_administration_guide/checking_ledger_data_consistency.md --- # Checking Ledger Data Consistency ## Prerequisites The database is running properly, and a series of addition, deletion, and modification operations are performed on the tamper-proof database to ensure that operation records are generated in the ledger for query. ## Background * Currently, the ledger database provides two verification interfaces: [ledger\_hist\_check(text,...](../sql_reference/ledger_database_functions.md) and [ledger\_gchain\_check(text...](../sql_reference/ledger_database_functions.md). When a common user invokes a verification interface, only the tables that the user has the permission to access can be verified. * The interface for verifying the tamper-proof user table and user history table is **pg\_catalog.ledger\_hist\_check**. To verify a table, run the following command: ``` SELECT pg_catalog.ledger_hist_check(schema_name text,table_name text); ``` If the verification is successful, the function returns **t**. Otherwise, the function returns **f**. * The **pg\_catalog.ledger\_gchain\_check** interface is used to check whether the tamper-proof user table, user history table, and global blockchain table are consistent. To verify consistency, run the following command: ``` SELECT pg_catalog.ledger_gchain_check(schema_name text, table_name text); ``` If the verification is successful, the function returns **t**. Otherwise, the function returns **f**. ## Procedure 1. Check whether the tamper-proof user table **ledgernsp.usertable** is consistent with the corresponding user history table. ``` openGauss=# SELECT pg_catalog.ledger_hist_check('ledgernsp', 'usertable'); ``` The query result is as follows: ``` ledger_hist_check ------------------- t (1 row) ``` The query result shows that the results recorded in the tamper-proof user table and user history table are consistent. 2. Check whether the records in the tamper-proof **ledgernsp.usertable** table are the same as those in the corresponding user history table and global blockchain table. ``` openGauss=# SELECT pg_catalog.ledger_gchain_check('ledgernsp', 'usertable'); ``` The query result is as follows: ``` ledger_gchain_check --------------------- t (1 row) ``` The query result shows that the records of **ledgernsp.usertable** in the preceding three tables are consistent and no tampering occurs. --- --- url: >- /en/docs/latest-lite/database_administration_guide/checking_the_number_of_database_connections.md --- # Checking the Number of Database Connections ## Background If the number of connections reaches its upper limit, new connections cannot be created. Therefore, if a user fails to connect a database, the administrator must check whether the number of connections has reached the upper limit. The following are details about database connections: * The maximum number of global connections is specified by the **max\_connections** parameter. * The number of a user's connections is specified by **CONNECTION LIMIT connlimit** in the **CREATE ROLE** statement and can be changed using **CONNECTION LIMIT connlimit** in the **ALTER ROLE** statement. * The number of a database's connections is specified by the **CONNECTION LIMIT connlimit** parameter in the **CREATE DATABASE** statement. ## Procedure 1. Log in as the OS user **omm** to the primary node of the database. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 ``` **postgres** is the name of the database to be connected, and **8000** is the port number of the database primary node. If information similar to the following is displayed, the connection succeeds: ``` gsql((openGauss x.x.x build f521c606) compiled at 2021-09-16 14:55:22 commit 2935 last mr 6385 release) Non-SSL connection (SSL connection is recommended when requiring high-security) Type "help" for help. openGauss=# ``` 3. View the upper limit of the number of global connections. ``` openGauss=# SHOW max_connections; max_connections ----------------- 800 (1 row) ``` **800** is the maximum number of session connections. 4. View the number of connections that have been used. For details, see [Table 1](#en-us_topic_0283136582_en-us_topic_0237121094_en-us_topic_0059779140_t608a1965463e41f1b6eacd02f97a65ba). > \[!TIP]NOTICE > > Except for database and usernames that are enclosed in double quotation marks (") during creation, uppercase letters are not allowed in the database and usernames in the commands in the following table. **Table 1** Viewing the number of session connections --- --- url: >- /en/docs/latest/database_administration_guide/checking_the_number_of_database_connections.md --- # Checking the Number of Database Connections ## Background If the number of connections reaches its upper limit, new connections cannot be created. Therefore, if a user fails to connect a database, the administrator must check whether the number of connections has reached the upper limit. The following are details about database connections: * The maximum number of global connections is specified by the **max\_connections** parameter. Its default value is **5000**. * The number of a user's connections is specified by **CONNECTION LIMIT connlimit** in the **CREATE ROLE** statement and can be changed using **CONNECTION LIMIT connlimit** in the **ALTER ROLE** statement. * The number of a database's connections is specified by the **CONNECTION LIMIT connlimit** parameter in the **CREATE DATABASE** statement. ## Procedure 1. Log in as the OS user **omm** to the primary node of the database. 2. Run the following command to connect to the database: ``` gsql -d postgres -p 8000 ``` **postgres** is the name of the database to be connected, and **8000** is the port number of the database primary node. If information similar to the following is displayed, the connection succeeds: ``` gsql ((openGauss 1.0 build 290d125f) compiled at 2020-05-08 02:59:43 commit 2143 last mr 131) Non-SSL connection (SSL connection is recommended when requiring high-security) Type "help" for help. postgres=# ``` 3. View the upper limit of the number of global connections. ``` postgres=# SHOW max_connections; max_connections ----------------- 800 (1 row) ``` **800** is the maximum number of session connections. 4. View the number of connections that have been used. For details, see [Table 1](#en-us_topic_0237121094_en-us_topic_0059779140_t608a1965463e41f1b6eacd02f97a65ba). > \[!TIP]NOTICE\ > Except for database and usernames that are enclosed in double quotation marks (") during creation, uppercase letters are not allowed in the database and usernames in the commands in the following table. **Table 1** Viewing the number of session connections ​ --- --- url: /en/docs/latest-lite/sql_reference/checkpoint.md --- # CHECKPOINT ## Function A checkpoint is a point in the transaction log sequence at which all data files have been updated to reflect the information in the log. All data files will be flushed to a disk. **CHECKPOINT** forces a transaction log checkpoint. By default, WALs periodically specify checkpoints in a transaction log. You may use **gs\_guc** to specify run-time parameters **checkpoint\_segments**, **checkpoint\_timeout**, and **incremental\_checkpoint\_timeout** to adjust the atomized checkpoint intervals. ## Precautions * Only the system administrator and O\&M administrator can invoke **CHECKPOINT**. * **CHECKPOINT** forces an immediate checkpoint when the related command is issued, without waiting for a regular checkpoint scheduled by the system. ## Syntax ``` CHECKPOINT; ``` ## Parameter Description None ## Examples ``` -- Set a checkpoint. openGauss=# CHECKPOINT; ``` --- --- url: /en/docs/latest/sql_reference/checkpoint.md --- # CHECKPOINT ## Function A checkpoint is a point in the transaction log sequence at which all data files have been updated to reflect the information in the log. All data files will be flushed to a disk. **CHECKPOINT** forces a transaction log checkpoint. By default, WALs periodically specify checkpoints in a transaction log. You may use **gs\_guc** to specify run-time parameters **checkpoint\_segments**, **checkpoint\_timeout**, and **incremental\_checkpoint\_timeout** to adjust the atomized checkpoint intervals. ## Precautions * Only the system administrator and O\&M administrator can invoke **CHECKPOINT**. * **CHECKPOINT** forces an immediate checkpoint when the related command is issued, without waiting for a regular checkpoint scheduled by the system. ## Syntax ``` CHECKPOINT; ``` ## Parameter Description None ## Examples ``` -- Set a checkpoint. openGauss=# CHECKPOINT; ``` --- --- url: /zh/docs/latest-lite/sql_reference/checkpoint.md --- # CHECKPOINT ## 功能描述 检查点(CHECKPOINT)是一个事务日志中的点,所有数据文件都在该点被更新以反映日志中的信息,所有数据文件都将被刷新到磁盘。 设置事务日志检查点。预写式日志(WAL)缺省时在事务日志中每隔一段时间放置一个检查点。可以使用gs\_guc命令设置相关运行时参数(checkpoint\_segments,checkpoint\_timeout和incremental\_checkpoint\_timeout)来调整这个原子化检查点的间隔。 ## 注意事项 * 只有系统管理员和运维管理员可以调用CHECKPOINT。 * CHECKPOINT强制立即进行检查,而不是等到下一次调度时的检查点。 ## 语法格式 ``` CHECKPOINT; ``` ## 参数说明 无。 ## 示例 ``` --设置检查点。 openGauss=# CHECKPOINT; ``` --- --- url: /zh/docs/latest/sql_reference/checkpoint.md --- # CHECKPOINT ## 功能描述 检查点(CHECKPOINT)是一个事务日志中的点,所有数据文件都在该点被更新以反映日志中的信息,所有数据文件都将被刷新到磁盘。 设置事务日志检查点。预写式日志(WAL)缺省时在事务日志中每隔一段时间放置一个检查点。可以使用gs\_guc命令设置相关运行时参数(checkpoint\_segments、checkpoint\_timeout和incremental\_checkpoint\_timeout)来调整这个原子化检查点的间隔。 ## 注意事项 * 只有系统管理员和运维管理员可以调用CHECKPOINT。 * CHECKPOINT强制立即进行检查,而不是等到下一次调度时的检查点。 ## 语法格式 ``` CHECKPOINT; ``` ## 参数说明 无。 ## 示例 ``` --设置检查点。 openGauss=# CHECKPOINT; ``` --- --- url: /en/docs/latest-lite/database_reference/checkpoints.md --- # Checkpoints ## checkpoint\_segments **Parameter description**: Specifies the minimum number of WAL segment files in the period specified by **[checkpoint\_timeout](#en-us_topic_0283137153_en-us_topic_0237124708_en-us_topic_0059778936_s880baa9f9b594980afbbe95fb8a77182)**. The size of each log file is 16 MB. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer. The minimum value is **1**. Increasing the value of this parameter speeds up the export of a large amount of data. Set this parameter based on **[checkpoint\_timeout](#en-us_topic_0283137153_en-us_topic_0237124708_en-us_topic_0059778936_s880baa9f9b594980afbbe95fb8a77182)** and **[shared\_buffers](memory.md#en-us_topic_0283136786_en-us_topic_0237124699_en-us_topic_0059777577_s55a43fb6d0464430a59031671b37cd07)**. This parameter affects the number of WAL segment files that can be reused. Generally, the maximum number of reused files in the **pg\_xlog** folder is twice the number of **checkpoint\_segments**. The reused files are not deleted and are renamed to the WAL segment files which will be later used. **Default value**: **64** ## checkpoint\_timeout **Parameter description**: Specifies the maximum time between automatic WAL checkpoints. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 30 to 3600. The unit is second. If the value of **[checkpoint\_segments](#en-us_topic_0283137153_en-us_topic_0237124708_en-us_topic_0059778936_sbadc77895e6643b882a5e7557e405373)** is increased, you need to increase the value of this parameter. The increase of these two parameters further requires the increase of **[shared\_buffers](memory.md#en-us_topic_0283136786_en-us_topic_0237124699_en-us_topic_0059777577_s55a43fb6d0464430a59031671b37cd07)**. Consider all these parameters during setting. **Default value**: **15min** ## checkpoint\_completion\_target **Parameter description**: Specifies the completion target of each checkpoint, as a fraction of total time between checkpoints. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** a double-precision floating point number ranging from 0.0 to 1.0 **Default value**: **0.5** > \[!NOTE]NOTE > **0.5** indicates that each checkpoint should be complete within 50% of the interval between checkpoints. ## checkpoint\_warning **Parameter description**: Specifies a time in seconds. If the checkpoint interval is close to this time due to filling of checkpoint segment files, a message is sent to the server log to suggest an increase in the **[checkpoint\_segments](#en-us_topic_0283137153_en-us_topic_0237124708_en-us_topic_0059778936_sbadc77895e6643b882a5e7557e405373)** value. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to *INT\_MAX*. The unit is second. **0** indicates that the warning is disabled. **Default value**: **5min** **Recommended value**: **5min** ## checkpoint\_wait\_timeout **Parameter description**: Sets the longest time that the checkpoint waits for the checkpointer thread to start. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 2 to 3600. The unit is second. **Default value**: **1min** ## enable\_incremental\_checkpoint **Parameter description**: Specifies whether to enable incremental checkpointing. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean **Default value**: **off** ## enable\_double\_write **Parameter description**: Specifies whether to enable double writing. When the incremental checkpoint function is enabled and **enable\_double\_write** is enabled, the **enable\_double\_write** dual-write feature is used for protection, and **full\_page\_writes** is not used to prevent half-page write. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean **Default value**: **off** ## incremental\_checkpoint\_timeout **Parameter description**: Specifies the maximum interval between automatic WAL checkpoints when the incremental checkpointing is enabled. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 1 to 3600. The unit is second. **Default value**: **1min** ## enable\_xlog\_prune **Parameter description**: Specifies whether the primary server recycles logs when any standby server is disconnected. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * If this parameter is set to **on**, the primary server does not recycle logs when any standby server is disconnected. * If this parameter is set to **off**, the primary server recycles logs when any standby server is disconnected. **Default value**: **on** ## max\_redo\_log\_size **Parameter description:** On the standby DN, this parameter specifies the maximum size of logs between the latest checkpoint and the current log replay location. On the primary DN, this parameter specifies the maximum size of logs between the recovery point and the latest log location. You are not advised to set this parameter to a large value if the RTO is concerned. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 163840 to 2147483647. The unit is kB. **Default value**: **1 GB** ## max\_size\_for\_xlog\_prune **Parameter description**: This parameter takes effect when **enable\_xlog\_prune** is enabled. The working mechanism is as follows: 1. If all standby nodes specified by the **replconninfo** series GUC parameters are connected to the primary node, this parameter does not take effect. 2. If any standby node specified by the **replconninfo** series GUC parameters is not connected to the primary node, this parameter takes effect. When the number of historical logs on the primary node is greater than the value of this parameter, the logs are forcibly recycled. Exception: In synchronous commit mode (that is, the value of **synchronous\_commit** is not **local** or **off**), if there are connected standby nodes, the primary node retains the logs that meet the minimum log receiving requirements on the majority of standby nodes. In this case, the number of reserved logs may exceed the value of **max\_size\_for\_xlog\_prune**. 3. If any standby node is being built, this parameter does not take effect. All logs of the primary node are retained to prevent build failures due to log recycling. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 0 to 2147483647. The unit is kB. **Default value**: **2147483647**. The unit is kB. --- --- url: /en/docs/latest/database_reference/checkpoints.md --- # Checkpoints ## checkpoint\_segments **Parameter description**: Specifies the minimum number of WAL segment files in the period specified by **[checkpoint\_timeout](#en-us_topic_0283137153_en-us_topic_0237124708_en-us_topic_0059778936_s880baa9f9b594980afbbe95fb8a77182)**. The size of each log file is 16 MB. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer. The minimum value is **1**. Increasing the value of this parameter speeds up the export of a large amount of data. Set this parameter based on **[checkpoint\_timeout](#en-us_topic_0283137153_en-us_topic_0237124708_en-us_topic_0059778936_s880baa9f9b594980afbbe95fb8a77182)** and **[shared\_buffers](memory.md#en-us_topic_0283136786_en-us_topic_0237124699_en-us_topic_0059777577_s55a43fb6d0464430a59031671b37cd07)**. This parameter affects the number of WAL segment files that can be reused. Generally, the maximum number of reused files in the **pg\_xlog** folder is twice the number of **checkpoint\_segments**. The reused files are not deleted and are renamed to the WAL segment files which will be later used. **Default value**: **64** ## checkpoint\_timeout **Parameter description**: Specifies the maximum time between automatic WAL checkpoints. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 30 to 3600. The unit is s. If the value of **[checkpoint\_segments](#en-us_topic_0283137153_en-us_topic_0237124708_en-us_topic_0059778936_sbadc77895e6643b882a5e7557e405373)** is increased, you need to increase the value of this parameter. The increase of these two parameters further requires the increase of **[shared\_buffers](memory.md#en-us_topic_0283136786_en-us_topic_0237124699_en-us_topic_0059777577_s55a43fb6d0464430a59031671b37cd07)**. Consider all these parameters during setting. **Default value**: **15min** ## checkpoint\_completion\_target **Parameter description**: Specifies the completion target of each checkpoint, as a fraction of total time between checkpoints. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** a double-precision floating point number ranging from 0.0 to 1.0 **Default value**: **0.5** > \[!NOTE]NOTE > **0.5** indicates that each checkpoint should be complete within 50% of the interval between checkpoints. ## checkpoint\_warning **Parameter description**: Specifies a time in seconds. If the checkpoint interval is close to this time due to filling of checkpoint segment files, a message is sent to the server log to suggest an increase in the **[checkpoint\_segments](#en-us_topic_0283137153_en-us_topic_0237124708_en-us_topic_0059778936_sbadc77895e6643b882a5e7557e405373)** value. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to *INT\_MAX*. The unit is second. **0** indicates that the warning is disabled. **Default value**: **5min** **Recommended value**: **5min** ## checkpoint\_wait\_timeout **Parameter description**: Sets the longest time that the checkpoint waits for the checkpointer thread to start. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 2 to 3600. The unit is s. **Default value**: **1min** ## enable\_incremental\_checkpoint **Parameter description**: Specifies whether to enable incremental checkpointing. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean **Default value**: **on** ## enable\_double\_write **Parameter description**: Specifies whether to enable double writing. When the incremental checkpoint function is enabled and **enable\_double\_write** is enabled, the **enable\_double\_write** dual-write feature is used for protection, and **full\_page\_writes** is not used to prevent half-page write. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean **Default value**: **on** ## incremental\_checkpoint\_timeout **Parameter description**: Specifies the maximum interval between automatic WAL checkpoints when the incremental checkpointing is enabled. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 1 to 3600. The unit is s. **Default value**: **1min** ## enable\_xlog\_prune **Parameter description**: Specifies whether the primary node recycles logs when any standby node is disconnected. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * If this parameter is set to **on**, the primary node does not recycle logs when any standby node is disconnected. * If this parameter is set to **off**, the primary node recycles logs when any standby node is disconnected. **Default value**: **on** ## max\_redo\_log\_size **Parameter description:** On the standby DN, this parameter specifies the maximum size of logs between the latest checkpoint and the current log replay location. On the primary DN, this parameter specifies the maximum size of logs between the recovery point and the latest log location. You are not advised to set this parameter to a large value if the RTO is concerned. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 163840 to 2147483647. The unit is kB. **Default value**: **1 GB** ## max\_size\_for\_xlog\_prune **Parameter description**: This parameter takes effect when **enable\_xlog\_prune** is enabled. The working mechanism is as follows: 1. If all standby nodes specified by the **replconninfo** series GUC parameters are connected to the primary node, this parameter does not take effect. 2. If any standby node specified by the **replconninfo** series GUC parameters is not connected to the primary node, this parameter takes effect. When the number of historical logs on the primary node is greater than the value of this parameter, the logs are forcibly recycled. Exception: In synchronous commit mode (that is, the value of **synchronous\_commit** is not **local** or **off**), if there are connected standby nodes, the primary node retains the logs that meet the minimum log receiving requirements on the majority of standby nodes. In this case, the number of reserved logs may exceed the value of **max\_size\_for\_xlog\_prune**. 3. If any standby node is being built, this parameter does not take effect. All logs of the primary node are retained to prevent build failures due to log recycling. This parameter is a SIGHUP parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range:** an integer ranging from 0 to 2147483647. The unit is kB. **Default value**: **2147483647**. The unit is kB.\*\*\*\* --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-checksum-table.md --- # CHECKSUM TABLE ## Function Calculates the table data checksum. ## Precautions * The QUICK schema is not supported (NULL is returned). * NULL is returned for non-ordinary tables (such as views) and tables that do not exist. * Comparability with table checksums of heterogeneous databases is not supported. (For example, if the number of records is the same, the query results in openGauss and MySQL cannot be compared.) * For non-QUICK option mode, checksum result is based on calculating of query result string, thus differentiation of column type is currently not supported ## Syntax ``` CHECKSUM TABLE tbl_name [, tbl_name] ... [QUICK | EXTENDED] ``` ## Parameter Description * **tbl\_name** Table name. You can specify a table name or **schema\_name.table\_name**. * **\[QUICK | EXTENDED]** Verification mode. Only EXTENDED (default value) is supported. ## Examples ``` --Create a simple table. openGauss=# CREATE SCHEMA tst_schema1; openGauss=# SET SEARCH_PATH TO tst_schema1; opengauss=# CREATE TABLE tst_t1 ( id int, name VARCHAR(20), addr text, phone text, addr_code text ); opengauss=# CREATE TABLE tst_t2 AS SELECT * FROM tst_t1; INSERT 0 0 --Verify different insertion sequences. opengauss=# INSERT INTO tst_t1 values(2022001, 'tst_name1', 'tst_addr1', '15600000001', '000001'); INSERT INTO tst_t1 values(2022002, 'tst_name2', 'tst_addr2', '15600000002', '000002'); INSERT INTO tst_t1 values(2022003, 'tst_name3', 'tst_addr3', '15600000003', '000003'); INSERT INTO tst_t1 values(2022004, 'tst_name4', 'tst_addr4', '15600000004', '000004'); INSERT INTO tst_t2 (SELECT * FROM tst_t1 ORDER BY id DESC); opengauss=# checksum table tst_t1,tst_t2,xxx; Table | Checksum --------------------+------------ tst_schema1.tst_t1 | 1579899754 tst_schema1.tst_t2 | 1579899754 tst_schema1.xxx | NULL --Test a table containing large columns. opengauss=# CREATE TABLE blog ( id int, title text, content text ); opengauss=# CREATE TABLE blog_v2 AS SELECT * FROM blog; opengauss=# INSERT INTO blog values(1, 'title1', '01234567890'), (2, 'title2', '0987654321'); opengauss=# CREATE OR REPLACE FUNCTION loop_insert_result_toast(n integer) RETURNS integer AS $$ DECLARE count integer := 0; BEGIN LOOP EXIT WHEN count = n; UPDATE blog SET content=content||content where id = 2; count := count + 1; END LOOP; RETURN count; END; $$ LANGUAGE PLPGSQL; opengauss=# select loop_insert_result_toast(16); loop_insert_result_toast -------------------------- 16 opengauss=# INSERT INTO blog_v2 (SELECT * FROM blog); opengauss=# checksum table blog,blog_v2; Table | Checksum ---------------------+------------ tst_schema1.blog | 6249493220 tst_schema1.blog_v2 | 6249493220 --Test a segment-page table. opengauss=# CREATE TABLE tst_seg_t1(id int, name VARCHAR(20)) WITH (segment=on); opengauss=# CREATE TABLE tst_seg_t2(id int, name VARCHAR(20)) WITH (segment=on); opengauss=# INSERT INTO tst_seg_t1 values(2022001, 'name_example_1'); INSERT INTO tst_seg_t1 values(2022002, 'name_example_2'); INSERT INTO tst_seg_t1 values(2022003, 'name_example_3'); opengauss=# INSERT INTO tst_seg_t2 (SELECT * FROM tst_seg_t1); opengauss=# checksum table tst_seg_t1,tst_seg_t2; Table | Checksum ------------------------+------------ tst_schema1.tst_seg_t1 | 5620410817 tst_schema1.tst_seg_t2 | 5620410817 ``` --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CHECKSUM-TABLE.md --- # CHECKSUM TABLE ## 功能描述 计算表数据校验和。 ## 注意事项 * 不支持QUICK模式(返回NULL)。 * 对于非普通表(例如视图)、不存在的表均返回NULL。 * 不支持与异构数据库的表校验和的可比性。 (例如对于相同数目,在opengauss和mysql中查询结果无法对比)。 * 非QUICK模式的校验和计算基于查询结果子串,暂不支持针对列的数据类型的区分。 ## 语法格式 ``` CHECKSUM TABLE tbl_name [, tbl_name] ... [QUICK | EXTENDED] ``` ## 参数说明 * **tbl\_name** 表名,可指定表名。也可以指定schema\_name.table\_name。 * **\[QUICK | EXTENDED]** 校验模式,只支持EXTENDED(也即默认值)。 ## 示例 ``` --创建简单表 openGauss=# CREATE SCHEMA tst_schema1; openGauss=# SET SEARCH_PATH TO tst_schema1; opengauss=# CREATE TABLE tst_t1 ( id int, name VARCHAR(20), addr text, phone text, addr_code text ); opengauss=# CREATE TABLE tst_t2 AS SELECT * FROM tst_t1; INSERT 0 0 --不同插入顺序校验 opengauss=# INSERT INTO tst_t1 values(2022001, 'tst_name1', 'tst_addr1', '15600000001', '000001'); INSERT INTO tst_t1 values(2022002, 'tst_name2', 'tst_addr2', '15600000002', '000002'); INSERT INTO tst_t1 values(2022003, 'tst_name3', 'tst_addr3', '15600000003', '000003'); INSERT INTO tst_t1 values(2022004, 'tst_name4', 'tst_addr4', '15600000004', '000004'); INSERT INTO tst_t2 (SELECT * FROM tst_t1 ORDER BY id DESC); opengauss=# checksum table tst_t1,tst_t2,xxx; Table | Checksum --------------------+------------ tst_schema1.tst_t1 | 1579899754 tst_schema1.tst_t2 | 1579899754 tst_schema1.xxx | NULL --含大段字段的表测试 opengauss=# CREATE TABLE blog ( id int, title text, content text ); opengauss=# CREATE TABLE blog_v2 AS SELECT * FROM blog; opengauss=# INSERT INTO blog values(1, 'title1', '01234567890'), (2, 'title2', '0987654321'); opengauss=# CREATE OR REPLACE FUNCTION loop_insert_result_toast(n integer) RETURNS integer AS $$ DECLARE count integer := 0; BEGIN LOOP EXIT WHEN count = n; UPDATE blog SET content=content||content where id = 2; count := count + 1; END LOOP; RETURN count; END; $$ LANGUAGE PLPGSQL; opengauss=# select loop_insert_result_toast(16); loop_insert_result_toast -------------------------- 16 opengauss=# INSERT INTO blog_v2 (SELECT * FROM blog); opengauss=# checksum table blog,blog_v2; Table | Checksum ---------------------+------------ tst_schema1.blog | 6249493220 tst_schema1.blog_v2 | 6249493220 --段页式表测试 opengauss=# CREATE TABLE tst_seg_t1(id int, name VARCHAR(20)) WITH (segment=on); opengauss=# CREATE TABLE tst_seg_t2(id int, name VARCHAR(20)) WITH (segment=on); opengauss=# INSERT INTO tst_seg_t1 values(2022001, 'name_example_1'); INSERT INTO tst_seg_t1 values(2022002, 'name_example_2'); INSERT INTO tst_seg_t1 values(2022003, 'name_example_3'); opengauss=# INSERT INTO tst_seg_t2 (SELECT * FROM tst_seg_t1); opengauss=# checksum table tst_seg_t1,tst_seg_t2; Table | Checksum ------------------------+------------ tst_schema1.tst_seg_t1 | 5620410817 tst_schema1.tst_seg_t2 | 5620410817 ``` --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CHECKSUM-TABLE.md --- # CHECKSUM TABLE ## 功能描述 计算表数据校验和。 ## 注意事项 * 不支持QUICK模式(返回NULL)。 * 对于非普通表(例如视图)、不存在的表均返回NULL。 * 不支持与异构数据库的表校验和的可比性。 (例如对于相同数目,在openGauss和MySQL中查询结果无法对比)。 * 非QUICK模式的校验和计算基于查询结果子串,暂不支持针对列的数据类型的区分。 ## 语法格式 ``` CHECKSUM TABLE tbl_name [, tbl_name] ... [QUICK | EXTENDED] ``` ## 参数说明 * **tbl\_name** 表名,可指定表名。也可以指定schema\_name.table\_name。 * **\[QUICK | EXTENDED]** 校验模式,只支持EXTENDED(也即默认值)。 ## 示例 ``` --创建简单表 openGauss=# CREATE SCHEMA tst_schema1; openGauss=# SET SEARCH_PATH TO tst_schema1; opengauss=# CREATE TABLE tst_t1 ( id int, name VARCHAR(20), addr text, phone text, addr_code text ); opengauss=# CREATE TABLE tst_t2 AS SELECT * FROM tst_t1; INSERT 0 0 --不同插入顺序校验 opengauss=# INSERT INTO tst_t1 values(2022001, 'tst_name1', 'tst_addr1', '15600000001', '000001'); INSERT INTO tst_t1 values(2022002, 'tst_name2', 'tst_addr2', '15600000002', '000002'); INSERT INTO tst_t1 values(2022003, 'tst_name3', 'tst_addr3', '15600000003', '000003'); INSERT INTO tst_t1 values(2022004, 'tst_name4', 'tst_addr4', '15600000004', '000004'); INSERT INTO tst_t2 (SELECT * FROM tst_t1 ORDER BY id DESC); opengauss=# checksum table tst_t1,tst_t2,xxx; Table | Checksum --------------------+------------ tst_schema1.tst_t1 | 1579899754 tst_schema1.tst_t2 | 1579899754 tst_schema1.xxx | NULL --含大段字段的表测试 opengauss=# CREATE TABLE blog ( id int, title text, content text ); opengauss=# CREATE TABLE blog_v2 AS SELECT * FROM blog; opengauss=# INSERT INTO blog values(1, 'title1', '01234567890'), (2, 'title2', '0987654321'); opengauss=# CREATE OR REPLACE FUNCTION loop_insert_result_toast(n integer) RETURNS integer AS $$ DECLARE count integer := 0; BEGIN LOOP EXIT WHEN count = n; UPDATE blog SET content=content||content where id = 2; count := count + 1; END LOOP; RETURN count; END; $$ LANGUAGE PLPGSQL; opengauss=# select loop_insert_result_toast(16); loop_insert_result_toast -------------------------- 16 opengauss=# INSERT INTO blog_v2 (SELECT * FROM blog); opengauss=# checksum table blog,blog_v2; Table | Checksum ---------------------+------------ tst_schema1.blog | 6249493220 tst_schema1.blog_v2 | 6249493220 --段页式表测试 opengauss=# CREATE TABLE tst_seg_t1(id int, name VARCHAR(20)) WITH (segment=on); opengauss=# CREATE TABLE tst_seg_t2(id int, name VARCHAR(20)) WITH (segment=on); opengauss=# INSERT INTO tst_seg_t1 values(2022001, 'name_example_1'); INSERT INTO tst_seg_t1 values(2022002, 'name_example_2'); INSERT INTO tst_seg_t1 values(2022003, 'name_example_3'); opengauss=# INSERT INTO tst_seg_t2 (SELECT * FROM tst_seg_t1); opengauss=# checksum table tst_seg_t1,tst_seg_t2; Table | Checksum ------------------------+------------ tst_schema1.tst_seg_t1 | 5620410817 tst_schema1.tst_seg_t2 | 5620410817 ``` --- --- url: /zh/docs/latest/ograc/about_ograc/product_architecture/ckpt.md --- # CKPT ## 核心目标 为了平衡持久性和性能,数据库在数据的修改真正写入磁盘数据文件之前,先将这个修改操作记录到磁盘上的重做日志文件中,如果日志文件无限增长,恢复过程就需要重放从最开始到现在的所有日志记录,这可能会非常耗时。checkpoint(缩写为CKPT)就是为了解决这个问题而生的。CKPT是数据库管理系统中的一个关键机制,主要目的是在内存和磁盘之间建立一个同步点,以确保数据的一致性和持久性,并加速数据库的恢复过程。 ## 工作机制 ### 关键point oGRAC有几个核心日志点,其基本结构都包含LFN(递增序号),用于标识log\_batch顺序。 CURR\_POINT:标记数据库最近一次落盘。 TRUNC\_POINT:脏页落盘时,该点及该点之前的log都已落盘。 RCY\_POINT:数据库恢复的起始点。 LRP\_POINT:数据库至少恢复到该点才能保证数据一致。 在CKPT中进行log\_flush时,会将LRP\_POINT推到CURR\_POINT,并将RCY\_POINT推到最老的脏页的TRUNC\_POINT,恢复时将从RCY\_POINT开始重演日志。 ### CKPT工作线程 ![](public_sys-resources/ckpt0.png) ckpt\_proc为CKPT线程,负责处理CKPT请求,可主动触发也可定期/定量触发; dbwr\_proc为flush线程,负责刷脏页到数据盘; ckpt\_full\_checkpoint用于全量CKPT; ckpt\_inc\_checkpoint用于增量CKPT; ckpt\_page\_clean用于writelist上的PAGE CLEAN。 ### 增量CKPT 当全量CKPT时,数据库需要将所有被修改过的数据页(脏页)一次性、全部写入磁盘。对于一个繁忙的数据库,脏页可能非常多。这种集中的、大量的磁盘 I/O 会瞬间占用大量系统资源,导致数据库在 CKPT 期间性能急剧下降,出现"卡顿"现象。这带来的另一个问题就是CKPT不能频繁触发,导致point推进不及时,宕机恢复时间变长。增量 CKPT 就是为了解决这些问题而生的。 oGRAC增量CKPT的核心思想是:不再一次性刷写所有脏页,而是通过一种机制,持续地、分批次地将脏页写入磁盘。这样,任何一个时间点需要持久化的脏页数量都大大减少,从而平滑了I/O写入,避免了性能尖峰。 ### 批量并发刷脏页技术 传统的单页顺序刷新会带来显著的I/O开销和延迟。为优化性能,oGRAC引入批量与并发的刷新技术。将多个待写入的脏页在内存中组织成一个批次,然后由后台线程一次性、顺序地写入磁盘。此举将大量随机写I/O转化为高效的顺序写,极大地提升了I/O吞吐量。 为进一步降低延迟,oGRAC会启动多个刷新线程并发执行不同的刷脏批次,充分利用现代多核CPU和存储设备的并行处理能力。通过批量与并发的结合,数据库平滑了写入波动,避免了I/O性能尖峰,确保了在高负载下仍能保持稳定、高效的数据持久化能力。 ## 相关参数配置 CHECKPOINT\_PERIOD:两次增量CKPT之间的间隔时间。 CHECKPOINT\_PAGES:两次增量CKPT之间的脏页数。 BUFFER\_PAGE\_CLEAN\_PERIOD:两次PAGE\_CLEAN之间的间隔时间。 CHECKPOINT\_GROUP\_SIZE:一次增量CKPT最多处理的Page数。 DBWR\_PROCESSES:刷脏页的线程个数。 ## 相关视图 ### DV\_DATABASE * RCY\_POINT: 恢复信息 * LRP\_POINT: Least Recovery信息 * CKPT\_ID: CHECKPOINT ID * LSN: 重做日志序列号 * LFN: 重做日志刷新号 * LOG\_FIRST: 重做日志开始文件号 * LOG\_LAST: 重做日志结束文件号 * LOG\_FREE\_SIZE: 重做日志可用空间 ### DV\_SYS\_STATS * CKPT avg merge io: 脏页落盘平均IO合并数 * CKPT last merge io: 脏页落盘最后一次IO合并数 --- --- url: /en/docs/latest-lite/sql_reference/class_vital_info.md --- # CLASS\_VITAL\_INFO **CLASS\_VITAL\_INFO** is used to check whether the OIDs of the same table or index are consistent for WDR snapshots. **Table 1** CLASS\_VITAL\_INFO columns --- --- url: /en/docs/latest/sql_reference/class_vital_info.md --- # CLASS\_VITAL\_INFO **CLASS\_VITAL\_INFO** is used to check whether the OIDs of the same table or index are consistent for WDR snapshots. **Table 1** CLASS\_VITAL\_INFO columns --- --- url: /zh/docs/latest-lite/sql_reference/class_vital_info.md --- # CLASS\_VITAL\_INFO CLASS\_VITAL\_INFO视图用于做WDR时校验相同的表或者索引的Oid是否一致。 **表 1** CLASS\_VITAL\_INFO字段 --- --- url: /zh/docs/latest/sql_reference/class_vital_info.md --- # CLASS\_VITAL\_INFO CLASS\_VITAL\_INFO视图用于做WDR时校验相同的表或者索引的oid是否一致。 示例: ```sql openGauss=# select * from DBE_PERF.CLASS_VITAL_INFO; relid | schemaname | relname | relkind -------+--------------------+------------------------------------------------+--------- ``` **表 1** CLASS\_VITAL\_INFO字段 --- --- url: /en/docs/latest-lite/sql_reference/clean_connection.md --- # CLEAN CONNECTION ## Function **CLEAN CONNECTION** clears database connections. You may use this statement to delete a specific user's connections to a specified database. ## Precautions * openGauss does not support specified nodes and supports only TO ALL. * This function can be used to clear the normal connections that are being used only in force mode. ## Syntax ``` CLEAN CONNECTION TO { COORDINATOR ( nodename [, ... ] ) | NODE ( nodename [, ... ] )| ALL [ CHECK ] [ FORCE ] } [ FOR DATABASE dbname ] [ TO USER username ]; ``` ## Parameter Description * **CHECK** This parameter can be specified only when the node list is specified as **TO ALL**. Setting this parameter will check whether a database is accessed by other sessions before its connections are cleared. If any sessions are detected before **DROP DATABASE** is executed, an error will be reported and the database will not be deleted. * **FORCE** This parameter can be specified only when the node list is specified as **TO ALL**. Setting this parameter will send **SIGTERM** signals to all the threads related to the specified **dbname** and **username** and forcibly shut them down. * **COORDINATOR ( nodename \[, ... ] ) | NODE ( nodename \[, ... ] ) | ALL** Only **TO ALL** is supported. This parameter must be specified. All specified connections on the node will be deleted. * **dbname** Deletes connections to a specified database. If this parameter is not specified, connections to all databases will be deleted. Value range: an existing database name * **username** Deletes connections of a specific user. If this parameter is not specified, connections of all users will be deleted. Value range: an existing username ## Examples ``` -- Create user jack. CREATE USER jack PASSWORD 'xxxxxx'; -- Clean the user jack's connections to the template1 database. CLEAN CONNECTION TO ALL FOR DATABASE template1 TO USER jack; -- Delete all connections of user jack. CLEAN CONNECTION TO ALL TO USER jack; -- Clean all the connections to the gaussdb database. CLEAN CONNECTION TO ALL FORCE FOR DATABASE gaussdb; -- Delete user jack. DROP USER jack; ``` --- --- url: /en/docs/latest/sql_reference/clean_connection.md --- # CLEAN CONNECTION ## Function Clears database connections. You may use this statement to delete a specific user's connections to a specified database. ## Precautions * openGauss does not support specified nodes and supports only TO ALL. * This function can be used to clear the normal connections that are being used only in force mode. ## Syntax ``` CLEAN CONNECTION TO { COORDINATOR ( nodename [, ... ] ) | NODE ( nodename [, ... ] )| ALL [ CHECK ] [ FORCE ] } [ FOR DATABASE dbname ] [ TO USER username ]; ``` ## Parameters * **CHECK** This parameter can be specified only when the node list is specified as **TO ALL**. Setting this parameter will check whether a database is accessed by other sessions before its connections are cleared. If any sessions are detected before **DROP DATABASE** is executed, an error will be reported and the database will not be deleted. * **FORCE** This parameter can be specified only when the node list is specified as **TO ALL**. Setting this parameter will send **SIGTERM** signals to all the threads related to the specified **dbname** and **username** and forcibly shut them down. * **COORDINATOR ( nodename \[, ... ] ) | NODE ( nodename \[, ... ] ) | ALL** Deletes connections to a specified instance. There are three scenarios: * Deletes connections on a specified CN. openGauss does not support this scenario. * Deletes connections on a specified DN. openGauss does not support this scenario. * Deletes connections on all nodes(TO ALL). openGauss supports only this scenario. * **dbname** Deletes connections to a specified database. If this parameter is not specified, connections to all databases will be deleted. Value range: an existing database name * **username** Deletes connections of a specific user. If this parameter is not specified, connections of all users will be deleted. Value range: an existing username ## Examples ``` --Create user **jack**. CREATE USER jack PASSWORD 'xxxxxx'; --Clean the user **jack**'s connections to the postgres database: CLEAN CONNECTION TO ALL FOR DATABASE template1 TO USER jack; --Delete all connections of user **jack**. CLEAN CONNECTION TO ALL TO USER jack; --Clean all the connections to the **gaussdb** database. CLEAN CONNECTION TO ALL FORCE FOR DATABASE gaussdb; --Delete the user **jack**. DROP USER jack; ``` --- --- url: /zh/docs/latest-lite/sql_reference/clean_connection.md --- # CLEAN CONNECTION ## 功能描述 用来清理数据库连接。允许在节点上清理指定数据库的指定用户的相关连接。 ## 注意事项 * openGauss下不支持指定节点,仅支持TO ALL。 * 该功能仅在force模式下,可以清理正在使用的正常连接。 ## 语法格式 ``` CLEAN CONNECTION TO { COORDINATOR ( nodename [, ... ] ) | NODE ( nodename [, ... ] )| ALL [ CHECK ] [ FORCE ] } [ FOR DATABASE dbname ] [ TO USER username ]; ``` ## 参数说明 * **CHECK** 仅在节点列表为TO ALL时可以指定。如果指定该参数,会在清理连接之前检查数据库是否被其他会话连接访问。此参数主要用于DROP DATABASE之前的连接访问检查,如果发现有其他会话连接,则将报错并停止删除数据库。 * **FORCE** 仅在节点列表为TO ALL时可以指定,如果指定该参数,所有和指定dbname和username相关的线程都会收到SIGTERM信号,然后被强制关闭。 * **COORDINATOR ( nodename \[, ... ] ) | NODE ( nodename \[, ... ] ) | ALL** 仅支持TO ALL,必须指定该参数,节点上的指定连接会被全部删除。 * **dbname** 删除指定数据库上的连接。如果不指定,则删除所有数据库的连接。 取值范围:已存在数据库名。 * **username** 删除指定用户上的连接。如果不指定,则删除所有用户的连接。 取值范围:已存在的用户。 ## 示例 ``` --创建jack用户。 CREATE USER jack PASSWORD 'XXXXXXXX'; --删除用户jack在数据库template1上的所有连接。 CLEAN CONNECTION TO ALL FOR DATABASE template1 TO USER jack; --删除用户jack的所有连接。 CLEAN CONNECTION TO ALL TO USER jack; --删除在数据库gaussdb上的所有连接。 CLEAN CONNECTION TO ALL FORCE FOR DATABASE gaussdb; --删除用户jack。 DROP USER jack; ``` --- --- url: /zh/docs/latest/sql_reference/clean_connection.md --- # CLEAN CONNECTION ## 功能描述 用来清理数据库连接。允许在节点上清理指定数据库的指定用户的相关连接。 ## 注意事项 * openGauss下不支持指定节点,仅支持TO ALL。 * 该功能仅在force模式下,可以清理正在使用的正常连接。 ## 语法格式 ``` CLEAN CONNECTION TO { COORDINATOR ( nodename [, ... ] ) | NODE ( nodename [, ... ] )| ALL [ CHECK ] [ FORCE ] } [ FOR DATABASE dbname ] [ TO USER username ]; ``` ## 参数说明 * **CHECK** 仅在节点列表为TO ALL时可以指定。如果指定该参数,会在清理连接之前检查数据库是否被其他会话连接访问。此参数主要用于DROP DATABASE之前的连接访问检查,如果发现有其他会话连接,则将报错并停止删除数据库。 * **FORCE** 仅在节点列表为TO ALL时可以指定,如果指定该参数,所有和指定dbname和username相关的线程都会收到SIGTERM信号,然后被强制关闭。 * **COORDINATOR ( nodename \[, ... ] ) | NODE ( nodename \[, ... ] ) | ALL** 删除指定节点上的连接。有三种场景: * 删除指定CN上的连接,openGauss不支持。 * 删除指定DN上的连接,openGauss不支持。 * 删除所有节点上的连接(TO ALL),openGauss仅支持该场景。 * **dbname** 删除指定数据库上的连接。如果不指定,则删除所有数据库的连接。 取值范围:已存在数据库名。 * **username** 删除指定用户上的连接。如果不指定,则删除所有用户的连接。 取值范围:已存在的用户。 ## 示例 ``` --创建jack用户。 CREATE USER jack PASSWORD 'XXXXXXXX'; --删除用户jack在数据库template1上的所有连接。 CLEAN CONNECTION TO ALL FOR DATABASE template1 TO USER jack; --删除用户jack的所有连接。 CLEAN CONNECTION TO ALL TO USER jack; --删除在数据库gaussdb上的所有连接。 CLEAN CONNECTION TO ALL FORCE FOR DATABASE gaussdb; --删除用户jack。 DROP USER jack; ``` --- --- url: /en/docs/latest-lite/tool_and_commandreference/client_tool.md --- # Client Tool After a database is deployed, you need certain tools to connect to a database for operations and commissioning. openGauss provides some tools for database connections. You can use these tools to easily connect to the database and perform operations on it. * **[gsql](gsql.md)** --- --- url: /en/docs/latest-lite/sql_reference/close.md --- # CLOSE ## Function **CLOSE** frees the resources associated with an open cursor. ## Precautions * After a cursor is closed, no subsequent operations are allowed on it. * A cursor should be closed when it is no longer needed. * Every non-holdable open cursor is implicitly closed when a transaction is terminated by **COMMIT** or **ROLLBACK**. * A holdable cursor is implicitly closed if the transaction that created it aborts by **ROLLBACK**. * If the cursor creation transaction is successfully committed, the holdable cursor remains open until an explicit **CLOSE** operation is executed, or the client disconnects. * openGauss does not have an explicit **OPEN** cursor statement. A cursor is considered open when it is declared. You can view all available cursors by querying the **pg\_cursors** system view. * When the same cursor is opened twice in a row without closing, the cursor will implicitly **CLOSE** and continue to open before the second opening. ## Syntax ``` CLOSE { cursor_name | ALL } ; ``` ## Parameter Description * **cursor\_name** Specifies the name of a cursor to be closed. * **ALL** Closes all open cursors. ## Examples See [Examples](fetch.md#en-us_topic_0283137321_en-us_topic_0237122165_en-us_topic_0059778422_s1ee72832a27547e4949061a010e24578) in **FETCH**. ## Helpful Links [FETCH](fetch.md) and [MOVE](move.md) --- --- url: /en/docs/latest/sql_reference/close.md --- # CLOSE ## Function **CLOSE** frees the resources associated with an open cursor. ## Precautions * After a cursor is closed, no subsequent operations are allowed on it. * A cursor should be closed when it is no longer needed. * Every non-holdable open cursor is implicitly closed when a transaction is terminated by **COMMIT** or **ROLLBACK**. * A holdable cursor is implicitly closed if the transaction that created it aborts by **ROLLBACK**. * If the cursor creation transaction is successfully committed, the holdable cursor remains open until an explicit **CLOSE** operation is executed, or the client disconnects. * openGauss does not have an explicit **OPEN** cursor statement. A cursor is considered open when it is declared. You can view all available cursors by querying the **pg\_cursors** system view. * When the same cursor is opened twice in a row without closing, the cursor will implicitly **CLOSE** and continue to open before the second opening. ## Syntax ``` CLOSE { cursor_name | ALL } ; ``` ## Parameter Description * **cursor\_name** Specifies the name of a cursor to be closed. * **ALL** Closes all open cursors. ## Examples See [Examples](fetch.md#en-us_topic_0283137321_en-us_topic_0237122165_en-us_topic_0059778422_s1ee72832a27547e4949061a010e24578) in **FETCH**. ## Helpful Links [FETCH](fetch.md) and [MOVE](move.md) --- --- url: /zh/docs/latest-lite/sql_reference/close.md --- # CLOSE ## 功能描述 CLOSE释放和一个游标关联的所有资源。 ## 注意事项 * 不允许对一个已关闭的游标再做任何操作。 * 一个不再使用的游标应该尽早关闭。 * 当创建游标的事务用COMMIT或ROLLBACK终止之后,每个不可保持的已打开游标都隐含关闭。 * 当创建游标的事务通过ROLLBACK退出之后,每个可以保持的游标都将隐含关闭。 * 当创建游标的事务成功提交,可保持的游标将保持打开,直到执行一个明确的CLOSE或者客户端断开。 * openGauss没有明确打开游标的OPEN语句,因为一个游标在使用CURSOR命令定义的时候就打开了。可以通过查询系统视图pg\_cursors看到所有可用的游标。 * 当连续open同一个游标两次,而未进行close,那么第二次open前会隐式close掉游标,再进行open。 ## 语法格式 ``` CLOSE { cursor_name | ALL } ; ``` ## 参数说明 * **cursor\_name** 一个待关闭的游标名称。 * **ALL** 关闭所有已打开的游标。 ## 示例 请参考FETCH的[示例](fetch.md#zh-cn_topic_0283137321_zh-cn_topic_0237122165_zh-cn_topic_0059778422_s1ee72832a27547e4949061a010e24578)。 ## 相关链接 [FETCH](fetch.md),[MOVE](move.md) --- --- url: /zh/docs/latest/sql_reference/close.md --- # CLOSE ## 功能描述 CLOSE释放和一个游标关联的所有资源。 ## 注意事项 * 不允许对一个已关闭的游标再做任何操作。 * 一个不再使用的游标应该尽早关闭。 * 当创建游标的事务用COMMIT或ROLLBACK终止之后,每个不可保持的已打开游标都隐含关闭。 * 当创建游标的事务通过ROLLBACK退出之后,每个可以保持的游标都将隐含关闭。 * 当创建游标的事务成功提交,可保持的游标将保持打开,直到执行一个明确的CLOSE或者客户端断开。 * openGauss没有明确打开游标的OPEN语句,因为一个游标在使用CURSOR命令定义的时候就打开了。可以通过查询系统视图pg\_cursors看到所有可用的游标。 * 当连续open同一个游标两次,而未进行close,那么第二次open前会隐式close掉游标,再进行open。 ## 语法格式 ``` CLOSE { cursor_name | ALL } ; ``` ## 参数说明 * **cursor\_name** 一个待关闭的游标名称。 * **ALL** 关闭所有已打开的游标。 ## 示例 请参考FETCH的[示例](fetch.md#zh-cn_topic_0283137321_zh-cn_topic_0237122165_zh-cn_topic_0059778422_s1ee72832a27547e4949061a010e24578)。 ## 相关链接 [FETCH](fetch.md),[MOVE](move.md) --- --- url: /en/docs/latest-lite/developer_guide/closing_a_connection_jdbc.md --- # Closing a Connection After you complete required data operations in the database, close the database connection. Call the close method to close the connection, for example, **Connection conn = DriverManager.getConnection("url","user","password"); conn.close();** --- --- url: /en/docs/latest/developer_guide/closing_a_connection_jdbc.md --- # Closing a Connection After you complete required data operations in the database, close the database connection. Call the close method to close the connection, for example, **Connection conn = DriverManager.getConnection("url","user","password"); conn.close();** --- --- url: /en/docs/latest-lite/developer_guide/closing_the_connection_psycopg.md --- # Closing the Connection After you complete required data operations in a database, close the database connection. Call the close method such as **connection.close()** to close the connection. > \[!WARNING]CAUTION > This method closes the database connection and does not automatically call **commit()**. If you just close the database connection without calling **commit()** first, changes will be lost. --- --- url: /en/docs/latest/developer_guide/closing_the_connection_psycopg.md --- # Closing the Connection After you complete required data operations in a database, close the database connection. Call the close method such as **connection.close()** to close the connection. > \[!WARNING]CAUTION > This method closes the database connection and does not automatically call **commit()**. If you just close the database connection without calling **commit()** first, changes will be lost. --- --- url: /en/docs/latest-lite/sql_reference/cluster.md --- # CLUSTER ## Function **CLUSTER** is used to cluster a table based on an index. **CLUSTER** instructs openGauss to cluster the table specified by **table\_name** based on the index specified by **index\_name**. The index must have been defined by **table\_name**. When a table is clustered, it is physically reordered based on the index information. Clustering is a one-time operation. When the table is subsequently updated, the changes are not clustered. That is, no attempt is made to store new or updated rows according to their index order. When a table is clustered, openGauss records which index the table was clustered by. The form **CLUSTER table\_name** reclusters the table using the same index as before. You can also use the **CLUSTER** or **SET WITHOUT CLUSTER** form of **ALTER TABLE** to set the index to be used for future cluster operations, or to clear any previous settings. **CLUSTER** without any parameter reclusters all the previously-clustered tables in the current database that the calling user owns, or all such tables if called by an administrator. When a table is being clustered, an **ACCESS EXCLUSIVE** lock is acquired on it. This prevents any other database operations (both read and write) from being performed on the table until the **CLUSTER** is finished. ## Precautions * Only row-store B-tree indexes support **CLUSTER**. * In the case where you are accessing single rows randomly within a table, the actual order of the data in the table is unimportant. However, if you tend to access some data more than others, and there is an index that groups them together, it is helpful by using **CLUSTER**. If you are requesting a range of indexed values from a table, or a single indexed value that has multiple rows that match, **CLUSTER** will help because once the index identifies the table page for the first row that matches, all other rows that match are probably already on the same table page, and so you save disk accesses and speed up the query. * When an index scan is used, a temporary copy of the table is created that contains the table data in the index order. Temporary copies of each index on the table are created as well. Therefore, you need free space on disk at least equal to the sum of the table size and the total index size. * Because **CLUSTER** remembers which indexes are clustered, one can cluster the tables manually the first time, then set up a time like **VACUUM** without any parameters, so that the desired tables are periodically reclustered. * Because the optimizer records statistics about the ordering of tables, it is advisable to run **ANALYZE** on the newly clustered table. Otherwise, the optimizer might make poor choices of query plans. * **CLUSTER** cannot be executed in transactions. * If the **xc\_maintenance\_mode** parameter is not enabled, the CLUSTER operation will skip all system catalogs. ## Syntax * Cluster a table. ``` CLUSTER [ VERBOSE ] table_name [ USING index_name ]; ``` * Cluster a partition. ``` CLUSTER [ VERBOSE ] table_name PARTITION ( partition_name ) [ USING index_name ]; ``` * Recluster a table. ``` CLUSTER [ VERBOSE ]; ``` ## Parameter Description * **VERBOSE** Enables the display of progress messages. * **table\_name** Specifies the table name. Value range: an existing table name * **index\_name** Specifies the index name. Value range: an existing index name * **partition\_name** Specifies the partition name. Value range: an existing partition name ## Examples ``` -- Create a partitioned table. openGauss=# CREATE TABLE tpcds.inventory_p1 ( INV_DATE_SK INTEGER NOT NULL, INV_ITEM_SK INTEGER NOT NULL, INV_WAREHOUSE_SK INTEGER NOT NULL, INV_QUANTITY_ON_HAND INTEGER ) PARTITION BY RANGE(INV_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2451179), PARTITION P2 VALUES LESS THAN(2451544), PARTITION P3 VALUES LESS THAN(2451910), PARTITION P4 VALUES LESS THAN(2452275), PARTITION P5 VALUES LESS THAN(2452640), PARTITION P6 VALUES LESS THAN(2453005), PARTITION P7 VALUES LESS THAN(MAXVALUE) ); -- Create an index named ds_inventory_p1_index1. openGauss=# CREATE INDEX ds_inventory_p1_index1 ON tpcds.inventory_p1 (INV_ITEM_SK) LOCAL; -- Cluster the tpcds.inventory_p1 table. openGauss=# CLUSTER tpcds.inventory_p1 USING ds_inventory_p1_index1; -- Cluster the p3 partition. openGauss=# CLUSTER tpcds.inventory_p1 PARTITION (p3) USING ds_inventory_p1_index1; -- Cluster the tables that can be clustered in the database. openGauss=# CLUSTER; -- Delete the index. openGauss=# DROP INDEX tpcds.ds_inventory_p1_index1; -- Delete the partitioned table. openGauss=# DROP TABLE tpcds.inventory_p1; ``` ## Suggestions * cluster * It is recommended that you run **ANALYZE** on a newly clustered table. Otherwise, the optimizer might make poor choices of query plans. * **CLUSTER** cannot be executed in transactions. --- --- url: /en/docs/latest/sql_reference/cluster.md --- # CLUSTER ## Function **CLUSTER** is used to cluster a table based on an index. **CLUSTER** instructs openGauss to cluster the table specified by **table\_name** based on the index specified by **index\_name**. The index must have been defined by **table\_name**. When a table is clustered, it is physically reordered based on the index information. Clustering is a one-time operation. When the table is subsequently updated, the changes are not clustered. That is, no attempt is made to store new or updated rows according to their index order. When a table is clustered, openGauss records which index the table was clustered by. The form **CLUSTER table\_name** reclusters the table using the same index as before. You can also use the **CLUSTER** or **SET WITHOUT CLUSTER** form of **ALTER TABLE** to set the index to be used for future cluster operations, or to clear any previous settings. **CLUSTER** without any parameter reclusters all the previously-clustered tables in the current database that the calling user owns, or all such tables if called by an administrator. When a table is being clustered, an **ACCESS EXCLUSIVE** lock is acquired on it. This prevents any other database operations (both read and write) from being performed on the table until the **CLUSTER** is finished. ## Precautions * Only row-store B-tree indexes support **CLUSTER**. * In the case where you are accessing single rows randomly within a table, the actual order of the data in the table is unimportant. However, if you tend to access some data more than others, and there is an index that groups them together, it is helpful by using **CLUSTER**. If you are requesting a range of indexed values from a table, or a single indexed value that has multiple rows that match, **CLUSTER** will help because once the index identifies the table page for the first row that matches, all other rows that match are probably already on the same table page, and so you save disk accesses and speed up the query. * When an index scan is used, a temporary copy of the table is created that contains the table data in the index order. Temporary copies of each index on the table are created as well. Therefore, you need free space on disk at least equal to the sum of the table size and the total index size. * Because **CLUSTER** remembers which indexes are clustered, one can cluster the tables manually the first time, then set up a time like **VACUUM** without any parameters, so that the desired tables are periodically reclustered. * Because the optimizer records statistics about the ordering of tables, it is advisable to run **ANALYZE** on the newly clustered table. Otherwise, the optimizer might make poor choices of query plans. * **CLUSTER** cannot be executed in transactions. * If the **xc\_maintenance\_mode** parameter is not enabled, the CLUSTER operation will skip all system catalogs. ## Syntax * Cluster a table. ``` CLUSTER [ VERBOSE ] table_name [ USING index_name ]; ``` * Cluster a partition. ``` CLUSTER [ VERBOSE ] table_name PARTITION ( partition_name ) [ USING index_name ]; ``` * Recluster a table. ``` CLUSTER [ VERBOSE ]; ``` ## Parameter Description * **VERBOSE** Enables the display of progress messages. * **table\_name** Specifies the table name. Value range: an existing table name * **index\_name** Specifies the index name. Value range: an existing index name * **partition\_name** Specifies the partition name. Value range: an existing partition name ## Examples ``` -- Create a partitioned table. openGauss=# CREATE TABLE tpcds.inventory_p1 ( INV_DATE_SK INTEGER NOT NULL, INV_ITEM_SK INTEGER NOT NULL, INV_WAREHOUSE_SK INTEGER NOT NULL, INV_QUANTITY_ON_HAND INTEGER ) PARTITION BY RANGE(INV_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2451179), PARTITION P2 VALUES LESS THAN(2451544), PARTITION P3 VALUES LESS THAN(2451910), PARTITION P4 VALUES LESS THAN(2452275), PARTITION P5 VALUES LESS THAN(2452640), PARTITION P6 VALUES LESS THAN(2453005), PARTITION P7 VALUES LESS THAN(MAXVALUE) ); -- Create an index named ds_inventory_p1_index1. openGauss=# CREATE INDEX ds_inventory_p1_index1 ON tpcds.inventory_p1 (INV_ITEM_SK) LOCAL; -- Cluster the tpcds.inventory_p1 table. openGauss=# CLUSTER tpcds.inventory_p1 USING ds_inventory_p1_index1; -- Cluster the p3 partition. openGauss=# CLUSTER tpcds.inventory_p1 PARTITION (p3) USING ds_inventory_p1_index1; -- Cluster the tables that can be clustered in the database. openGauss=# CLUSTER; -- Delete the index. openGauss=# DROP INDEX tpcds.ds_inventory_p1_index1; -- Delete the partitioned table. openGauss=# DROP TABLE tpcds.inventory_p1; ``` ## Suggestions * cluster * It is recommended that you run **ANALYZE** on a newly clustered table. Otherwise, the optimizer might make poor choices of query plans. * **CLUSTER** cannot be executed in transactions. --- --- url: /zh/docs/latest-lite/sql_reference/cluster.md --- # CLUSTER ## 功能描述 根据一个索引对表进行聚簇排序。 CLUSTER指定openGauss通过索引名指定的索引聚簇由表名指定的表。 表名上必须已经定义该索引。 当对一个表聚集后,该表将基于索引信息进行物理存储。聚集是一次性操作:当表被更新之后, 更改的内容不会被聚集。也就是说,系统不会试图按照索引顺序对新的存储内容及更新记录进行重新聚集。 在对一个表聚簇之后,openGauss会记录在哪个索引上建立了聚集。 CLUSTER table\_name的聚集形式在之前的同一个索引的表上重新聚集。用户也可以用ALTER TABLE的CLUSTER或SET WITHOUT CLUSTER形式来设置索引来用于后续的聚集操作或清除任何之前的设置。 不含参数的CLUSTER会将当前用户所拥有的数据库中的先前做过聚簇的所有表重新处理,或者系统管理员调用的这些表。 在对一个表进行聚簇的时候,会在其上请求一个ACCESS EXCLUSIVE锁。这样就避免了在CLUSTER完成之前对此表执行其它的操作(包括读写)。 ## 注意事项 * 只有行存B-tree索引支持CLUSTER操作。 * 如果用户只是随机访问表中的行,那么表中数据的实际存储顺序是无关紧要的。但是, 如果对某些数据的访问多于其它数据,而且有一个索引将这些数据分组, 那么将使用CLUSTER中会有所帮助。如果从一个表中请求一定索引范围的值, 或者是一个索引值对应多行,CLUSTER也会有助于应用,因为如果索引标识出第一匹配行所在的存储页,所有其它行也可能已经在同一个存储页里了,这样便节省了磁盘访问的时间,加速了查询。 * 在聚簇过程中,系统先创建一个按照索引顺序建立的表的临时拷贝。同时也建立表上的每个索引的临时拷贝。因此,需要磁盘上有足够的剩余空间, 至少是表大小和索引大小的和。 * 因为CLUSTER记忆聚集信息,可以在第一次的时候手工对表进行聚簇,然后设置一个类似VACUUM的时间,这样就可以周期地自动对表进行聚簇操作。 * 因为优化器记录着有关表的排序的统计,所以建议在新近聚簇的表上运行ANALYZE。否则,优化器可能会选择很差劲的查询规划。 * CLUSTER不允许在事务中执行。 * 如果没有打开xc\_maintenance\_mode参数,那么CLUSTER操作将跳过所有系统表。 * 段页式表不支持CLUSTER操作。 ## 语法格式 * 对一个表进行聚簇排序。 ``` CLUSTER [ VERBOSE ] [CONCURRENTLY] table_name [ USING index_name ]; ``` * 对一个分区进行聚簇排序。 ``` CLUSTER [ VERBOSE ] [CONCURRENTLY] table_name PARTITION ( partition_name ) [ USING index_name ]; ``` * 对已做过聚簇的表重新进行聚簇。 ``` CLUSTER [ VERBOSE ]; ``` ## 参数说明 * **VERBOSE** 启用显示进度信息。 * **CONCURRENTLY** 使用在线DDL模式执行VACUUM FULL操作,只有VACUUM FULL可以使用在线DDL模式,只支持传统主备场景Astore、段页式的普通表、分区表进行修改列数据类型、修改行存压缩属性、添加列的约束(非空约束、范围约束)。 * **table\_name** 表名称。 取值范围:已存在的表名称。 * **index\_name** 索引名称。 取值范围:已存在的索引名称。 * **partition\_name** 分区名称。 取值范围:已存在的分区名称。 ## 示例 ``` -- 创建一个分区表。 openGauss=# CREATE TABLE tpcds.inventory_p1 ( INV_DATE_SK INTEGER NOT NULL, INV_ITEM_SK INTEGER NOT NULL, INV_WAREHOUSE_SK INTEGER NOT NULL, INV_QUANTITY_ON_HAND INTEGER ) PARTITION BY RANGE(INV_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2451179), PARTITION P2 VALUES LESS THAN(2451544), PARTITION P3 VALUES LESS THAN(2451910), PARTITION P4 VALUES LESS THAN(2452275), PARTITION P5 VALUES LESS THAN(2452640), PARTITION P6 VALUES LESS THAN(2453005), PARTITION P7 VALUES LESS THAN(MAXVALUE) ); -- 创建索引ds_inventory_p1_index1。 openGauss=# CREATE INDEX ds_inventory_p1_index1 ON tpcds.inventory_p1 (INV_ITEM_SK) LOCAL; -- 对表tpcds.inventory_p1进行聚集。 openGauss=# CLUSTER tpcds.inventory_p1 USING ds_inventory_p1_index1; -- 对分区p3进行聚集。 openGauss=# CLUSTER tpcds.inventory_p1 PARTITION (p3) USING ds_inventory_p1_index1; -- 对数据库中可以进行聚集的表进行聚集。 openGauss=# CLUSTER; --删除索引。 openGauss=# DROP INDEX tpcds.ds_inventory_p1_index1; --删除分区表。 openGauss=# DROP TABLE tpcds.inventory_p1; ``` --- --- url: /zh/docs/latest/sql_reference/cluster.md --- # CLUSTER ## 功能描述 根据一个索引对表进行聚簇排序。 CLUSTER指定openGauss通过索引名指定的索引聚簇由表名指定的表。表名上必须已经定义该索引。 当对一个表聚集后,该表将基于索引信息进行物理存储。聚集是一次性操作:当表被更新之后,更改的内容不会被聚集。也就是说,系统不会试图按照索引顺序对新的存储内容及更新记录进行重新聚集。 在对一个表聚簇之后,openGauss会记录在哪个索引上建立了聚集。CLUSTER table\_name的聚集形式在之前的同一个索引的表上重新聚集。用户也可以用ALTER TABLE的CLUSTER或SET WITHOUT CLUSTER形式来设置索引来用于后续的聚集操作或清除任何之前的设置。 不含参数的CLUSTER会将当前用户所拥有的数据库中的先前做过聚簇的所有表重新处理,或者系统管理员调用的这些表。 在对一个表进行聚簇的时候,会在其上请求一个ACCESS EXCLUSIVE锁。这样就避免了在CLUSTER完成之前对此表执行其它的操作(包括读写)。 ## 注意事项 * 只有行存B-tree索引支持CLUSTER操作。 * 如果用户只是随机访问表中的行,那么表中数据的实际存储顺序是无关紧要的。但是,如果对某些数据的访问多于其它数据,而且有一个索引将这些数据分组,那么将使用CLUSTER中会有所帮助。如果从一个表中请求一定索引范围的值,或者是一个索引值对应多行,CLUSTER也会有助于应用,因为如果索引标识出第一匹配行所在的存储页,所有其它行也可能已经在同一个存储页里了,这样便节省了磁盘访问的时间,加速了查询。 * 在聚簇过程中,系统先创建一个按照索引顺序建立的表的临时拷贝。同时也建立表上的每个索引的临时拷贝。因此,需要磁盘上有足够的剩余空间, 至少是表大小和索引大小的和。 * 因为CLUSTER记忆聚集信息,可以在第一次的时候手工对表进行聚簇,然后设置一个类似VACUUM的时间,这样就可以周期地自动对表进行聚簇操作。 * 因为优化器记录着有关表的排序的统计,所以建议在新近聚簇的表上运行ANALYZE。否则,优化器可能会选择很差劲的查询规划。 * CLUSTER不允许在事务中执行。 * 如果没有打开xc\_maintenance\_mode参数,那么CLUSTER操作将跳过所有系统表。 * 段页式表不支持CLUSTER操作。 ## 语法格式 * 对一个表进行聚簇排序。 ``` CLUSTER [ VERBOSE ] [CONCURRENTLY] table_name [ USING index_name ]; ``` * 对一个分区进行聚簇排序。 ``` CLUSTER [ VERBOSE ] [CONCURRENTLY] table_name PARTITION ( partition_name ) [ USING index_name ]; ``` * 对已做过聚簇的表重新进行聚簇。 ``` CLUSTER [ VERBOSE ]; ``` ## 参数说明 * **VERBOSE** 启用显示进度信息。 * **CONCURRENTLY** 使用在线DDL模式执行VACUUM FULL操作,只支持传统主备场景Astore、段页式的普通表、分区表进行修改列数据类型、修改行存压缩属性、添加列的约束(非空约束、范围约束)。 * **table\_name** 表名称。 取值范围:已存在的表名称。 * **index\_name** 索引名称。 取值范围:已存在的索引名称。 * **partition\_name** 分区名称。 取值范围:已存在的分区名称。 ## 示例 ``` -- 创建一个分区表。 openGauss=# CREATE TABLE tpcds.inventory_p1 ( INV_DATE_SK INTEGER NOT NULL, INV_ITEM_SK INTEGER NOT NULL, INV_WAREHOUSE_SK INTEGER NOT NULL, INV_QUANTITY_ON_HAND INTEGER ) PARTITION BY RANGE(INV_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2451179), PARTITION P2 VALUES LESS THAN(2451544), PARTITION P3 VALUES LESS THAN(2451910), PARTITION P4 VALUES LESS THAN(2452275), PARTITION P5 VALUES LESS THAN(2452640), PARTITION P6 VALUES LESS THAN(2453005), PARTITION P7 VALUES LESS THAN(MAXVALUE) ); -- 创建索引ds_inventory_p1_index1。 openGauss=# CREATE INDEX ds_inventory_p1_index1 ON tpcds.inventory_p1 (INV_ITEM_SK) LOCAL; -- 对表tpcds.inventory_p1进行聚集。 openGauss=# CLUSTER tpcds.inventory_p1 USING ds_inventory_p1_index1; -- 对分区p3进行聚集。 openGauss=# CLUSTER tpcds.inventory_p1 PARTITION (p3) USING ds_inventory_p1_index1; -- 对数据库中可以进行聚集的表进行聚集。 openGauss=# CLUSTER; --删除索引。 openGauss=# DROP INDEX tpcds.ds_inventory_p1_index1; --删除分区表。 openGauss=# DROP TABLE tpcds.inventory_p1; ``` --- --- url: >- /zh/docs/latest/characteristic_description/aifeature_guide/cluster_diagnosis.md --- # Cluster Diagnosis ## 概述 在现网业务中需要对发生的故障原因进行快速定位定界,本功能可以通过收集数据库实例中各个组件(如CMS、DN)等的信息和即时状态(如网络连通性),来判断实例环境是否存在故障,以及故障根因。可用于实现实例级别的故障根因诊断。 DBMind对cmd-exporter进行加强,本版本支持DN、CMS、CMA、ffic、OM\_Monitor等日志采集,同时也支持基于节点间网络连通(如ping)状态采集。同时DBMind对现网故障场景进行了梳理,并对数据集进行枚举扩充,最终实现DN故障快速定位。 > \[!NOTE]说明 > 由于该功能是根据日志来进行诊断的,所以诊断结果中的时间可能因为日志的延迟或者日志的延迟处理,导致诊断结果中的时间晚于故障发生的时间。 **表 1** 现支持诊断的DN故障根因列表 > \[!NOTE]说明 > 当cm\_ctl query的集群状态输出结果异常时,一般是发生了调用栈输出,这种情况下难以获取集群状态,无法获取集群的诊断结果,相关状态标记为"abnormal\_output\_from\_cm\_ctl\_query", 诊断结果为Unknown。 > 当DN节点处于Offline状态时,不对其进行数据库实例故障诊断,返回状态为Normal,状态码-1。 ## 使用指导 在DN实例产生异常告警时,一个完整的用于启动实例故障分析功能的命令是: ``` gs_dbmind component cluster_diagnosis --conf {confpath} --host {ip_address} --role dn --time "2023-04-20 16:00:00" --method tree ``` 输入此命令后,系统读取所设定时间前3分钟的日志记录,并对选定的DN实例使用选定方法进行分析,分析的结果示例如[图1](#zh-cn_topic_0000001714948973_fig0615168103510)所示。 **图 1** DN实例使用选定方法分析\ ![](figures/DN实例使用选定方法分析.png) 返回结果前半部分的字典给出对日志的解析结果,其中Good表示该项正常,Bad表示该项有异常;最后的Output表示输出结果。 > \[!NOTE]说明 > > * 单次诊断读取的是诊断时间点之前三分钟的日志和节点状态,由于网络延迟,模型计算用时等因素,实际时间会略短于三分钟,综合各种因素,以150秒内的诊断结果作为参考更为准确。 > * 集群故障诊断功能的网络连通性诊断是通过各个数据库节点之间的连通性来判断的,对于单节点集群,不存在数据库节点之间的连通性,所以集群诊断不支持单节点集群的故障诊断。 > * 数据库实例诊断功能中,判断网络连通性的超时时长是1秒,当网络延迟达到1秒及以上时,节点会被判断为断开连接。 > * 尝试对于新近纳管的集群进行集群诊断时,由于采集数据存在延迟,可能会出现短暂的网络异常。 ## 获取帮助 模块命令行说明: ``` gs_dbmind component cluster_diagnosis --help ``` 显示如下帮助信息: ``` usage: [-h] --conf CONF --host HOST --role {cn,dn} [--time TIME] [--method {logical,tree}] Cluster diagnosis. optional arguments: -h, --help show this help message and exit --conf CONF set the directory of configuration files --host HOST set the host of the cluster node, ip only. --role {cn,dn} set the role of instance for diagnosis. roles: [cn] are not supported for centralized DB. --time TIME set time for diagnosis in timestamp(ms) or datetime format --method {logical,tree} set method for the model: logical: if-else, tree: xgboost. ``` ## 命令参考 **表 1** 命令行参数说明 ## 常见问题处理 如果尝试启动实例诊断时发现系统不能返回预期的诊断结果,需按照以下顺序逐项排查: * 检查连接时序数据库需要的配置文件地址是否输入正确,是否包含实例诊断需要读取的日志文件,所用账户是否有权限读写日志,以及日志文件是否损坏,能否正常读写。 * 检查目标节点的IP地址是否有误。 * 检查是否支持对所选定的实例进行诊断,实例诊断目前仅支持对DN的诊断,并检查参数是否输入正确。 * 检查所键入的异常发生时间点是否符合日期时间格式,此外,实例诊断仅支持对当前及过去时刻的诊断,即只能针对过去或与当前时间点相关的事件。 * 检查所选择的诊断方法是否有输入正确,并且是否超出支持范围。 * 对于网卡故障的监测,建议在时序数据库采集数据时将cmd-exporter同时连接在多个网卡上,以便在其中某一网卡故障时,其他网卡仍然能正常将消息发送。 --- --- url: /en/docs/latest/characteristic_description/cm.md --- # CM ## Availability This feature is available since openGauss 3.0.0. ## Introduction Cluster manager (CM) is a database management software, which consists of cm\_server and cm\_agent. * cm\_agent is a database management component deployed on each database host. It is used to start, stop, and monitor database instance processes. * cm\_server is a component used for managing database instances and arbitrating instances. ## Benefits It manages and monitors the running status of functional units and physical resources in a database system, ensuring stable running of the system. ## Description It supports customized resource monitoring and provides capabilities such as monitoring of the primary/standby database status, network communication faults, file system faults, and automatic primary/standby switchover upon faults. It also provides various database management capabilities, such as starting and stopping nodes and instances, querying database instance status, performing primary/standby switchover, and managing logs. ## Enhancements The CM supports external status query and push. * The HTTP/HTTPS service is used to remotely query the cluster status, helping management personnel and O\&M platforms monitor the cluster status. * When an primary/standby switchover occurs in the database cluster, the latest primary/standby information of the cluster is pushed to the receiving address registered by the application through the HTTP/HTTPS service in time. In this way, the application can detect the primary/standby change of the cluster in time and quickly connect to the new primary and standby nodes. The CM supports two-node deployment mode * The minimum number of nodes in the CM cluster is reduced from 3 nodes to 2 nodes, bringing significant cost advantages. * By introducing a third-party gateway IP, it effectively solves the self-arbitration problem in the two-node deployment mode of the CM cluster, and supports dynamic configuration of the CM cluster failover strategy and the database cluster split-brain fault recovery strategy, so as to ensure data integrity and consistency as much as possible. The CM supports automatic cleanup of gstor archive logs (introduced in 7.0.0RC2) * Added automatic cleanup functionality for gstor archive logs. When the size of gstor archive logs exceeds 85% of the threshold (2G), the automatic archive log cleanup policy is triggered, and after cleanup, 15% of the threshold size is retained. ## Constraints Versions before 5.0.0, in scenarios where there are one primary node and one standby node, CM supports only basic capabilities, such as installation, startup, stop, and detection. ## Dependencies None. --- --- url: /zh/docs/latest/characteristic_description/cm.md --- # CM ## 可获得性 本特性自openGauss 3.0.0版本开始引入。 ## 特性简介 CM(Cluster Manager)是一款数据库管理软件,由cm\_server和cm\_agent组成。 * cm\_agent是部署在数据库每个主机上,用来启停和监控各个数据库实例进程的数据库管理组件。 * cm\_server是用来进行数据库实例管理和实例仲裁的组件。 ## 客户价值 管理和监控数据库系统中各个功能单元和物理资源的运行情况,确保整个系统的稳定运行。 ## 特性描述 支持自定义资源监控,提供了数据库主备的状态监控、网络通信故障监控、文件系统故障监控、故障自动主备切换等能力。提供了丰富的数据库管理能力,如节点、实例级的启停,数据库实例状态查询、主备切换、日志管理等。 ## 特性增强 CM支持对外状态查询和推送能力 * 通过http/https服务远程查询到集群的状态,便于管理人员、运维平台等监控集群状态 * 在数据库集群发生切主事件时,通过http/https服务及时地将集群最新的主备信息推送到应用端注册的接收地址,便于应用端及时的感知到集群的主备变化,从而能够快速的连接到新的主机和备机。 CM支持两节点部署模式 * CM集群最小节点数限制由3节点减少为2节点,带来显著的成本优势 * 通过引入第三方网关IP,有效解决CM集群两节点部署模式下自仲裁问题,同时支持动态配置CM集群故障切换策略和数据库集群脑裂故障恢复策略,从而能够尽可能确保集群数据的完整性和一致性。 CM两节点部署增强(6.0.0引入) * CM支持多个三方IP检测(third\_party\_gateway\_ip),可以预防CM脑裂。 * 当CM为两节点部署时,cm\_server参数third\_party\_gateway\_ip支持以逗号分隔的多个IP。在两节点环境中,cms\_enable\_failover\_on2nodes配置为true时,节点1与节点2的cm\_server会将以与第三方网关的连通条件作为cm\_server是否升主的条件之一。具体如下:当节点CM与三方网关中配置的所有IP都能ping通时,CM会升主;当节点CM与三方网关中配置的所有IP都不能ping通时,CM会降备。即CM升主与降备的条件是三方网关的所有IP都能ping通或者不能ping通。 支持CM部署与数据库部署解耦 * 已经部署了openGauss数据库集群,但是尚未部署CM的集群直接部署CM,而不需要通过升级的方式将CM带入 支持一键式暂停/恢复CM服务 * 支持一键暂停CM自动故障处理服务,避免运维人员在运维过程中的操作受到CM影响,运维完成之后可以一键恢复CM服务 支持按事件触发调用用户自定义脚本 * 在特定事件发生后,由CM自动触发用户自定义的脚本,执行相应的操作 CM支持容器化部署 * 支持将CM和数据库打包到docker镜像中,并启动两个以上的容器实例组成CM集群。 * 已经部署了openGauss数据库集群,但是尚未部署CM的集群直接部署CM,而不需要通过升级的方式将CM带入 支持一键式暂停/恢复CM服务 * 支持一键暂停CM自动故障处理服务,避免运维人员在运维过程中的操作受到CM影响,运维完成之后可以一键恢复CM服务 支持按事件触发调用用户自定义脚本 * 在特定事件发生后,由CM自动触发用户自定义的脚本,执行相应的操作 CM支持在多数派节点未回放完的情况下选主(6.0.0引入) * CM发起选主流程中,若多数派节点未回放完,直接找到Local max replay lsn最大的节点为主,指定其为主,等待该节点回放结束后升主,不再等待多数派回的节点放完。 CM磁盘使用率管理能力增强 * 支持PGDATA目录下软连接(主要针对base、global、pg\_xlog、pg\_tblspc及以下表空间)所在真实目录对应磁盘使用率的管理。 CM支持最大可用模式动态调整(6.0.0引入) * CM支持管理数据库最大可用模式参数most\_available\_sync。当数据库集群同步备机数量不满足要求时,CM可以打开数据库最大可用模式,以保证数据库主节点的可用性。 * 当允许CM管理数据库最大可用模式时,需要将cm\_server.conf配置文件中enable\_set\_most\_available\_sync参数设置为on,否则应该设置为off。 * 当允许CM管理数据库最大可用模式时,如果数据库主节点因为同步备机故障或者期待的同步备机数量不足导致主机事务提交被hang住,由CM自动打开数据库最大可用模式;当同步备机数量满足要求时,由CM自动关闭数据库最大可用模式。 CM支持安装管理ipv6的数据库集群(7.0.0RC1引入) CM支持DCC自动build * 增加DCC build机制,识别到日志不接续时,DCC内部会自动全量build主节点的日志。 CM支持gstor的归档日志自动清理(7.0.0RC2引入) * 添加gstor的归档日志自动清理功能,当gstor的归档日志大小超过阈值(2G)的85%时,触发自动清理归档日志策略,清理后保留阈值的15%大小。 CM支持显示灵衢场景下UBSE集群内存详情 (7.0.0RC2引入) * 添加显示MXE集群内存功能,返回实时内存总量、借入借出以及可借用内存大小。 ## 特性约束 一主一备模式下,5.0.0之前的版本中CM只支持基本的安装、启停、检测能力,其他功能不支持。 ## 依赖关系 无。 --- --- url: /en/docs/latest/database_reference/cm-parameters.md --- # CM Parameters Modifying CM parameters affects the running mechanism of GaussDB Kernel. You are advised to ask GaussDB Kernel engineers to do it for you. For details about how to modify the CM parameters, see method 1 in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). * **[Parameters Related to cm\_agent](parameters-related-to-cm_agent.md)** * **[Parameters Related to cm\_server](parameters-related-to-cm_server.md)** --- --- url: /en/docs/latest/tool_and_commandreference/cm_parameters.md --- # CM Parameters Modifying CM parameters affects the running mechanism of GaussDB Kernel. You are advised to ask GaussDB Kernel engineers to do it for you. For details about how to modify the CM parameters, see method 1 in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). * **[Parameters Related to cm\_agent](parameters_related_to_cm_agent.md)** * **[Parameters Related to cm\_server](parameters_related_to_cm_server.md)** --- --- url: /zh/docs/latest/resource_pooling/cm_syssentry_fault_detection.md --- # CM SysSentry故障检测 ## 可获得性 本特性自openGauss 7.0.0版本开始引入。 ## 特性简介 CM支持对接SysSentry故障事件通道,实现节点故障快速感知。 ## 客户价值 提升集群对节点异常的感知速度,降低人工介入成本,增强故障处理闭环能力。 ## 特性描述 CM通过cm\_agent接收SysSentry事件,并将关键故障事件上报cm\_server,由集群控制面执行后续处置(如节点踢出、仲裁流程触发)。 ## 特性增强 * openGauss 7.0.0 支持CM SysSentry故障检测能力。 ## 特性约束 * 满足灵衢总线协议的服务器。 * 依赖操作系统侧SysSentry能力。 * 需要在cm\_agent侧开启对应配置后生效。 * 当前仅覆盖CM定义的关键故障处理场景。 ## 基本原理 * cm\_agent订阅故障事件并解析节点信息,通过SysSentry快速感知节点级故障。 * 事件上报至cm\_server后,CM按集群状态执行对应处置策略。 ## 使用指导 * 启动SysSentry服务并开启目标故障事件检测。 * 开启cm\_agent事件检测能力并正确配置节点映射。 * 重启cm\_agent使配置生效。 ## 使用场景 * 发生panic、reboot等节点级故障时,需快速触发CM仲裁。 --- --- url: /zh/docs/latest/tool_and_commandreference/parameters_related_to_cm_agent.md --- # cm\_agent参数 ## log\_dir **参数说明**: log\_dir决定存放cm\_agent日志文件的目录。 可以是绝对路径,或者是相对路径(相对于$GAUSSLOG的路径)。通过cm\_ctl设置绝对路径时需要将路径用''把路径包含起来,例如:cm\_ctl set --param --agent -k log\_dir="'/log/dir'"。 **取值范围**: 字符串,最大长度为1024。修改后需要重启cm\_agent才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: “log”,表示在$GAUSSLOG下对应的cm目录下生成cm\_agent日志。 ## log\_file\_size **参数说明**: 控制日志文件的大小。当cm\_agent-xx-current.log日志文件达到指定大小时,则重新创建一个日志文件记录日志信息。 **取值范围**: 整型,\[0, 2047],实际生效范围\[1, 2047],单位:MB。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 16MB。 ## log\_min\_messages **参数说明**: 控制写到cm\_agent日志文件中的消息级别。每个级别都包含排在它后面的所有级别中的信息。级别越低,服务器运行日志中记录的消息就越少。 **取值范围**: 枚举类型,有效值有debug5、debug1、warning、error、log、fatal(不区分大小写)。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514) 进行设置。 **默认值**: warning ## incremental\_build **参数说明**: 控制重建备节点模式是否为增量。打开这个开关,则增量重建备节点;否则,全量重建备节点。 **取值范围**: 布尔型。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示增量重建备节点。 * off、no、false、0:表示全量重建备节点。 **默认值**: on ## security\_mode **参数说明**: 控制是否以安全模式启动节点。打开这个开关,则以安全模式启动节点;否则,以非安全模式启动节点。 **取值范围**: 布尔型。修改后可以动态生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示以安全模式启动节点。 * off、no、false、0:表示以非安全模式启动节点。 **默认值**: off ## upgrade\_from **参数说明**: 升级过程中使用,用于标示升级前数据库的内部版本号,此参数禁止手动修改。 **取值范围**: 非负整型,\[0, 4294967295]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 0 ## alarm\_component **参数说明**: 在使用第一种告警方式时,设置用于处理告警内容的告警组件的位置。通过cm\_ctl设置绝对路径时需要将路径用''把路径包含起来,例如:cm\_ctl set --param --agent -k alarm\_component="'/alarm/dir'"。 **取值范围**: 字符串,最大长度为1024。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: /opt/huawei/snas/bin/snas\_cm\_cmd ## alarm\_report\_interval **参数说明**: 指定告警上报的时间间隔。 **取值范围**: 非负整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1 ## agent\_heartbeat\_timeout **参数说明**: cm\_server心跳超时时间。 **取值范围**: 整型,\[2, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 5 ## agent\_connect\_timeout **参数说明**: cm\_agent连接cm\_server超时时间。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1 ## agent\_connect\_retries **参数说明**: cm\_agent连接cm\_server尝试次数。 **取值范围**: 整型,\[0, 2147483647]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 15 ## agent\_kill\_instance\_timeout **参数说明:当**cm\_agent在无法连接cm\_server主节点后,发起一次杀死本节点上所有实例的操作之前,所需等待的时间间隔。 **取值范围**: 整型,\[0, 2147483647]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 0,不发起杀死本节点上所有实例的操作。 ## agent\_report\_interval **参数说明**: cm\_agent上报实例状态的时间间隔。 **取值范围**: 整型,\[0, 2147483647]。单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1 ## alarm\_report\_max\_count **参数说明**: 指定告警上报的最大次数。 **取值范围**: 非负整型,\[1, 2592000]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1 ## agent\_check\_interval **参数说明**: cm\_agent查询实例状态的时间间隔。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 2 ## enable\_log\_compress **参数说明**:控制压缩日志功能。 **取值范围**:布尔型。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示允许压缩日志。 * off、no、false、0:表示不允许压缩日志。 **默认值**:on ## process\_cpu\_affinity **参数说明**: 控制是否以绑核优化模式启动主节点进程。配置该参数为0,则不进行绑核优化;否则,进行绑核优化,且物理CPU片数为2n个。仅支持ARM。 **取值范围**: 整型,\[0, 2]。修改后需要重启数据库、cm\_agent才能生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 0 ## enable\_xc\_maintenance\_mode **参数说明**: 在数据库为只读模式下,控制是否可以修改pgxc\_node系统表。 **取值范围**: 布尔型。修改后需要重启cm\_agent才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示开启可以修改pgxc\_node系统表功能。 * off、no、false、0:表示关闭可以修改pgxc\_node系统表功能。 **默认值**: on ## log\_threshold\_check\_interval **参数说明**:cm日志压缩和清除的时间间隔,每1800秒压缩和清理一次。 **生效范围**:由 **本节点 cm\_agent** 在 `enable_log_compress = on` 且环境变量 `GAUSSLOG` 有效时执行;递归扫描 **整个 `$GAUSSLOG` 目录树**(不仅限于 `$GAUSSLOG/cm/`)。对文件名匹配下列前缀的历史日志生效(当前正在写入的 `-current` 日志及同组最新未压缩文件不参与压缩)。匹配前缀包括: * cm\_agent-、cm\_server-、cm\_ctl-、cm\_client-、om\_monitor-、system\_call-、system\_alarm- * gs\_clean-、gs\_ctl-、gs\_guc-、gs\_dump-、gs\_dumpall-、gs\_restore-、gs\_upgrade-、gs\_initcm-、gs\_initdb-、gs\_local-、gs\_preinstall-、gs\_install-、gs\_replace-、gs\_uninstall-、gs\_om-、pssh-、gs\_upgradectl-、gs\_expand-、gs\_shrink-、gs\_postuninstall-、gs\_backup-、gs\_checkos-、gs\_collector-、GaussReplace-、GaussOM-、gs\_checkperf-、gs\_check-、gs\_cgroup-、pscp-、gs\_hotpatch- * roach\_agent-、roach\_controller-、sync-、postgresql-、sessionstat-、pg\_perf-、slow\_query\_log-、asp-、etcd-、cmd\_sender-、uploader-、checkRunStatus-、ffic\_gaussdb-、key\_event-、mem\_log- * gs\_initgtm-、gtm\_ctl-、gtm- **取值范围**:整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:1800 ## log\_max\_size **参数说明**:控制cm日志最大存储值,当CM日志总大小超过(log\_max\_size\*95/100)MB时,根据压缩日志生成时间,依次删除历史压缩日志,直到日志总大小小于(log\_max\_size\*95/100)MB。 **生效范围**:由 **本节点 cm\_agent** 在 `enable_log_compress = on` 且环境变量 `GAUSSLOG` 有效时执行;递归扫描 **整个 `$GAUSSLOG` 目录树**(不仅限于 `$GAUSSLOG/cm/`)。对文件名匹配下列前缀的历史日志生效(当前正在写入的 `-current` 日志及同组最新未压缩文件不参与压缩)。匹配前缀包括: * cm\_agent-、cm\_server-、cm\_ctl-、cm\_client-、om\_monitor-、system\_call-、system\_alarm- * gs\_clean-、gs\_ctl-、gs\_guc-、gs\_dump-、gs\_dumpall-、gs\_restore-、gs\_upgrade-、gs\_initcm-、gs\_initdb-、gs\_local-、gs\_preinstall-、gs\_install-、gs\_replace-、gs\_uninstall-、gs\_om-、pssh-、gs\_upgradectl-、gs\_expand-、gs\_shrink-、gs\_postuninstall-、gs\_backup-、gs\_checkos-、gs\_collector-、GaussReplace-、GaussOM-、gs\_checkperf-、gs\_check-、gs\_cgroup-、pscp-、gs\_hotpatch- * roach\_agent-、roach\_controller-、sync-、postgresql-、sessionstat-、pg\_perf-、slow\_query\_log-、asp-、etcd-、cmd\_sender-、uploader-、checkRunStatus-、ffic\_gaussdb-、key\_event-、mem\_log- * gs\_initgtm-、gtm\_ctl-、gtm- **取值范围**:整型,\[0, 2147483647],单位:MB。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:10240 ## log\_max\_count **参数说明**:cm可存储的最多日志数量,当cm日志总个数超过该值,根据压缩日志文件名时间,删除超过保留天数log\_saved\_days的压缩日志。 **生效范围**:由 **本节点 cm\_agent** 在 `enable_log_compress = on` 且环境变量 `GAUSSLOG` 有效时执行;递归扫描 **整个 `$GAUSSLOG` 目录树**(不仅限于 `$GAUSSLOG/cm/`)。对文件名匹配下列前缀的历史日志生效(当前正在写入的 `-current` 日志及同组最新未压缩文件不参与压缩)。匹配前缀包括: * cm\_agent-、cm\_server-、cm\_ctl-、cm\_client-、om\_monitor-、system\_call-、system\_alarm- * gs\_clean-、gs\_ctl-、gs\_guc-、gs\_dump-、gs\_dumpall-、gs\_restore-、gs\_upgrade-、gs\_initcm-、gs\_initdb-、gs\_local-、gs\_preinstall-、gs\_install-、gs\_replace-、gs\_uninstall-、gs\_om-、pssh-、gs\_upgradectl-、gs\_expand-、gs\_shrink-、gs\_postuninstall-、gs\_backup-、gs\_checkos-、gs\_collector-、GaussReplace-、GaussOM-、gs\_checkperf-、gs\_check-、gs\_cgroup-、pscp-、gs\_hotpatch- * roach\_agent-、roach\_controller-、sync-、postgresql-、sessionstat-、pg\_perf-、slow\_query\_log-、asp-、etcd-、cmd\_sender-、uploader-、checkRunStatus-、ffic\_gaussdb-、key\_event-、mem\_log- * gs\_initgtm-、gtm\_ctl-、gtm- **取值范围**:整型,\[0, 30000],单位:个。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:30000 ## log\_saved\_days **参数说明**:cm压缩日志保存的天数,cm压缩日志超过该值并且cm日志总个数超过log\_max\_count,删除压缩日志。 **生效范围**:由 **本节点 cm\_agent** 在 `enable_log_compress = on` 且环境变量 `GAUSSLOG` 有效时执行;递归扫描 **整个 `$GAUSSLOG` 目录树**(不仅限于 `$GAUSSLOG/cm/`)。对文件名匹配下列前缀的历史日志生效(当前正在写入的 `-current` 日志及同组最新未压缩文件不参与压缩)。匹配前缀包括: * cm\_agent-、cm\_server-、cm\_ctl-、cm\_client-、om\_monitor-、system\_call-、system\_alarm- * gs\_clean-、gs\_ctl-、gs\_guc-、gs\_dump-、gs\_dumpall-、gs\_restore-、gs\_upgrade-、gs\_initcm-、gs\_initdb-、gs\_local-、gs\_preinstall-、gs\_install-、gs\_replace-、gs\_uninstall-、gs\_om-、pssh-、gs\_upgradectl-、gs\_expand-、gs\_shrink-、gs\_postuninstall-、gs\_backup-、gs\_checkos-、gs\_collector-、GaussReplace-、GaussOM-、gs\_checkperf-、gs\_check-、gs\_cgroup-、pscp-、gs\_hotpatch- * roach\_agent-、roach\_controller-、sync-、postgresql-、sessionstat-、pg\_perf-、slow\_query\_log-、asp-、etcd-、cmd\_sender-、uploader-、checkRunStatus-、ffic\_gaussdb-、key\_event-、mem\_log- * gs\_initgtm-、gtm\_ctl-、gtm- **取值范围**:整型,\[0, 1000],单位天。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:90 > \[!TIP]须知 > 日志压缩能力受限于内存限制,最多只能检测到30000个日志文件。总日志量超过30000个文件时,则无法保证日志能被正常压缩及删除。可以通过调整log\_saved\_days和log\_threshold\_check\_interval快速清理已压缩日志文件。 ## agent\_phony\_dead\_check\_interval **参数说明**: cm\_agent检测进程是否僵死的时间间隔。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 10 ## unix\_socket\_directory **参数说明**: unix套接字的目录位置。通过cm\_ctl设置绝对路径时需要将路径用''把路径包含起来,例如:cm\_ctl set --param --agent -k unix\_socket\_directory="'/unix/dir'"。 **取值范围**: 字符串,最大长度为1024。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值:''** ## dilatation\_shard\_count\_for\_disk\_capacity\_alarm **参数说明**:扩容场景下,设置新增的扩容分片数,用于上报磁盘容量告警时的阈值计算。 **取值范围**:整型,\[0, 2147483647],单位:个。该参数设置为0,表示关闭磁盘扩容告警上报;该参数设置为大于0,表示开启磁盘扩容告警上报,且告警上报的阈值根据此参数设置的分片数量进行计算。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:1 ## enable\_dcf **参数说明**:DCF模式开关。 **取值范围**:布尔型。修改后需要重启cm\_agent才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示启用dcf。 * off、no、false、0:表示不启用dcf。 **默认值**:off ## disaster\_recovery\_type **参数说明**:主备数据库灾备关系的类型。 **取值范围**:整型,\[0, 2]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * 0表示未搭建灾备关系。 * 1表示搭建了obs灾备关系。 * 2表示搭建了流式灾备关系 **默认值**:0 ## agent\_backup\_open **参数说明**:灾备模式设置,开启后CM按照灾备模式运行。 **取值范围**:整型,\[0, 2]。修改后需要重启cm\_agent才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * 0表示未搭建灾备关系。 * 1表示搭建了obs灾备关系(之后不再支持)。 * 2表示搭建了流式灾备关系。 **默认值**:0 ## disk\_timeout **参数说明**: 磁盘心跳超时时间。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 200 ## voting\_disk\_path **参数说明**: 投票盘路径。 **取值范围**: 字符串,最大长度为1024。修改后需要重启cm\_agent才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 无,需要安装时进行配置。 ## agent\_rhb\_interval **参数说明**: cma节点间网络连通性检测周期。 **取值范围**: 整型,\[0, 2147483647],单位:毫秒。修改后需要重启cm\_agent才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1000 ## enable\_ssl **参数说明**:ssl证书开关。 **取值范围**:布尔型。打开后使用ssl证书加密通信。修改后需要重启cm\_agent才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示启用ssl。 * off、no、false、0:表示不启用ssl。 * **默认值**:on > \[!TIP]须知 > 出于安全性考虑,建议不要关闭该配置。关闭后cm将**不使用**加密通信,所有信息明文传播,可能带来窃听、篡改、冒充等安全风险。 ## ssl\_cert\_expire\_alert\_threshold **参数说明**:ssl证书过期告警时间。 **取值范围**:整型,\[7, 180],单位:天。证书过期时间少于该时间时,上报证书即将过期告警。修改后需要重启cm\_agent才能生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:90 ## ssl\_cert\_expire\_check\_interval **参数说明**:ssl证书过期检测周期。 **取值范围**:整型,\[0, 2147483647],单位:秒。修改后需要重启cm\_agent才能生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:86400 ## enable\_fence\_dn **参数说明**:cm\_agent连不上任何除了自身节点的cms,并且自身节点cms不是Primary时,设置是否重启datanode进程。 **取值范围**:布尔型。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示重启datanode进程。 * off、no、false、0:表示不重启datanode进程。 **默认值**:off ## event\_triggers **参数说明**: 该参数用于定义事件触发器。 **取值范围**:以字符串表示的json类型。\ 配置形式为:'{"trigger\_type\_1":"trigger\_value\_1",...,"trigger\_type\_n":"trigger\_value\_n"}'\ 其中: > trigger\_type为事件触发器类型,当前支持的事件触发器类型为:on\_start、on\_stop、on\_failover、on\_switchover > trigger\_value为发生对应事件时待执行的用户自定义触发器脚本 修改后重载cm\_agent参数生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 自定义脚本的输出会重定向至cm\_agent日志目录下的system-callxxx.log中。 **默认值**:'' **约束条件**: 1. trigger\_value即自定义脚本,必须为真实存在的shell脚本,且为绝对路径,并且对当前用户至少有读取和执行权限。 2. 使用cm\_ctl set命令配置该参数时,参数值必须符合json格式,并且将json类型表示为字符串类型,中间不能包含换行和空格。 3. 参数值最大长度为1024。 **配置样例**: '{"on\_start":"/dir/on\_start.sh","on\_stop":"/dir/on\_stop.sh","on\_failover":"/dir/on\_failover.sh","on\_switchover":"/dir/on\_switchover.sh"}' > \[!WARNING]注意 > 由于CM内部对各事件的执行均是异步执行,即将事件置于后台执行,所以CM在调用用户自定义的触发器脚本时,有可能事件还尚未执行完成,所以用户自定义触发器脚本中如果是需要等待事件完成后才执行动作的话,则需要在脚本中添加对应的状态检查,以确保事件完成。 ## db\_service\_vip **参数说明**: 数据库集群对外提供服务的VIP。 **取值范围**: 字符串。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 无,安装时可选配置。 ## ss\_double\_cluster\_mode **参数说明**: 资源池化主备双集群容灾场景下数据库集群的启动方式。 **取值范围**: 整型,\[0, 2]。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * 0表示非资源池化主备双集群容灾模式。 * 1表示以资源池化主集群模式启动。 * 2表示以资源池化备集群模式启动。 **默认值**: 0 ## environment\_threshold **参数说明**: 告警检测功能阈值参数,前三个参数分别为内存、cpu、io阈值参数,超过该值会触发cm告警。 **取值范围**: 字符串,格式同(90,90,90,0,0)。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: (90,90,90,0,0) ## diskusage\_threshold\_value\_check **参数说明**: 磁盘告警检测功能阈值参数,当某个节点数据库使用的磁盘占用阈值超过这个值会触发cm告警。 **取值范围**: 整型,\[0, 100]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 90 ## disk\_check\_timeout **参数说明**: 磁盘读写检测超时时间。 **取值范围**: 整型,\[0, 2147483647],单位:毫秒。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 2000 ## disk\_check\_interval **参数说明**: 磁盘读写检测周期。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1 ## enable\_xalarm\_event\_check **参数说明**: 是否订阅SysSentry告警事件。 **取值范围**: 布尔型。修改后重启生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示订阅SysSentry告警事件。 * off、no、false、0:表示不订阅SysSentry告警事件。 **默认值**: off ## xalarm\_node\_map **参数说明**: 标识节点与服务器cna的对应关系。告警检测相关参数,依赖开启参数enable\_xalarm\_event\_check。 **取值范围**: 字符串,格式同nodeid1:cna1;nodeid2:cna2。修改后重启生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: '' > 配置样例:3节点环境,cna值分别为201、202、203,参数设置为1:201;2:202;3:203。 --- --- url: /en/docs/latest/tool_and_commandreference/cm_ctl.md --- # cm\_ctl **cm\_ctl** is a tool provided by openGauss to control database instance services. This tool is called by O\&M personnel for automatic database instance service restoration. cm\_ctl provides the following functions: * Starts database instance services, all the instances in an AZ, all instances on a single host, or a single instance process. * Stops database instance services, all instances in an AZ, all instances on a single host, or instance processes on a single node. * Restarts the logical database instance service. * Queries the database instance status or the status of a single host. * Switches over the primary and standby instances or resets the instance status. * Rebuilds the standby node. * Views the database instance configuration file. * Sets the log level, the arbitration mode of cm\_server when one primary and multiple standby database instances are deployed, and the switchover mode between AZs. * Obtains the log level, the arbitration mode of cm\_server when one primary and multiple standby database instances are deployed, and the switchover mode between AZs. * Checks the status of an instance process. Files related to the cm\_ctl tool: * cluster\_manual\_start This is a flag file for starting and stopping a database instance. The file is stored in *$GAUSSHOME/bin*, where *GAUSSHOME* is an environment variable. When the database instance is started, the **cm\_ctl** tool deletes the file. When the database instance is stopped, the **cm\_ctl** tool generates the file and writes the stop mode to the file. * instance\_manual\_start\_X (X indicates the instance ID.) This is a flag file of starting and stopping a single instance. The file is stored in *$GAUSSHOME/bin*, where *GAUSSHOME* is an environment variable. When starting the instance, **cm\_ctl** deletes the file. When stopping the instance, **cm\_ctl** generates the file and writes the stop mode to the file. cm\_ctl constraints: * In cluster mode, the **cm\_ctl** tool instead of the **gs\_ctl** tool is used to switch the database role. ## Command Description cm\_ctl uses the following options: * [Commands of options](#en-us_topic_0116784021_table1718281376) * [Common options](#en-us_topic_0116784021_t73f4b6dad11943ea811a211e6c127669) * [Options of start](#table45722029132319) * [Options of switchover](#table12226155814102) * [Options of build](#table649003761312) * [Options of check](#en-us_topic_0116784021_t5582631c9b25449da85855fab919ddfd) * [Options of stop](#en-us_topic_0116784021_t7507cabe697c4b4da00814fccee8e559) * [Options of query](#en-us_topic_0116784021_t19badc48929f4f9abd94b8ac774f06c1) * [Options of view](#en-us_topic_0116784021_table207722104617) * [Options of set](#en-us_topic_0116784021_tef5e0858a71c4d21abce8f80e3ba7723) and [Options of set cm](#table10437204416514) * [Options of get](#table1599151916313) * [Options of setrunmode](#table1656519521713) * [Options of changerole](#table326418392182) * [Options of changemember](#table27311655104911) * [Options of reload](#table11377594818) * [Options of list](#table0914920191018) * [Options of encrypt](#table4739105911382) * [Options of ddb](#table9665145942617) * [Options of switch](#table7591811163812) * [Options of res](#table11658339114119) Usage: ``` cm_ctl start [-z AVAILABILITY_ZONE [--cm_arbitration_mode=ARBITRATION_MODE]] | [-n NODEID [-D DATADIR]] [-t SECS] cm_ctl switchover [-z AVAILABILITY_ZONE] | [-n NODEID -D DATADIR [-f]] | [-a] | [-A] [-t SECS] cm_ctl finishredo cm_ctl build [-c] [-n NODEID] [-D DATADIR [-t SECS] [-f] [-b full] [-j NUM]] cm_ctl check -B BINNAME -T DATAPATH cm_ctl stop [[-z AVAILABILITY_ZONE] | [-n NODEID [-D DATADIR]]] [-t SECS] [-m SHUTDOWN-MODE] cm_ctl query [-z ALL] [-l FILENAME] [-v [-C [-w] [-s] [-S] [-d] [-i] [-F] [-x] [-p]] | [-r]] [-t SECS] [--minorityAz=AZ_NAME] cm_ctl view [-v | -N | -n NODEID] [-l FILENAME] cm_ctl set [--log_level=LOG_LEVEL] [--cm_arbitration_mode=ARBITRATION_MODE] [--cm_switchover_az_mode=SWITCHOVER_AZ_MODE] [--cmsPromoteMode=CMS_PROMOTE_MODE -I INSTANCEID] cm_ctl set --param --agent | --server [-n [NODEID]] -k [PARAMETER]="[value]" cm_ctl get [--log_level] [--cm_arbitration_mode] [--cm_switchover_az_mode] cm_ctl setrunmode -n NODEID -D DATADIR [[--xmode=normal] | [--xmode=minority --votenum=NUM]] cm_ctl changerole [--role=PASSIVE | --role=FOLLOWER] -n NODEID -D DATADIR [-t SECS] cm_ctl changemember [--role=PASSIVE | --role=FOLLOWER] [--group=xx] [--priority=xx] -n NODEID -D DATADIR [-t SECS] cm_ctl reload --param [--agent | --server] cm_ctl list --param --agent | --server cm_ctl encrypt [-M MODE] -D DATADIR cm_ctl ddb DCC_CMD cm_ctl switch [--ddb_type=[DDB]] [--commit] [--rollback] ``` **Table 1** Commands of options **Table 2** Common options > \[!NOTE]NOTE > > * The common options listed here may not be applicable to all commands. For details about how to use the common options, see the preceding description. You can also run the **cm\_ctl --help** command to query the common options. **Table 3** Options of switchover **Table 4** Options of build **Table 5** Options of check **Table 6** Options of stop **Table 7** Options of query **Table 8** Options of set **Table 9** Options of set cm **Table 10** Options of get **Table 11** Options of view **Table 12** Options of setrunmode **Table 13** Options of changerole **Table 14** Options of changemember **Table 15** Options of start **Table 16** Options of reload **Table 17** Options of list **Table 18** Options of encrypt **Table 19** Options of switch **Table 20** Options of ddb **Table 21** Options of res ## Command Reference * Start an instance. ``` cm_ctl start [-z AVAILABILITY_ZONE [--cm_arbitration_mode=ARBITRATION_MODE]] | [-n NODEID [-D DATADIR]] [-t SECS] ``` * Perform a switchover between primary and standby databases. ``` cm_ctl switchover [-z AVAILABILITY_ZONE] | [-n NODEID -D DATADIR [-f]] | [-a] | [-A] [-t SECS] ``` * Stop the playback on all standby nodes, and forcibly promote one of the shards to primary. ``` cm_ctl finishredo ``` * Rebuild the standby node. ``` cm_ctl build -n NODEID -D DATADIR [-t SECS] [-f] [-b full] ``` * Check the running status of an instance process. ``` cm_ctl check -B BINNAME -T DATAPATH ``` * Stop an instance. ``` cm_ctl stop [[-z AVAILABILITY_ZONE] | [-n NODEID [-D DATADIR [-R]]]] [-t SECS] [-m SHUTDOWN-MODE] ``` * Query the cluster status. ``` cm_ctl query [-z ALL] [-l FILENAME] [-v [-C [-s] [-S] [-d] [-i] [-F] [-x] [-p]] | [-r]] [-t SECS] [--minorityAz=AZ_NAME] ``` * View the cluster configuration file. ``` cm_ctl view [-v | -N | -n NODEID] [-l FILENAME] ``` * Set parameters. ``` cm_ctl set [--log_level=LOG_LEVEL] [--cm_arbitration_mode=ARBITRATION_MODE] [--cm_switchover_az_mode=SWITCHOVER_AZ_MODE] ``` * Set CM parameters. ``` cm_ctl set --param --agent | --server [-n NODEID] -k "PARAMETER='value'" ``` * Obtain parameters. ``` cm_ctl get [--log_level] [--cm_arbitration_mode] [--cm_switchover_az_mode] ``` * Set the number of DCF votes. ``` cm_ctl setrunmode -n NODEID -D DATADIR [[--xmode=normal] | [--xmode=minority --votenum=NUM]] ``` * Change the DCF role information. ``` cm_ctl changerole [--role=PASSIVE | --role=FOLLOWER] -n NODEID -D DATADIR [-t SECS] ``` * Change the attributes of the DCF node. ``` cm_ctl changemember [--role=PASSIVE | --role=FOLLOWER] [--group=xx] [--priority=xx] -n NODEID -D DATADIR [-t SECS] ``` * Dynamically load CM parameters. ``` cm_ctl reload --param [--agent | --server] ``` * List all CM parameters. ``` cm_ctl list --param [--agent | --server] ``` * Perform encryption. ``` cm_ctl encrypt [-M MODE] -D DATADIR ``` * Run the DCC command. ``` cm_ctl ddb DCC_CMD Set: cm\_ctl ddb --put [key] [value] Delete: cm\_ctl ddb --delete [key] View DCC command help information: cm\_ctl ddb --help ``` * Run the **switch ddb** command. ``` cm_ctl switch [--ddb_type=[DDB]] [--commit] [--rollback] ``` * Run the **res** command. ``` Add a resource: cm_ctl res --add --res_name=[name] --res_attr=[res_info] Delete a resource: cm_ctl res --del --res_name=[name] Modify a resource: cm_ctl res --edit --res_name=[name] --res_attr=[res_info] Add a resource instance: cm_ctl res --edit --res_name=[name] --add_inst=[inst_info] Delete a resource instance: cm_ctl res --edit --res_name=[name] --del_inst=[inst_info] Check resources: cm_ctl res --check ``` --- --- url: /zh/docs/latest/database_om_guide/cm_ctl_stop_cluster_failure.md --- # cm\_ctl stop集群失败 ## 现象 cm\_ctl stop集群失败,利用ssh命令检查互信,发现无法连通。 ## 原因 数据库互信掉了。/etc/hosts文件中互信记录被删除。 ## 解决方案 修改/etc/hosts文件,按下图方法将记录添加回来。 ![Alt text](image-6.png) --- --- url: /zh/docs/latest/tool_and_commandreference/cm_ctl.md --- # cm\_ctl工具介绍 cm\_ctl是openGauss提供的用来控制数据库实例服务的工具。该工具主要供OM调用,及数据库实例服务自恢复时使用。cm\_ctl的主要功能有: * 启动数据库实例服务、AZ的所有实例、单个主机上的所有实例或单独启动某个实例进程。 * 停止数据库实例服务、AZ的所有实例、单个主机上的所有实例或单独停止某个节点实例进程。 * 重启逻辑数据库实例服务。 * 查询数据库实例状态或者单个主机的状态。 * 切换主备实例或重置实例状态。 * 重建备机。 * 查看数据库实例配置文件。 * 设置日志级别,一主多备数据库实例部署下cm\_server的仲裁模式、AZ之间的切换模式。 * 获取日志级别,一主多备数据库实例部署下cm\_server的仲裁模式、AZ之间的切换模式。 * 检测实例进程状态。 与cm\_ctl工具相关的文件: * cluster\_manual\_start 该文件是数据库实例启停标志文件。文件位于\_$GAUSSHOME/bin\_下。其中,GAUSSHOME为环境变量。启动数据库实例时,cm\_ctl会删除该文件;停止数据库实例时,cm\_ctl会生成该文件,并向文件写入停止模式。 * instance\_manual\_start\_X(X是实例编号) 该文件是单个实例启停标志文件。文件位于\_$GAUSSHOME/bin\_下。其中,GAUSSHOME为环境变量。启动实例时,cm\_ctl会删除该文件;停止实例时,cm\_ctl会生成该文件,并向文件写入停止模式。 cm\_ctl的相关约束: * 在安装CM的集群环境下,使用cm\_ctl集群工具来切换数据库角色,而不是gs\_ctl或gs\_om工具。 * 在安装CM的集群环境下,如果要执行的操作没有对应的cm\_ctl命令,可以通过以下流程实现:通过cm\_uninstall工具卸载cm,手动修改完成对应操作,通过cm\_install工具安装重新安装cm。 ## 命令说明 cm\_ctl参数可分为如下几类: * option参数,详细请参见 [表 option参数](#zh-cn_topic_0116784021_table1718281376)。 * 公共参数,详细请参见 [表 公共参数](#zh-cn_topic_0116784021_t73f4b6dad11943ea811a211e6c127669)。 * start模式的参数,详细参见 [表 start参数](#table45722029132319)。 * switchover模式的参数,详细请参见 [表 switchover参数](#table12226155814102)。 * build模式的参数,详细请参见 [表 build参数](#table649003761312)。 * check模式的参数,详细请参见 [表 check参数](#zh-cn_topic_0116784021_t5582631c9b25449da85855fab919ddfd)。 * stop模式的参数,详细请参见 [表 stop参数](#zh-cn_topic_0116784021_t7507cabe697c4b4da00814fccee8e559)。 * query模式的参数,详细请参见 [表 query参数](#zh-cn_topic_0116784021_t19badc48929f4f9abd94b8ac774f06c1)。 * view模式的参数,详细请参见 [表 view参数](#zh-cn_topic_0116784021_table207722104617)。 * set模式的参数,详细请参见 [表 set参数](#zh-cn_topic_0116784021_tef5e0858a71c4d21abce8f80e3ba7723) [表 set cm参数](#table10437204416514)。 * get模式的参数,详情请参见 [表 get参数](#table1599151916313)。 * setrunmode模式的参数,详细请参见 [表 setrunmode参数](#table1656519521713)。 * changerole模式的参数,详细请参见 [表 changerole参数](#table326418392182)。 * changemember功能的参数,详细请参见 [表 changemember参数](#table27311655104911)。 * reload模式的参数,详细请参见 [表 reload 参数](#table11377594818)。 * list模式的参数,详细请参见 [表 list参数](#table0914920191018)。 * encrypt模式的参数,详细请参见 [表 encrypt参数](#table4739105911382)。 * ddb模式的参数,详细请参见 [表 ddb参数](#table9665145942617)。 * switch模式的参数,详细请参见 [表 switch参数](#table7591811163812)。 * res模式的参数,详细请参见 [表 res参数](#table11658339114119)。 使用方法: ``` cm_ctl start [-z AVAILABILITY_ZONE [--cm_arbitration_mode=ARBITRATION_MODE]] | [-n NODEID [-D DATADIR]] [-t SECS] cm_ctl switchover [-z AVAILABILITY_ZONE] | [-n NODEID -D DATADIR [-f]] | [-a] | [-A] [-t SECS] cm_ctl finishredo cm_ctl build [-c] [-n NODEID] [-D DATADIR [-t SECS] [-f] [-b full] [-j NUM]] cm_ctl check -B BINNAME -T DATAPATH cm_ctl stop [[-z AVAILABILITY_ZONE] | [-n NODEID [-D DATADIR]]] [-t SECS] [-m SHUTDOWN-MODE] cm_ctl query [-z ALL] [-l FILENAME] [-v [-C [-w] [-s] [-S] [-d] [-i] [-F] [-x] [-p]] | [-r]] [-t SECS] [- O] [--minorityAz=AZ_NAME] cm_ctl view [-v | -N | -n NODEID] [-l FILENAME] cm_ctl set [--log_level=LOG_LEVEL] [--cm_arbitration_mode=ARBITRATION_MODE] [--cm_switchover_az_mode=SWITCHOVER_AZ_MODE] [--cmsPromoteMode=CMS_PROMOTE_MODE -I INSTANCEID] cm_ctl set --param --agent | --server [-n [NODEID]] -k [PARAMETER]="[value]" cm_ctl get [--log_level] [--cm_arbitration_mode] [--cm_switchover_az_mode] cm_ctl setrunmode -n NODEID -D DATADIR [[--xmode=normal] | [--xmode=minority --votenum=NUM]] cm_ctl changerole [--role=PASSIVE | --role=FOLLOWER] -n NODEID -D DATADIR [-t SECS] cm_ctl changemember [--role=PASSIVE | --role=FOLLOWER] [--group=xx] [--priority=xx] -n NODEID -D DATADIR [-t SECS] cm_ctl reload --param [--agent | --server] cm_ctl list --param --agent | --server cm_ctl encrypt [-M MODE] -D DATADIR cm_ctl ddb DCC_CMD cm_ctl switch [--ddb_type=[DDB]] [--commit] [--rollback] ``` **表 1** option参数 **表 2** 公共参数 \[!NOTE]说明 此处列出的公共参数并不一定适用于所有命令,而是多个命令支持,为避免冗余信息,所以统一在此说明,详细的使用方法见以上使用方法,也可以使用cm\_ctl --help进行查询。 **表 3** switchover参数 **表 4** build参数 **表 5** check参数 **表 6** stop参数 **表 7** query参数 **表 8** set参数 **表 9** set cm参数 **表 10** get参数 **表 11** view参数 **表 12** setrunmode参数 **表 13** changerole参数 **表 14** changemember参数 **表 15** start参数 **表 16** reload 参数 **表 17** list参数 **表 18** encrypt参数 **表 19** switch参数 **表 20** ddb参数 **表 21** res参数 > \[!WARNING]注意 > > * 在部署有CM工具的情况下,对于某些既可以直接调用内核工具,也可以调用CM工具进行执行的命令,如:switchover、build等,请优先使用CM工具,因为如果直接调用内核工具,有可能CM感知不到用户正在手动执行指令,进而误判集群状态异常。 > * CM有进程保活功能,并且会实时监控集群状态并进行自动故障处理,如果运维人员需要手动处理集群状态或进行问题调试定位等,最好执行cm\_ctl pause命令将CM服务暂停掉,否则可能会干扰运维操作,待运维操作完成后可以执行cm\_ctl resume命令恢复CM服务。 ## 命令参考 * 启动实例: ``` cm_ctl start [-z AVAILABILITY_ZONE [--cm_arbitration_mode=ARBITRATION_MODE]] | [-n NODEID [-D DATADIR]] [-t SECS] ``` * 数据库主备倒换: ``` cm_ctl switchover [-z AVAILABILITY_ZONE] | [-n NODEID -D DATADIR [-f]] | [-a] | [-A] [-t SECS] ``` * 所有备机停止回放,每个分片中选择一个强制升主: ``` cm_ctl finishredo ``` * 重建备节点: ``` cm_ctl build -n NODEID -D DATADIR [-t SECS] [-f] [-b full] ``` * 检测实例进程运行状态: ``` cm_ctl check -B BINNAME -T DATAPATH ``` * 停止实例: ``` cm_ctl stop [[-z AVAILABILITY_ZONE] | [-n NODEID [-D DATADIR [-R]]]] [-t SECS] [-m SHUTDOWN-MODE] ``` * 查询集群状态: ``` cm_ctl query [-z ALL] [-l FILENAME] [-v [-C [-s] [-S] [-d] [-i] [-F] [-x] [-p]] | [-r]] [-t SECS] [--minorityAz=AZ_NAME] ``` * 查看集群配置文件: ``` cm_ctl view [-v | -N | -n NODEID] [-l FILENAME] ``` * 设置参数: ``` cm_ctl set [--log_level=LOG_LEVEL] [--cm_arbitration_mode=ARBITRATION_MODE] [--cm_switchover_az_mode=SWITCHOVER_AZ_MODE] ``` * 设置CM参数: ``` cm_ctl set --param --agent | --server [-n NODEID] -k PARAMETER="'value'" ``` * 获取参数: ``` cm_ctl get [--log_level] [--cm_arbitration_mode] [--cm_switchover_az_mode] ``` * 设置DCF投票数: ``` cm_ctl setrunmode -n NODEID -D DATADIR [[--xmode=normal] | [--xmode=minority --votenum=NUM]] ``` * 改变dcf角色信息: ``` cm_ctl changerole [--role=PASSIVE | --role=FOLLOWER] -n NODEID -D DATADIR [-t SECS] ``` * 改变dcf节点属性: ``` cm_ctl changemember [--role=PASSIVE | --role=FOLLOWER] [--group=xx] [--priority=xx] -n NODEID -D DATADIR [-t SECS] ``` * 动态加载CM参数: ``` cm_ctl reload --param [--agent | --server] ``` * 列出所有CM参数: ``` cm_ctl list --param [--agent | --server] ``` * 加密: ``` cm_ctl encrypt [-M MODE] -D DATADIR ``` * 执行DDB命令行: ``` cm_ctl ddb DDB_CMD 设置:cm_ctl ddb --put [key] [value] 删除:cm_ctl ddb --delete [key] 查看DDB命令帮助信息:cm_ctl ddb --help ``` * 执行switch ddb命令: ``` cm_ctl switch [--ddb_type=[DDB]] [--commit] [--rollback] ``` * 执行res命令: ``` 新增资源:cm_ctl res --add --res_name=[name] --res_attr=[res_info] 删除资源:cm_ctl res --del --res_name=[name] 修改资源:cm_ctl res --edit --res_name=[name] --res_attr=[res_info] 新增资源实例:cm_ctl res --edit --res_name=[name] --add_inst=[inst_info] 删除资源实例:cm_ctl res --edit --res_name=[name] --del_inst=[inst_info] 检查资源:cm_ctl res --check ``` --- --- url: /en/docs/latest/tool_and_commandreference/cm_install_and_cm_uninstall.md --- # cm\_install and cm\_uninstall The cm\_install tool can be used to deploy CMs in the openGauss database cluster. The cm\_uninstall tool can be used to uninstall CMs from the openGauss database cluster without affecting the DN cluster. ## Precautions * After cm\_install is executed, the cluster is started by default. * This tool must be used as an individual user. * This tool allows you to install or uninstall the CM tool when the cluster is stopped. Note that the primary node before the cluster is stopped must be the initial primary node configured in the XML file. Otherwise, after the CM tool is installed or uninstalled and started again, the host of the cluster is different from that before the cluster is stopped. * If the CM tool is uninstalled when the cluster is stopped, dynamic files will be deleted after the uninstallation. However, dynamic files cannot be generated because the cluster is stopped. If necessary, run the **gs\_om -t refreshconf** command to generate dynamic files after the cluster is started using gs\_om. * Before using this tool, go to the **cm\_tool** directory where this tool is located. * If after executing cm\_install, the term value of the host is checked to be 0, in order to ensure normal operation of subsequent services, the user needs to follow the prompt and execute **cm\_ctl stop && cm\_ctl start** to restart the service. ## Prerequisites * The OM tool is required for installing the openGauss cluster. * Generally, the cluster installed using the OM tool can ensure that mutual trust exists between nodes in the cluster. * The version of the openGauss cluster to be installed is the same as that of the CM to be installed. * Before CM deployment, the cluster status must be normal or stopped, and the term value of the host must be a non-zero value and the largest value in the cluster. * Before using this command, you need to run the source command to set environment variables. ## Usage Installation ``` cm_install -? | --help cm_install -X XMLFILE [-e envFile] --cmpkg=cmpkgPath ``` Uninstallation ``` cm_uninstall -? | --help cm_uninstall -X XMLFILE [-e envFile] [--deleteData] [--deleteBinary] ``` **Description:** * -X Specifies the path of the XML file. * -e Specifies the path of the environment variable file. The default value is **~/.bashrc**. * \--cmpkg Specifies the path of the CM package. * \--deleteData Deletes the CM data directory. By default, the CM data directory is not deleted. * \--deleteBinary Delete CM-related binary files, including om\_monitor, cm\_agent, cm\_server, and cm\_ctl. By default, the binary files are not deleted. * -?, --help Displays help information. --- --- url: /en/docs/latest/tool_and_commandreference/cm_persist.md --- # cm\_persist ## Function The cm\_persist tool is used to preempt the disk lock on the shared storage device. This tool is an internal tool automatically invoked by CM Server. You are not advised to use it. ## Prerequisites * The storage device supports the SCSI-3 and CAW protocols. * The cm\_persist tool has the CAP\_SYS\_RAWIO permission. Otherwise, the cm\_persist tool cannot invoke the ioctl system function to operate the shared storage device. ## Syntax * Run the **cm\_persist** command. ``` cm_persist [DEVICEPATH] [INSTANCE_ID] [OFFSET] ``` * Display the help information. ``` cm_persist -? | --help ``` ## Parameter Description * DEVICEPATH Specifies the path to the shared storage device. * INSTANCE\_ID Specifies the ID of the CM Server instance. You can run the **cm\_ctl query -Cv** command to query the ID. * OFFSET Preempts the disk lock at the specified disk offset address. * -?,--help Prints help information. --- --- url: /zh/docs/latest/tool_and_commandreference/cm_persist.md --- # cm\_persist工具介绍 ## 功能介绍 cm\_persist工具用来在资源池化设备上实现抢占磁盘锁功能。该工具是系统内部工具,由cm\_server实例自动调用,不建议用户使用。 ## 前提条件 * 确保存储设备支持SCSI-3及CAW协议。 * 确保cm\_persist工具拥有CAP\_SYS\_RAWIO权限,拥有该权限后才可以调用ioctl系统函数操作资源池化设备。 ## 语法 * 执行cm\_persist命令 ``` cm_persist [DEVICEPATH] [INSTANCE_ID] [OFFSET] ``` * 显示帮助信息 ``` cm_persist -? | --help ``` ## 参数说明 * DEVICEPATH 资源池化设备的路径。 * INSTANCE\_ID cm\_server实例的instance id,可通过cm\_ctl query -Cv命令查询获取。 * OFFSET 在指定的磁盘偏移地址上抢占磁盘锁。 * -?,--help 打印帮助信息。 --- --- url: /zh/docs/latest/tool_and_commandreference/parameters_related_to_cm_server.md --- # cm\_server参数 ## log\_dir **参数说明**: log\_dir决定存放cm\_server日志文件的目录。 它可以是绝对路径,或者是相对路径(相对于$GAUSSLOG的路径)。通过cm\_ctl设置绝对路径时需要将路径用''把路径包含起来,例如:cm\_ctl set --param --server -k log\_dir="'/log/dir'"。 **取值范围**: 字符串,最大长度为1024。修改后需要重启cm\_server才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: “log”,表示在$GAUSSLOG下对应的cm目录下生成cm\_server日志。 ## log\_file\_size **参数说明**: 控制日志文件的大小。当'cm\_server-xx-current.log'日志文件达到指定大小时,则重新创建一个日志文件记录日志信息。 **取值范围**: 整型,\[0, 2047],实际生效范围\[1, 2047],单位:MB。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 16MB ## log\_min\_messages **参数说明**: 控制写到cm\_server日志文件中的消息级别。每个级别都包含排在它后面的所有级别中的信息。级别越低,服务器运行日志中记录的消息就越少。 **取值范围**: 枚举类型,有效值有debug5、debug1、log、warning、error、fatal(不区分大小写)。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: warning ## thread\_count **参数说明**: cm\_server线程池的线程数。 **取值范围**: 整型,\[2, 1000]。修改后需要重启cm\_server才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1000 ## instance\_heartbeat\_timeout **参数说明**: 实例心跳超时时间。 **取值范围**: 整型,\[1, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 6 ## instance\_failover\_delay\_timeout **参数说明**: cm\_server检测到主机宕机,failover备机的延迟时间。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 0 ## cmserver\_ha\_connect\_timeout **参数说明**: cm\_server主备连接超时时间。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 2 ## cmserver\_ha\_heartbeat\_timeout **参数说明**: cm\_server主备心跳超时时间。 **取值范围**: 整型,\[1, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 6 ## cmserver\_ha\_status\_interval **参数说明**: cm\_server主备同步状态信息间隔时间。 **取值范围**: 整型,\[1, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1 ## cmserver\_self\_vote\_timeout **参数说明**: cm\_server之间相互投票的超时时间。旧版本遗留参数,实际不生效。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值:6** ## phony\_dead\_effective\_time **参数说明**: 用于数据库节点僵死检测,当检测到的僵死次数大于该参数值,认为进程僵死,将进程重启。 **取值范围**: 整型,\[1, 2147483647],单位:次数。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 5 ## cm\_server\_arbitrate\_delay\_base\_time\_out **参数说明**: cm\_server仲裁延迟基础时长。cm\_server主断连后,仲裁启动计时开始,经过仲裁延迟时长后,将选出新的cm\_server主。其中仲裁延迟时长由仲裁延迟基础时长、节点index(server ID序号)和增量时长共同决定。公式为:仲裁延迟时长=仲裁延迟基础时长+节点index\*仲裁延迟增量时长参数。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 10 ## cm\_server\_arbitrate\_delay\_incremental\_time\_out **参数说明**: cm\_server仲裁延迟增量时长。cm\_server主断连后,仲裁启动计时开始,经过仲裁延迟时长后,将选出新的cm\_server主。其中仲裁延迟时长由仲裁延迟基础时长、节点index(server ID序号)和增量时长共同决定。公式为:仲裁延迟时长=仲裁延迟基础时长+节点index\*仲裁延迟增量时长参数。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 3 ## alarm\_component **参数说明**: 在使用第一种告警方式时,设置用于处理告警内容的告警组件的位置。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。通过cm\_ctl设置绝对路径时需要将路径用''把路径包含起来,例如:cm\_ctl set --param --server -k alarm\_component="'/alarm/dir'"。 **取值范围**: 字符串,最大长度为1024。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: /opt/huawei/snas/bin/snas\_cm\_cmd ## alarm\_report\_interval **参数说明**: 指定告警上报的时间间隔。 **取值范围**: 非负整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 3 ## alarm\_report\_max\_count **参数说明**: 指定告警上报的最大次数。 **取值范围**: 非负整型,\[1, 2592000]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1 ## instance\_keep\_heartbeat\_timeout **参数说明**: cm\_agent会定期检测实例状态并上报给cm\_server,若实例状态长时间无法成功检测,累积次数超出该数值,则cm\_server将下发命令给agent重启该实例。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 40 ## az\_switchover\_threshold **参数说明**: 若一个AZ内节点分片的故障率(故障的节点分片数 / 总节点分片数 \* 100%)超过该数值,则会触发AZ自动切换。 **取值范围**: 整型,\[1, 100]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 100 ## az\_check\_and\_arbitrate\_interval **参数说明**: 当某个AZ状态不正常时,会触发AZ自动切换,该参数是检测AZ状态的时间间隔。 **取值范围**: 整型,\[1, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 2 ## az\_connect\_check\_interval **参数说明**: 定时检测AZ间的网络连接,该参数表示连续两次检测之间的间隔时间。 **取值范围**: 整型,\[1, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 60 ## az\_connect\_check\_delay\_time **参数说明**: 每次检测AZ间的网络连接时有多次重试,该参数表示两次重试之间的延迟时间。 **取值范围**: 整型,\[1, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 150 ## cmserver\_demote\_delay\_on\_etcd\_fault **参数说明**: 因为etcd不健康而导致cm\_server从主降为备的时间间隔。 **取值范围**: 整型,\[1, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 8 ## instance\_phony\_dead\_restart\_interval **参数说明**: 当数据库实例僵死时,会被cm\_agent重启,相同的实例连续因僵死被杀时,其间隔时间不能小于该参数数值,否则cm\_agent不会下发命令。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 21600 ## enable\_transaction\_read\_only **参数说明**: 控制数据库是否为只读模式开关。 **取值范围**: 布尔型,有效值有on,off,true,false,yes,no,1,0。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: on ## datastorage\_threshold\_check\_interval **参数说明**:检测磁盘占用的时间间隔。间隔时间由用户指定,表示检测一次磁盘的间隔时间。 **取值范围**:整型,\[1, 2592000],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:10 ## datastorage\_threshold\_value\_check **参数说明**: 设置数据库只读模式的磁盘占用阈值,当某个节点的数据目录或其下软连接(主要针对base、global、pg\_xlog、pg\_tblspc及以下表空间)对应真实目录所在磁盘占用阈值超过这个阈值,如果该节点为备机,自动将该节点设置为只读,如果该节点为主机,则会自动将主机切换到一个合适的主机上。如果所有节点的阈值均达到阈值,则会将集群设置为只读。在资源池化下,主节点超过阈值,不会切换主节点。 **取值范围**: 整型,\[1, 99]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 85 ## ss\_enable\_check\_sys\_disk\_usage **参数说明**: 设置在资源池化下,是否检测数据库的数据目录所在磁盘(非共享存储盘)超过阈值。 **取值范围**: 非负整型,0或1,0:开关关闭,1:开关打开。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 0 ## max\_datastorage\_threshold\_check **参数说明**: 设置磁盘使用率的最大检测间隔时间。当用户手动修改只读模式参数后,会自动在指定间隔时间后开启磁盘检测操作。 **取值范围**: 整型,\[1, 2592000],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 43200 ## enable\_az\_auto\_switchover **参数说明**: AZ自动切换开关,若打开,则表示允许cm\_server自动切换AZ。否则当发生节点故障等情况时,即使当前AZ已经不再可用,也不会自动切换到其他AZ上,除非手动执行切换命令。 **取值范围**: 非负整型,0或1,0:开关关闭,1:开关打开。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 1 ## cm\_krb\_server\_keyfile **参数说明**: kerberos服务端key文件所在位置,需要配置为绝对路径。该文件通常为${GAUSSHOME}/kerberos路径下,以keytab格式结尾,文件名与集群运行所在用户名相同。与上述cm\_auth\_method参数是配对的,当cm\_auth\_method参数修改为gss时,该参数也必须配置为正确路径,否则将影响集群状态。通过cm\_ctl设置绝对路径时需要将路径用''把路径包含起来,例如:cm\_ctl set --param --server -k cm\_krb\_server\_keyfile="'/krb/dir'"。 **取值范围**: 字符串类型,修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: ${GAUSSHOME}/kerberos/{UserName}.keytab,默认值无法生效,仅作为提示。 ## switch\_rto **参数说明**: cm\_server强启逻辑等待时延。在force\_promote被置为1时,当集群的某一分片处于无主状态开始计时,等待该延迟时间后开始执行强启逻辑。 **取值范围**: 整型,\[60, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 600 ## force\_promote **参数说明**: cm\_server是否打开强启逻辑(指集群状态为Unknown的时候以丢失部分数据为代价保证集群基本功能可用)的开关。0代表功能关闭,1代表功能开启。 **取值范围**: 整型,\[0, 1]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 0 ## backup\_open **参数说明**:灾备集群设置,开启后CM按照灾备集群模式运行。 **取值范围**:整型,\[0, 1]。修改后需要重启cm\_server才能生效。非灾备集群不能开启该参数。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * 0表示关闭。 * 1表示开启 **默认值**:0 ## enable\_dcf **参数说明**:DCF模式开关。 **取值范围**:布尔型。修改后需要重启cm\_server才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示启用dcf。 * off、no、false、0:表示不启用dcf。 **默认值**:off ## ddb\_type **参数说明**:ETCD,DCC、share disk模式切换开关。 **取值范围**:整型。0:ETCD;1:DCC;2:share disk。修改后需要重启cm\_server才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:1 > \[!NOTE]说明 > (openGauss只支持DCC或者share disk模式)。 ## enable\_ssl **参数说明**:ssl证书开关。 **取值范围**:布尔型。打开后使用ssl证书加密通信。修改后需要重启cm\_server才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示启用ssl。 * off、no、false、0:表示不启用ssl。 * **默认值**:on > \[!TIP]须知 > 出于安全性考虑,建议不要关闭该配置。关闭后cm将**不使用**加密通信,所有信息明文传播,可能带来窃听、篡改、冒充等安全风险。 ## ssl\_cert\_expire\_alert\_threshold **参数说明**:ssl证书过期告警时间。 **取值范围**:整型,\[7, 180],单位:天。证书过期时间少于该时间时,上报证书即将过期告警。修改后需要重启cm\_server才能生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:90 ## ssl\_cert\_expire\_check\_interval **参数说明**:ssl证书过期检测周期。 **取值范围**:整型,\[0, 2147483647],单位:秒。修改后需要重启cm\_server才能生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:86400 ## ddb\_log\_level **参数说明**:设置ddb日志级别。 关闭日志:“NONE”,NONE表示关闭日志打印,不能与以下日志级别混合使用。 开启日志:“RUN\_ERR|RUN\_WAR|RUN\_INF|DEBUG\_ERR|DEBUG\_WAR|DEBUG\_INF|TRACE|PROFILE|OPER”日志级别可以从上述字符串中选取字符串并使用竖线组合使用,不能配置空串。 **取值范围**:字符串,RUN\_ERR|RUN\_WAR|RUN\_INF|DEBUG\_ERR|DEBUG\_WAR|DEBUG\_INF|TRACE|PROFILE|OPER。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:RUN\_ERR|RUN\_WAR|DEBUG\_ERR|OPER|RUN\_INF|PROFILE ## ddb\_log\_backup\_file\_count **参数说明**:最大保存日志文件个数。 **取值范围**:整型,\[1, 100]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:10 ## ddb\_max\_log\_file\_size **参数说明**:单条日志最大字节数。 **取值范围**:字符串,长度最大为1024,\[1M, 1000M]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:10M ## ddb\_log\_suppress\_enable **参数说明**:是否开启日志抑制功能。 **取值范围**:整型,0:关闭; 1:开启。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:1 ## ddb\_election\_timeout **参数说明**:DCC 选举超时时间。 **取值范围**:整型,\[1, 600], 单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:3 ## coordinator\_heartbeat\_timeout **参数说明**: 节点故障自动剔除心跳超时时间。设置后立即生效,不需要重启cm\_server。该参数设置为0,则节点故障后不会自动剔除。 **取值范围**: 整型,单位为秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 25 ## cluster\_starting\_aribt\_delay **参数说明**: cm\_server在集群启动阶段,等待节点静态主升主的时间。 **取值范围**: 整型,\[1,2592000],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 180 ## enable\_e2e\_rto **参数说明**: 端到端RTO开关,开启后僵死检测周期及网络检测超时时间将缩短,CM可以达到端到端RTO指标(单实例故障RTO<=10s,叠加故障RTO<=30s)。 **取值范围**: 整型,\[0, 1]。1表示开启,0表示关闭。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 0 ## disk\_timeout **参数说明**: 磁盘心跳超时时间。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 200 ## agent\_network\_timeout **参数说明**:节点间网络超时时间。 **取值范围**: 整型,\[0, 2147483647],单位:秒。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 6 ## voting\_disk\_path **参数说明**: 投票盘路径。 **取值范围**: 字符串,最大长度为1024。修改后需要重启cm\_server才能生效。 **默认值**: 无,需要安装时进行配置。 ## share\_disk\_path **参数说明**: 共享盘路径。 **取值范围**: 字符串,最大长度为1024。修改后需要重启cm\_server才能生效。 **默认值**: 无,需要安装时进行配置。 ## dn\_arbitrate\_mode **参数说明**:dn仲裁模式。 **取值范围**:字符串。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置,share\_disk模式下,不建议用户修改仲裁模式。 * quorum * paxos * share\_disk **默认值**:quorum ## delay\_arbitrate\_max\_cluster\_timeout **参数说明**:启动过程中,延迟仲裁最大集群时间。 **取值范围**:整型,\[0, 1000],单位:秒。0:表示不进行仲裁。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:300 ## delay\_arbitrate\_timeout **参数说明**:设置等待跟主DN同AZ节点redo回放,优先选择同AZ升主的时间。 **取值范围**:整型,\[0, 2147483647],单位:秒。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:0 ## cm\_auth\_method **参数说明**: CM模块端口认证方式,trust表示未配置端口认证,gss表示采用kerberos端口认证。必须注意的是:只有当kerberos服务端和客户端成功安装后才能修改为gss,否则CM模块无法正常通信,将影响数据库状态。 **取值范围**: 枚举类型,有效值有trust, gss。修改后需要重启cm\_server才能生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: trust ## third\_party\_gateway\_ip **参数说明**: CM两节点部署模式必备参数。当前AZ中第三方网关IP地址或任何其他独立于当前集群的可用IP地址,需要确保其与集群中节点间的网络相通。 **取值范围**: 字符串。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 无,需要安装时进行配置。 ## cms\_enable\_failover\_on2nodes **参数说明**: CM两节点部署模式必备参数。是否允许CM集群自身故障自动切换,默认禁止CM集群自身自动故障切换。 **取值范围**: 布尔型。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示允许CM集群自身自动故障切换。 * off、no、false、0:表示禁止CM集群自身自动故障切换。 **默认值**: false ## cms\_enable\_db\_crash\_recovery **参数说明**: CM两节点部署模式必备参数。是否允许数据库集群脑裂自动故障恢复。为了确保数据库集群的数据一致性,默认不支持其自动故障恢复。 **取值范围**: 布尔型。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示允许DN集群脑裂自动故障恢复。 * off、no、false、0:表示禁止DN集群脑裂自动故障恢复。 **默认值**: false ## cms\_network\_isolation\_timeout **参数说明**: CM两节点部署模式必备参数。cm\_server检索ddb集群信息同步异常的最大连续检测次数,超过最大检测次数则认为发生网络分区故障。 **取值范围**:整型,单位:次。修改后需要重启cm\_server才能生效。 **默认值**: 20 ## wait\_static\_primary\_times **参数说明**: 主机异常挂掉之后,在选出新主之前等待旧主恢复的时间。在每一轮选主流程向选出的候选者下发failover命令之前判断当前已仲裁次数是否小于该参数,如果小于该参数则不下发failover命令,直接进入下一轮选主,继续等待旧主恢复,所以该参数的单位并不是秒。但是每一轮选主流程的耗时基本在1s左右,所以基本也可以认为等待旧主恢复的时间就是wait\_static\_primary\_times秒。 **取值范围**:整型,\[5, 2147483647],单位:次。修改后重载生效。 **默认值**: 6 ## ss\_double\_cluster\_mode **参数说明**: 资源池化主备双集群容灾场景下数据库集群的启动方式。 **取值范围**: 整型,\[0, 2]。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * 0表示非资源池化主备双集群容灾模式。 * 1表示以资源池化主集群模式启动。 * 2表示以资源池化备集群模式启动。 **默认值**: 0 ## share\_disk\_lock\_type **参数说明**: 资源池化集群共享盘锁类型。 **取值范围**: 整型,\[0, 1]。修改后需要重启cm\_server才能生效。 * 0表示共享盘锁类型为非SCSI/NOF协议锁。 * 1表示共享盘锁类型为SCSI/NOF协议锁。 **默认值**: 0 ## enable\_set\_most\_available\_sync **参数说明**: 是否允许CM管理数据库最大可用模式参数most\_available\_sync,默认禁止管理。 **取值范围**: 布尔型。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 * on、yes、true、1:表示允许CM管理最大可用模式参数。 * off、no、false、0:表示禁止CM管理最大可用模式参数。 **默认值**:off ## cmserver\_set\_most\_available\_sync\_delay\_time **参数说明**:当cm\_server检测到db主机因为同步备机数量不足被hang住时下发命令开启/关闭最大可用模式的延迟时间。 **取值范围**: 整型,\[0,10]。修改后可以reload生效。参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**:6 ## upgrade\_from **参数说明**: 升级过程中使用,用于标示升级前数据库的内部版本号,此参数禁止手动修改。 **取值范围**: 非负整型,\[0, 4294967295]。修改后可以reload生效,参数修改请参考[表 set cm参数](cm_ctl.md#table10437204416514)进行设置。 **默认值**: 0 --- --- url: >- /zh/docs/latest/ograc/fault_recovery_issues/issues_during_the_installation_phase/cms_installation_failed_missing_bashrcin.md --- # CMS 安装失败——残留用户家目录缺失 `.bashrc` 文件 #### 现象描述 在两节点部署 oGRAC 执行 `sh appctl.sh install config_params_lun.json` 时,安装流程在 **CMS 组件安装阶段** 中断,报错信息如下: ```text [EROR]cms install failed: CMS install failed:[Errno 2] No such file or directory:'/home/ograc/.bashrc' ``` 安装脚本自动终止,未生成完整的 oGRAC 二进制环境。 ![Missing bashrc](./Missingbashrc.png) #### 常见原因 此问题通常由 **历史安装残留未彻底清理** 导致,具体场景包括: 1. 上一次卸载 oGRAC 时,未使用 `userdel -r ograc` 彻底删除 `ograc` 用户及其家目录,仅手动删除了 `/opt/ograc` 等运行目录。 2. 残留的 `ograc` 用户家目录(`/home/ograc`)被保留,但目录内的 `.bashrc` 等环境配置文件已丢失或被误删。 3. 本次重新安装时,安装脚本检测到 `ograc` 用户已存在,未重新初始化家目录环境,导致 CMS 组件在配置用户环境变量时无法找到 `/home/ograc/.bashrc` 文件。 #### 排查与解决建议 1. **确认用户残留状态** 在两节点分别执行以下命令,检查 `ograc` 用户是否存在: ```bash id ograc ls -la /home/ograc/.bashrc ``` 若用户存在但 `.bashrc` 文件不存在,即可确认为本问题。 2. **彻底清理残留用户与环境** 在安装前,务必完全清除历史残留(需 `root` 用户执行): ```bash # 停止并卸载现有环境(若仍在运行) sh appctl.sh stop sh appctl.sh uninstall override # 彻底删除 ograc 用户及其家目录 userdel -r ograc # 确认无其他相关用户残留 userdel -r ogdba 2>/dev/null groupdel ogdba 2>/dev/null # 清理可能残留的安装目录 rm -rf /opt/ograc /data/ograc_install ``` 3. **重新执行安装流程** 清理完成后,重新执行预安装与安装命令,脚本会自动创建全新的 `ograc` 用户并生成完整的家目录环境: ```bash sh appctl.sh pre_install config_params_lun.json sh appctl.sh install config_params_lun.json ``` --- --- url: /zh/docs/latest/installation_guide/cm_installation_container.md --- # CM安装\_容器 本章节主要介绍通过Docker安装openGauss,方便DevOps用户的安装、配置和环境设置。 ## 支持的架构和操作系统版本 * x86-64 CentOS 7.6 * ARM64 openEuler 20.03 LTS ## CM容器化部署 ### 创建openGauss docker镜像 下载openGauss-container仓库代码,构建脚本在该仓库中管理。 > * 构建镜像需要openGauss社区发布的企业版本包openGauss-All-X.X.X-CentOS7-x86\_64.tar.gz,放到`openGauss-container/dockerfiles`目录下。 > * 运行buildDockerImage.sh脚本时,如果不指定-i参数,此时默认提供SHA256检查,,根据操作系统版本不同修改不同的校验文件, > Centos: sha256\_file\_amd64 , > openEuler\_aarch64: sha256\_file\_arm64 ,以Centos为例需要您手动将校验结果写入sha256\_file\_amd64文件。 > > ```sh > ## 修改sha256校验文件内容 > cd `openGauss-container/dockerfiles` > sha256sum openGauss-All-X.X.X-CentOS7-x86_64.tar.gz > sha256_file_amd64 > ``` > > * 对于x86平台,使用社区发布的Centos\_x86\_64的包;对于arm平台,使用发布的openEuler-arm版本企业包。 构建命令: ```sh sh buildDockerImage.sh -v X.X.X -i ``` > \[!NOTE]说明 > 默认创建版本为6.0.0,如需构建6.0.0之后版本,进入dockerfiles目录下修改对应dockerfile\_arm或dockerfile\_amd中 ENV OPENGAUSS\_VERSION 6.0.0为需要版本。 > 因包名变更,如需创建6.0.0之前版本需修改文件中包名称为对应的版本包名。 ### 使用社区发布的镜像 最新的容器镜像: x86\_64平台: ``` docker pull swr.cn-south-1.myhuaweicloud.com/opengauss/x86_64/opengauss:X.X.X docker tag swr.cn-south-1.myhuaweicloud.com/opengauss/x86_64/opengauss:X.X.X opengauss:X.X.X ``` arm平台: ``` docker pull swr.cn-south-1.myhuaweicloud.com/opengauss/arm/opengauss:X.X.X docker tag swr.cn-south-1.myhuaweicloud.com/opengauss/arm/opengauss:X.X.X opengauss:X.X.X ``` ### 启动容器 搭建CM集群至少需要两个容器实例才能使用。 1. 创建容器网络 * 如果多个容器部署在一台机器上,创建一个普通的容器网络即可。 `docker network create --subnet=172.11.0.0/24 og-network` * 如果容器跨多个节点部署,即要求节点间的容器能够进行通信。业界有多种实现方式,这里提供一种作为参考,用户可以自行选择。 选择一台部署progrium/consul容器: ``` docker pull progrium/consul docker run -d -p 8500:8500 -h consul --name consul progrium/consul -server -bootstrap ``` 每个节点的docker都进行修改: vim /usr/lib/systemd/system/docker.service 在ExecStart一栏后面追加: ``` -H tcp://0.0.0.0:2376 -H unix:///var/run/docker.sock --cluster-store=consul://192.168.0.94:8500 --cluster-advertise=eth0:2376 ``` **192.168.0.94** 是部署consul的机器ip。 修改完成后需要重启docker: ``` systemctl daemon-reload systemctl restart docker ``` 创建overlay网络 ``` docker network create -d overlay --subnet 10.22.1.0/24 --gateway 10.22.1.1 og-network ``` 2. 启动多个容器实例 ``` # ip需要和容器网络在同一网段,几个实例的ip和节点名称不能重复。如下示例1主2备: primary_nodeip="172.11.0.2" standby1_nodeip="172.11.0.3" standby2_nodeip="172.11.0.4" primary_nodename=primary standby1_nodename=standby1 standby2_nodename=standby2 OG_NETWORK=og-network GS_PASSWORD=test@123 # 启动实例1 docker run -d -it -P --ulimit nofile=1000000:1000000 --sysctl kernel.sem="250 6400000 1000 25600" --security-opt seccomp=unconfined -v /data/opengauss_volume:/volume --name opengauss-01 --net ${OG_NETWORK} --ip "$primary_nodeip" -h=$primary_nodename -e primaryhost="$primary_nodeip" -e primaryname="$primary_nodename" -e standbyhosts="$standby1_nodeip, $standby2_nodeip" -e standbynames="$standby1_nodename, $standby2_nodename" -e GS_PASSWORD=$GS_PASSWORD opengauss:X.X.X # 启动实例2 docker run -d -it -P --ulimit nofile=1000000:1000000 --sysctl kernel.sem="250 6400000 1000 25600" --security-opt seccomp=unconfined -v /data/opengauss_volume:/volume --name opengauss-02 --net ${OG_NETWORK} --ip "$standby1_nodeip" -h=$standby1_nodename -e primaryhost="$primary_nodeip" -e primaryname="$primary_nodename" -e standbyhosts="$standby1_nodeip, $standby2_nodeip" -e standbynames="$standby1_nodename, $standby2_nodename" -e GS_PASSWORD=$GS_PASSWORD opengauss:X.X.X # 启动实例3 docker run -d -it -P --ulimit nofile=1000000:1000000 --sysctl kernel.sem="250 6400000 1000 25600" --security-opt seccomp=unconfined -v /data/opengauss_volume:/volume --name opengauss-03 --net ${OG_NETWORK} --ip "$standby2_nodeip" -h=$standby2_nodename -e primaryhost="$primary_nodeip" -e primaryname="$primary_nodename" -e standbyhosts="$standby1_nodeip, $standby2_nodeip" -e standbynames="$standby1_nodename, $standby2_nodename" -e GS_PASSWORD=$GS_PASSWORD opengauss:X.X.X ``` 3. 使用脚本快速启动1主2备的cm集群容器实例 在`openGauss-container`目录下,执行`sh create_cm_contariners.sh` ```sh This script will create three containers with cm on a single node. \n Please input OG_SUBNET (容器所在网段) [172.11.0.0/24]: OG_SUBNET set 172.11.0.0/24 Please input OG_NETWORK (容器网络名称) [og-network]: OG_NETWORK set og-network Please input GS_PASSWORD (定义数据库密码)[xxxxxx]: GS_PASSWORD set Please input openGauss VERSION [X.X.X]: openGauss VERSION set X.X.X starting create docker containers... ``` 会让填入容器网段、容器网络名称、数据库密码、容器版本号。使用默认值得话可以直接回车跳过。 脚本执行完成后,会拉起3个容器实例,组成1主2备的cm集群。 ### 进入容器中查看实例状态 1. 进入容器 ``` docker exec -ti /bin/bash su - omm ``` 2. 查看集群状态 ``` cm_ctl query -Cvid ``` 3. 连接数据库 ``` gsql -d postgres -r ``` > \[!NOTE]说明 > > 1. 构建的容器需要包含操作系统层 > 2. 容器内仅提供CM和数据库内核工具,OM工具无法使用 --- --- url: >- /zh/docs/latest/resource_pooling/cm_supports_dual_cluster_backup_clusters_switchover.md --- # cm支持双集群备集群switchover ## 可获得性 本特性自openGauss 6.0.0版本开始引入。 ## 特性简介 增强CM的集群管理功能,通过该特性可以实现资源池化双集群的备集群首备切换能力。 ## 客户价值 提升对于资源池化双集群备集群的管理能力。 ## 特性描述 CM支持双集群中备集群首备和从备的switchover,保证切换后和主集群建联、日志同步状态正常。 ## 特性增强 无。 ## 特性约束 * 原首备与升首备节点状态正常。 * 尽量避免在大量业务情况下执行切换。 * 主备集群间的容灾关系正常,无网络及其他异常。 ## 依赖关系 无。 ## 基本原理 通过CM的客户端工具cm\_ctl向cm\_server发送switchover消息,cm\_server收到消息后会向对应节点的cm\_agent下发仲裁命令,再由cm\_agent执行gs\_ctl switchover使对应节点切换为备集群首备。在超时时间内,cm\_ctl会一直向cm\_server获取节点状态,通过获取到的状态判断是否切换成功,并在前端返回对应的结果。在switchover执行期间,cm\_server会暂停集群的部分仲裁,保证不会因仲裁导致切换失败。切换成功之后,新首备会主动向主集群建立连接,且从备主动连接首备,保证主备集群间容灾状态正常、备集群中首备从备连接正常。 ## 使用指导 与单集群切换命令保持一致,参考[cm\_ctl工具介绍](https://docs.opengauss.org/zh/docs/latest/tool_and_commandreference/cm_ctl.html)。 ## 使用场景 在实际生产环境中,对主节点或者备集群首备直接进行操作通常存在一定的风险,严重情况下会导致集群不可用。这个时候就可以使用该特性进行切换,便于管理且减少使用风险。如更换节点ip、更换节点名等变更场景下,为了不影响集群业务,对主节点或首备节点进行操作时,需要通过switchover命令将其切换为备节点,之后再进行对应操作。 --- --- url: /zh/docs/latest/database_reference/cm_relevant_parameters.md --- # CM相关参数 CM相关参数的修改对openGauss的运行机制有影响,建议由openGauss的工程师协助修改。修改CM相关参数的方法,请参考[CM配置参数介绍](../tool_and_commandreference/cm_parameters.md)进行设置。 --- --- url: /zh/docs/latest/tool_and_commandreference/cm_parameters.md --- # CM配置参数介绍 cm\_agent相关参数可通过cm\_agent数据目录下的cm\_agent.conf文件查看,cm\_server相关参数可通过cm\_server数据目录下的cm\_server.conf文件查看。 * **[cm\_agent参数](parameters_related_to_cm_agent.md)** * **[cm\_server参数](parameters_related_to_cm_server.md)** --- --- url: >- /zh/docs/latest/tool_and_commandreference/cm_error_log_information_reference.md --- # CM错误日志信息参考 ERRMSG: "Fail to access the cluster static config file." CMSTATE: c3000 CAUSE: "The cluster static config file is not generated or is manually deleted." ACTION: "Please check the cluster static config file." ERRMSG: "Fail to open the cluster static file." CMSTATE: c3000 CAUSE: "The cluster static config file is not generated or is manually deleted." ACTION: "Please check the cluster static config file." ERRMSG: "Fail to read the cluster static file." CMSTATE: c3001 CAUSE: "The cluster static file permission is insufficient." ACTION: "Please check the cluster static config file." ERRMSG: "Failed to read the static config file." CMSTATE: c1000 CAUSE: "out of memeory." ACTION: "Please check the system memory and try again." ERRMSG: "Could not find the current node in the cluster by the node id %u." CMSTATE: c3002 CAUSE: "The static config file probably contained content error." ACTION: "Please check static config file." ERRMSG: "Failed to open the logic config file." CMSTATE: c3000 CAUSE: "The logic config file is not generated or is manually deleted." ACTION: "Please check the cluster static config file." ERRMSG: "Fail to read the logic static config file." CMSTATE: c3001 CAUSE: "The logic static config file permission is insufficient." ACTION: "Please check the logic static config file." ERRMSG: "Failed to open or read the static config file." CMSTATE: c1000 CAUSE: "out of memeory." ACTION: "Please check the system memory and try again." ERRMSG: "Failed to open the log file '%s'." CMSTATE: c3000 CAUSE: "Log file not found." ACTION: "Please check the log file." ERRMSG: "Failed to open the log file '%s'." CMSTATE: c3000 CAUSE: "The log file permission is insufficient." ACTION: "please check the log file." ERRMSG: "Failed to open the dynamic config file '%s'." CMSTATE: c3000 CAUSE: "The dynamic config file permission is insufficient." ACTION: "Please check the dynamic config file." ERRMSG: "Failed to malloc memory, size = %lu." CMSTATE: c1000 CAUSE: "out of memeory." ACTION: "Please check the system memory and try again." ERRMSG: "unrecognized AZ name '%s'." CMSTATE: c3000 CAUSE: "The parameter(%s) entered by the user is incorrect." ACTION: "Please check the parameter entered by the user and try again." ERRMSG: "unrecognized minorityAz name '%s'." CMSTATE: c3000 CAUSE: "The parameter(%s) entered by the user is incorrect." ACTION: "Please check the parameter entered by the user and try again." ERRMSG: "Get GAUSSHOME failed." CMSTATE: c3000 CAUSE: "The environment variable('GAUSSHOME') is incorrectly configured." ACTION: "Please check the environment variable('GAUSSHOME')." ERRMSG: "Get current user name failed." CMSTATE: c3000 CAUSE: "N/A" ACTION: "Please check the environment." ERRMSG: "-B option must be specified." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-T option must be specified.\n" CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "can't stop one node or instance with -m normal." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "can't stop one node or instance with -m resume." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "can't stop one availability zone with -m resume." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "log level or cm server arbitration mode must be specified." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "log level or cm server arbitration mode need not be specified." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-R is needed." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-D is needed." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-n and -R are needed." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-n and -D are needed." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "no operation specified." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "no cm directory specified." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "Please check the usage of switchover." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-n and -z cannot be specified at the same time." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-m cannot be specified at the same time with -n or -z." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-n node(%d) is invalid." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-n node is needed." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "%s: -C is needed." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-z value must be 'ALL' when query mppdb cluster." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-v is needed." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-C is needed." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-Cv is needed." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-L value must be 'ALL' when query logic cluster." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "unrecognized LC name '%s'." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-n is needed." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "There is no '%s' information in cluster." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-D path is too long.\n" CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-D path is invalid." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-n node(%s) is invalid." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-R only support when the cluster is single-inst." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-t time is invalid." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "-votenum is invalid." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "unrecognized build mode." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "unrecognized build mode '%s'." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "too many command-line arguments (first is '%s')." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "unrecognized operation mode '%s'." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "no cm directory specified." CMSTATE: c3000 CAUSE: "%s: The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "Failed to malloc memory." CMSTATE: c1000 CAUSE: "out of memeory." ACTION: "Please check the system memory and try again." ERRMSG: "Failed to open etcd: %s." CMSTATE: c4000 CAUSE: "Etcd is abnoraml." ACTION: "Please check the Cluster Status and try again." ERRMSG: "\[PATCH-ERROR] hotpatch command or path set error." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "no standby datanode in single node cluster." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "restart logic cluster failed." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "restart logic cluster failed" CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." ERRMSG: "The option parameter is not specified." CMSTATE: c3000 CAUSE: "The cmdline entered by the user is incorrect." ACTION: "Please check the cmdline entered by the user(%s)." --- --- url: /zh/docs/latest-lite/sql_reference/collations.md --- # COLLATIONS 存储字符序相关的信息。 **表 1** COLLATIONS相比于PGXC/PG新增字段 --- --- url: /zh/docs/latest/sql_reference/collations.md --- # COLLATIONS 存储字符序相关的信息。 **表 1** COLLATIONS相比于PGXC/PG新增字段 --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_column_name_identifiers.md --- # Column Name Identifiers ## Precautions Compared with the original openGauss, Dolphin modifies the column name identifiers as follows: * Column names and aliases are sensitive to storage and display. Whether to use double quotation marks to enclose column names is not considered. * Column names and aliases are insensitive to comparison. That is, column names **'aAa'** and **'AAa'** identify the same column. Example: ``` openGauss=# create database col_name dbcompatibility 'B'; CREATE DATABASE openGauss=# \c col_name col_name=# create table t1(aAa int); CREATE TABLE col_name=# insert into t1 values(1); INSERT 0 1 col_name=# select * from t1; aAa ----- 1 (1 row) col_name=# select "AAa" from t1; AAa ----- 1 (1 row) col_name=# select aaa AS AaA from t1; AaA ----- 1 (1 row) ``` --- --- url: /en/docs/latest/characteristic_description/advanced_features/column_store.md --- # Column Store openGauss supports hybrid row-column store. Row store stores tables to disk partitions by row, and column store stores tables to disk partitions by column. Each storage model applies to specific scenarios. Select an appropriate model when creating a table. Generally, openGauss is used for databases in online transaction processing (OLTP) scenarios. By default, row store is used. Column store is used only in online analytical processing (OLAP) scenarios where complex queries are performed and the data volume is large. By default, a row-store table is created. For details about differences between row store and column store, see [Figure 1](#en-us_topic_0283136734_en-us_topic_0237120296_fig1417354233018). **Figure 1** Differences between row store and column store In the preceding figure, the upper left part is a row-store table, and the upper right part shows how the row-store table is stored on a disk; the lower left part is a column-store table, and the lower right part shows how the column-store table is stored on a disk. Both row-store and column-store models have benefits and drawbacks. Generally, if a table contains many columns (called a wide table) and its query involves only a few columns, column store is recommended. Row store is recommended if a table contains only a few columns and a query involves most of the columns. ## Syntax ``` CREATE TABLE table_name (column_name data_type [, ... ]) [ WITH ( ORIENTATION = value) ]; ``` ## Parameter Description * **table\_name** Specifies the name of the table to be created. * **column\_name** Specifies the name of a column to be created in the new table. * **data\_type** Specifies the data type of the column. * **ORIENTATION** Specifies the storage mode (row-store, column-store, or ORC) of table data. This parameter cannot be modified once it is set. Value range: * **ROW** indicates that table data is stored in rows. **ROW** applies to OLTP services and scenarios with a large number of point queries or addition/deletion operations. * **COLUMN** indicates that the data is stored in columns. **COLUMN** applies to the data warehouse service, which has a large amount of aggregation computing, and involves a few column operations. ## Example If **ORIENTATION** is not specified, the table is a row-store table by default. For example: ``` openGauss=# CREATE TABLE customer_test1 ( state_ID CHAR(2), state_NAME VARCHAR2(40), area_ID NUMBER ); -- Delete the table. openGauss=# DROP TABLE customer_test1; ``` When creating a column-store table, you need to specify the **ORIENTATION** parameter. For example: ``` openGauss=# CREATE TABLE customer_test2 ( state_ID CHAR(2), state_NAME VARCHAR2(40), area_ID NUMBER ) WITH (ORIENTATION = COLUMN); -- Delete the table. openGauss=# DROP TABLE customer_test2; ``` --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-COLUMNS.md --- # COLUMNS 用户定义对象的所有列。 **表1** COLUMNS --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-INFORMATION_SCHEMA_TSQL.COLUMNS.md --- # COLUMNS COLUMNS视图返回数据库中的列信息。 **表1** COLUMNS --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-COLUMNS.md --- # COLUMNS 用户定义对象的所有列。 **表1** COLUMNS --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-INFORMATION_SCHEMA_TSQL.COLUMNS.md --- # COLUMNS COLUMNS视图返回数据库中的列信息。 **表1** COLUMNS --- --- url: /zh/docs/latest-lite/sql_reference/columns.md --- # COLUMNS 存储列相关的信息。 **表 1** COLUMNS相比于PGXC/PG新增字段 --- --- url: /zh/docs/latest/sql_reference/columns.md --- # COLUMNS 存储列相关的信息。 **表 1** COLUMNS相比于PGXC/PG新增字段 --- --- url: >- /en/docs/latest/characteristic_description/aifeature_guide/prometheus_exporter_command_reference.md --- # Command Reference For details about how to use reprocessing-exporter, see the following help information: ``` gs_dbmind component reprocessing_exporter --help usage: [-h] [--disable-https] [--ssl-keyfile SSL_KEYFILE] [--ssl-certfile SSL_CERTFILE] [--ssl-ca-file SSL_CA_FILE] [--web.listen-address WEB.LISTEN_ADDRESS] [--web.listen-port WEB.LISTEN_PORT] [--collector.config COLLECTOR.CONFIG] [--log.filepath LOG.FILEPATH] [--log.level {debug,info,warn,error,fatal}] [-v] prometheus_host prometheus_port Reprocessing Exporter: A re-processing module for metrics stored in the Prometheus server. positional arguments: prometheus_host from which host to pull data prometheus_port the port to connect to the Prometheus host optional arguments: -h, --help show this help message and exit --disable-https disable Https scheme --ssl-keyfile SSL_KEYFILE set the path of ssl key file --ssl-certfile SSL_CERTFILE set the path of ssl certificate file --ssl-ca-file SSL_CA_FILE set the path of ssl ca file --web.listen-address WEB.LISTEN_ADDRESS address on which to expose metrics and web interface --web.listen-port WEB.LISTEN_PORT listen port to expose metrics and web interface --collector.config COLLECTOR.CONFIG according to the content of the yaml file for metric collection --log.filepath LOG.FILEPATH the path to log --log.level {debug,info,warn,error,fatal} only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal] -v, --version show program's version number and exit ``` **Table 1** reprocessing-exporter parameters For details about how to use openGauss-exporter, see the following help information: ``` gs_dbmind component opengauss_exporter --help usage: [-h] --url URL [--config-file CONFIG_FILE] [--include-databases INCLUDE_DATABASES] [--exclude-databases EXCLUDE_DATABASES] [--constant-labels CONSTANT_LABELS] [--web.listen-address WEB.LISTEN_ADDRESS] [--web.listen-port WEB.LISTEN_PORT] [--disable-cache] [--disable-settings-metrics] [--disable-statement-history-metrics] [--disable-https] [--disable-agent] [--ssl-keyfile SSL_KEYFILE] [--ssl-certfile SSL_CERTFILE] [--ssl-ca-file SSL_CA_FILE] [--parallel PARALLEL] [--log.filepath LOG.FILEPATH] [--log.level {debug,info,warn,error,fatal}] [-v] openGauss Exporter (DBMind): Monitoring or controlling for openGauss. optional arguments: -h, --help show this help message and exit --url URL openGauss database target url. It is recommended to connect to the postgres database through this URL, so that the exporter can actively discover and monitor other databases. --config-file CONFIG_FILE, --config CONFIG_FILE path to config file. --include-databases INCLUDE_DATABASES only scrape metrics from the given database list. a list of label=value separated by comma(,). --exclude-databases EXCLUDE_DATABASES scrape metrics from the all auto-discovered databases excluding the list of database. a list of label=value separated by comma(,). --constant-labels CONSTANT_LABELS a list of label=value separated by comma(,). --web.listen-address WEB.LISTEN_ADDRESS address on which to expose metrics and web interface --web.listen-port WEB.LISTEN_PORT listen port to expose metrics and web interface --disable-cache force not using cache. --disable-settings-metrics not collect pg_settings.yml metrics. --disable-statement-history-metrics not collect statement-history metrics (including slow queries). --disable-https disable Https scheme --disable-agent by default, this exporter also assumes the role of DBMind-Agent, that is, executing database operation and maintenance actions issued by the DBMind service. With this argument, users can disable the agent functionality, thereby prohibiting the DBMind service from making changes to the database. --ssl-keyfile SSL_KEYFILE set the path of ssl key file --ssl-certfile SSL_CERTFILE set the path of ssl certificate file --ssl-ca-file SSL_CA_FILE set the path of ssl ca file --parallel PARALLEL not collect pg_settings.yml metrics. --log.filepath LOG.FILEPATH the path to log --log.level {debug,info,warn,error,fatal} only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal] -v, --version show program's version number and exit ``` **Table 2** openGauss-exporter parameters For details about how to use cmd-exporter, see the following help information: ``` usage: [-h] [--constant-labels CONSTANT_LABELS] [--web.listen-address WEB.LISTEN_ADDRESS] [--web.listen-port WEB.LISTEN_PORT] [--disable-https] [--config CONFIG] [--ssl-keyfile SSL_KEYFILE] [--ssl-certfile SSL_CERTFILE] [--ssl-ca-file SSL_CA_FILE] [--parallel PARALLEL] [--log.filepath LOG.FILEPATH] [--log.level {debug,info,warn,error,fatal}] [-v] Command Exporter (DBMind): scrape metrics by performing shell commands. optional arguments: -h, --help show this help message and exit --constant-labels CONSTANT_LABELS a list of label=value separated by comma(,). --web.listen-address WEB.LISTEN_ADDRESS address on which to expose metrics and web interface --web.listen-port WEB.LISTEN_PORT listen port to expose metrics and web interface --disable-https disable Https scheme --config CONFIG path to config dir or file. --ssl-keyfile SSL_KEYFILE set the path of ssl key file --ssl-certfile SSL_CERTFILE set the path of ssl certificate file --ssl-ca-file SSL_CA_FILE set the path of ssl ca file --parallel PARALLEL performing shell command in parallel. --log.filepath LOG.FILEPATH the path to log --log.level {debug,info,warn,error,fatal} only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal] -v, --version show program's version number and exit ``` **Table 3** cmd-exporter parameters --- --- url: /en/docs/latest-lite/sql_reference/comment.md --- # COMMENT ## Function **COMMENT** defines or changes the comment of an object. ## Precautions * Each object stores only one comment. Therefore, you need to modify a comment and issue a new **COMMENT** command to the same object. To delete the comment, write **NULL** at the position of the text string. When an object is deleted, the comment is automatically deleted. * Currently, there is no security protection for viewing comments. Any user connected to a database can view all the comments for objects in the database. For shared objects such as databases, roles, and tablespaces, comments are stored globally so any user connected to any database in the cluster can see all the comments for shared objects. Therefore, do not put security-critical information in comments. * To comment objects, you must be an object owner or user granted the COMMENT permission. The system administrator has this permission by default. * Roles do not have owners, so the rule for **COMMENT ON ROLE** is that you must be an administrator to comment on an administrator role, or have the **CREATEROLE** permission to comment on non-administrator roles. A system administrator can comment on all objects. ## Syntax ``` COMMENT ON { AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | COLUMN { table_name.column_name | view_name.column_name } | CONSTRAINT constraint_name ON table_name | CONVERSION object_name | DATABASE object_name | DOMAIN object_name | EXTENSION object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ {[ argname ] [ argmode ] argtype} [, ...] ] ) | INDEX object_name | LARGE OBJECT large_object_oid | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | ROLE object_name | SCHEMA object_name | SERVER object_name | TABLE object_name | TABLESPACE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name | TRIGGER trigger_name ON table_name } IS 'text'; ``` ## Parameter Description * **agg\_name** Specifies the new name of an aggregate function. * **agg\_type** Specifies the data type of the aggregate function parameters. * **source\_type** Specifies the source data type of the cast. * **target\_type** Specifies the target data type of the cast. * **object\_name** Specifies the name of an object. * **table\_name.column\_name** **view\_name.column\_name** Specifies the column whose comment is defined or modified. You can add the table name or view name as the prefix. * **constraint\_name** Specifies the table constraint whose comment is defined or modified. * **table\_name** Specifies the name of a table. * **function\_name** Specifies the function whose comment is defined or modified. * **argname,argmode,argtype** Specifies the name, schema, and type of the function parameters. * **large\_object\_oid** Specifies the OID of the large object whose comment is defined or modified. * **operator\_name** Specifies the name of the operator. * **left\_type,right\_type** Specifies the data type of the operator parameters (optionally schema-qualified). If the prefix or suffix operator does not exist, the **NONE** option can be added. * **trigger\_name** Specifies the trigger name. * **text** Specifies the comment content. ## Examples ``` openGauss=# CREATE TABLE tpcds.customer_demographics_t2 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- Comment out the tpcds.customer_demographics_t2.cd_demo_sk column. openGauss=# COMMENT ON COLUMN tpcds.customer_demographics_t2.cd_demo_sk IS 'Primary key of customer demographics table.'; -- Create a view consisting of rows with c_customer_sk less than 150. openGauss=# CREATE VIEW tpcds.customer_details_view_v2 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; -- Comment out the tpcds.customer_details_view_v2 view. openGauss=# COMMENT ON VIEW tpcds.customer_details_view_v2 IS 'View of customer detail'; -- Delete the view. openGauss=# DROP VIEW tpcds.customer_details_view_v2; -- Delete the tpcds.customer_demographics_t2 table. openGauss=# DROP TABLE tpcds.customer_demographics_t2; ``` --- --- url: /en/docs/latest/sql_reference/comment.md --- # COMMENT ## Function **COMMENT** defines or changes the comment of an object. ## Precautions * Each object stores only one comment. Therefore, you need to modify a comment and issue a new **COMMENT** command to the same object. To delete the comment, write **NULL** at the position of the text string. When an object is deleted, the comment is automatically deleted. * Currently, there is no security protection for viewing comments. Any user connected to a database can view all the comments for objects in the database. For shared objects such as databases, roles, and tablespaces, comments are stored globally so any user connected to any database in the cluster can see all the comments for shared objects. Therefore, do not put security-critical information in comments. * To comment objects, you must be an object owner or user granted the COMMENT permission. The system administrator has this permission by default. * Roles do not have owners, so the rule for **COMMENT ON ROLE** is that you must be an administrator to comment on an administrator role, or have the **CREATEROLE** permission to comment on non-administrator roles. A system administrator can comment on all objects. ## Syntax ``` COMMENT ON { AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | COLUMN { table_name.column_name | view_name.column_name } | CONSTRAINT constraint_name ON table_name | CONVERSION object_name | DATABASE object_name | DOMAIN object_name | EXTENSION object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ {[ argname ] [ argmode ] argtype} [, ...] ] ) | INDEX object_name | LARGE OBJECT large_object_oid | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | ROLE object_name | SCHEMA object_name | SERVER object_name | TABLE object_name | TABLESPACE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name | TRIGGER trigger_name ON table_name } IS 'text'; ``` ## Parameter Description * **agg\_name** Specifies the new name of an aggregate function. * **agg\_type** Specifies the data type of the aggregate function parameters. * **source\_type** Specifies the source data type of the cast. * **target\_type** Specifies the target data type of the cast. * **object\_name** Specifies the name of an object. * **table\_name.column\_name** **view\_name.column\_name** Specifies the column whose comment is defined or modified. You can add the table name or view name as the prefix. * **constraint\_name** Specifies the table constraint whose comment is defined or modified. * **table\_name** Specifies the name of a table. * **function\_name** Specifies the function whose comment is defined or modified. * **argname,argmode,argtype** Specifies the schema, name, and type of the function parameters. * **large\_object\_oid** Specifies the OID of the large object whose comment is defined or modified. * **operator\_name** Specifies the name of the operator. * **left\_type,right\_type** Specifies the data type of the operator parameters (optionally schema-qualified). If the prefix or suffix operator does not exist, the **NONE** option can be added. * **trigger\_name** Specifies the trigger name. * **text** Specifies the comment content. ## Examples ``` openGauss=# CREATE TABLE tpcds.customer_demographics_t2 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- Comment out the tpcds.customer_demographics_t2.cd_demo_sk column. openGauss=# COMMENT ON COLUMN tpcds.customer_demographics_t2.cd_demo_sk IS 'Primary key of customer demographics table.'; -- Create a view consisting of rows with c_customer_sk less than 150. openGauss=# CREATE VIEW tpcds.customer_details_view_v2 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; -- Comment out the tpcds.customer_details_view_v2 view. openGauss=# COMMENT ON VIEW tpcds.customer_details_view_v2 IS 'View of customer detail'; -- Delete the view. openGauss=# DROP VIEW tpcds.customer_details_view_v2; -- Delete the tpcds.customer_demographics_t2 table. openGauss=# DROP TABLE tpcds.customer_demographics_t2; ``` --- --- url: /zh/docs/latest-lite/sql_reference/comment.md --- # COMMENT ## 功能描述 定义或修改一个对象的注释。 ## 注意事项 * 每个对象只存储一条注释,因此要修改一个注释,对同一个对象发出一条新的COMMENT命令即可。要删除注释,在文本字符串的位置写上NULL即可。当删除对象时,注释自动被删除掉。 * 目前注释浏览没有安全机制:任何连接到某数据库上的用户都可以看到所有该数据库对象的注释。共享对象(比如数据库、角色、表空间)的注释是全局存储的,连接到任何数据库的任何用户都可以看到它们。因此,不要在注释里存放与安全有关的敏感信息。 * 对大多数对象,只有对象的所有者或者被授予了对象COMMENT权限的用户可以设置注释,系统管理员默认拥有该权限。 * 角色没有所有者,所以COMMENT ON ROLE命令仅可以由系统管理员对系统管理员角色执行,有CREATEROLE权限的角色也可以为非系统管理员角色设置注释。系统管理员可以对所有对象进行注释。 ## 语法格式 ``` COMMENT ON { AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | COLUMN { table_name.column_name | view_name.column_name } | CONSTRAINT constraint_name ON table_name | CONVERSION object_name | DATABASE object_name | DOMAIN object_name | EXTENSION object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ {[ argname ] [ argmode ] argtype} [, ...] ] ) | INDEX object_name | LARGE OBJECT large_object_oid | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | ROLE object_name | SCHEMA object_name | SERVER object_name | TABLE object_name | TABLESPACE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name | TRIGGER trigger_name ON table_name } IS 'text'; ``` ## 参数说明 * **agg\_name** 聚集函数的名称。 * **agg\_type** 聚集函数参数的类型。 * **source\_type** 类型转换的源数据类型。 * **target\_type** 类型转换的目标数据类型。 * **object\_name** 对象名。 * **table\_name.column\_name** **view\_name.column\_name** 定义/修改注释的列名称。前缀可加表名称或者视图名称。 * **constraint\_name** 定义/修改注释的表约束的名称。 * **table\_name** 表的名称。 * **function\_name** 定义/修改注释的函数名称。 * **argname,argmode,argtype** 函数参数的名称、模式、类型。 * **large\_object\_oid** 定义/修改注释的大对象的OID值。 * **operator\_name** 操作符名称。 * **left\_type,right\_type** 操作参数的数据类型(可以用模式修饰)。当前置或者后置操作符不存在时,可以增加NONE选项。 * **trigger\_name** 触发器名称。 * **text** 注释。 ## 示例 ``` openGauss=# CREATE TABLE tpcds.customer_demographics_t2 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- 为tpcds.customer_demographics_t2.cd_demo_sk列加注释。 openGauss=# COMMENT ON COLUMN tpcds.customer_demographics_t2.cd_demo_sk IS 'Primary key of customer demographics table.'; --创建一个由c_customer_sk小于150的内容组成的视图。 openGauss=# CREATE VIEW tpcds.customer_details_view_v2 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; -- 为tpcds.customer_details_view_v2视图加注释。 openGauss=# COMMENT ON VIEW tpcds.customer_details_view_v2 IS 'View of customer detail'; -- 删除view。 openGauss=# DROP VIEW tpcds.customer_details_view_v2; -- 删除tpcds.customer_demographics_t2。 openGauss=# DROP TABLE tpcds.customer_demographics_t2; ``` --- --- url: /zh/docs/latest/sql_reference/comment.md --- # COMMENT ## 功能描述 定义或修改一个对象的注释。 ## 注意事项 * 每个对象只存储一条注释,因此要修改一个注释,对同一个对象发出一条新的COMMENT命令即可。要删除注释,在文本字符串的位置写上NULL即可。当删除对象时,注释自动被删除掉。 * 目前注释浏览没有安全机制:任何连接到某数据库上的用户都可以看到所有该数据库对象的注释。共享对象(比如数据库、角色、表空间)的注释是全局存储的,连接到任何数据库的任何用户都可以看到它们。因此,不要在注释里存放与安全有关的敏感信息。 * 对大多数对象,只有对象的所有者或者被授予了对象COMMENT权限的用户可以设置注释,系统管理员默认拥有该权限。 * 角色没有所有者,所以COMMENT ON ROLE命令仅可以由系统管理员对系统管理员角色执行,有CREATEROLE权限的角色也可以为非系统管理员角色设置注释。系统管理员可以对所有对象进行注释。 ## 语法格式 ``` COMMENT ON { AGGREGATE agg_name (agg_type [, ...] ) | CAST (source_type AS target_type) | COLLATION object_name | COLUMN { table_name.column_name | view_name.column_name } | CONSTRAINT constraint_name ON table_name | CONVERSION object_name | DATABASE object_name | DOMAIN object_name | Extension object_name | FOREIGN DATA WRAPPER object_name | FOREIGN TABLE object_name | FUNCTION function_name ( [ {[ argname ] [ argmode ] argtype} [, ...] ] ) | INDEX object_name | LARGE OBJECT large_object_oid | OPERATOR operator_name (left_type, right_type) | OPERATOR CLASS object_name USING index_method | OPERATOR FAMILY object_name USING index_method | [ PROCEDURAL ] LANGUAGE object_name | ROLE object_name | SCHEMA object_name | SERVER object_name | TABLE object_name | TABLESPACE object_name | TEXT SEARCH CONFIGURATION object_name | TEXT SEARCH DICTIONARY object_name | TEXT SEARCH PARSER object_name | TEXT SEARCH TEMPLATE object_name | TYPE object_name | VIEW object_name | TRIGGER trigger_name ON table_name } IS 'text'; ``` ## 参数说明 * **agg\_name** 聚集函数的名称。 * **agg\_type** 聚集函数参数的类型。 * **source\_type** 类型转换的源数据类型。 * **target\_type** 类型转换的目标数据类型。 * **object\_name** 对象名。 * **table\_name.column\_name** **view\_name.column\_name** 定义/修改注释的列名称。前缀可加表名称或者视图名称。 * **constraint\_name** 定义/修改注释的表约束的名称。 * **table\_name** 表的名称。 * **function\_name** 定义/修改注释的函数名称。 * **argname,argmode,argtype** 函数参数的模式、名称、类型。 * **large\_object\_oid** 定义/修改注释的大对象的OID值。 * **operator\_name** 操作符名称。 * **left\_type,right\_type** 操作参数的数据类型(可以用模式修饰)。当前置或者后置操作符不存在时,可以增加NONE选项。 * **trigger\_name** 触发器名称。 * **text** 注释。 ## 示例 ``` openGauss=# CREATE TABLE tpcds.customer_demographics_t2 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- 为tpcds.customer_demographics_t2.cd_demo_sk列加注释。 openGauss=# COMMENT ON COLUMN tpcds.customer_demographics_t2.cd_demo_sk IS 'Primary key of customer demographics table.'; --创建一个由c_customer_sk小于150的内容组成的视图。 openGauss=# CREATE VIEW tpcds.customer_details_view_v2 AS SELECT * FROM tpcds.customer WHERE c_customer_sk < 150; -- 为tpcds.customer_details_view_v2视图加注释。 openGauss=# COMMENT ON VIEW tpcds.customer_details_view_v2 IS 'View of customer detail'; -- 删除view。 openGauss=# DROP VIEW tpcds.customer_details_view_v2; -- 删除tpcds.customer_demographics_t2。 openGauss=# DROP TABLE tpcds.customer_demographics_t2; ``` --- --- url: /zh/docs/latest/ograc/sql_reference/comment_on.md --- # COMMENT ON ## 功能描述 使用 `COMMENT ON` 语句为表、视图或列添加注释信息。 添加的注释可通过以下系统视图查看: * **表/视图注释**:`MY_TAB_COMMENTS`、`ADM_TAB_COMMENTS` * **列注释**:`MY_COL_COMMENTS`、`ADM_COL_COMMENTS` ## 注意事项 * **权限要求**: * 为自己的表添加注释无需额外权限。 * 为其他用户的表添加注释需要具备 `COMMENT ANY TABLE` 权限。 * **支持场景**: * 支持在创建表时指定列的注释。 * **限制**: * 数据库重启或回滚期间不支持此操作。 ## 语法格式 ```sql COMMENT ON { TABLE [ schema_name. ] { table_name | view_name } | COLUMN [ schema_name. ] { table_name. | view_name. } column_name } IS 'string'; ``` ## 参数说明 * **\[ schema\_name. ]**: 用户名(模式名)。缺省时为当前登录用户。 * **{ table\_name | view\_name }**: 要添加注释的表名或视图名。 * **\[ schema\_name. ] { table\_name. | view\_name. } column\_name**: 要添加注释的列名。 * **IS**: 指定注释内容的关键字。 * **string**: 注释文本,最大长度为 4000 字节。 ## 示例 ``` -- 删除用户表 user_info(如果存在) DROP TABLE IF EXISTS user_info; -- 创建用户表 user_info CREATE TABLE user_info (user_id INT PRIMARY KEY,username VARCHAR(50) NOT NULL, email VARCHAR(100), create_time DATETIME DEFAULT CURRENT_TIMESTAMP, status CHAR(1) DEFAULT 'A'); -- 为表 user_info 添加注释 COMMENT ON TABLE user_info IS 'table of user info'; -- 为列 user_id 添加注释 COMMENT ON COLUMN user_info.user_id IS 'id of users'; ``` --- --- url: /en/docs/latest-lite/developer_guide/commissioning.md --- # Commissioning To control the output of log files and better understand the operating status of the database, modify specific configuration parameters in the **postgresql.conf** file in the instance data directory. [Table 1](#en-us_topic_0283136686_en-us_topic_0237120444_en-us_topic_0059779333_tec23904511dd4695b8b01f8c7c04563a) describes the adjustable configuration parameters. **Table 1** Configuration parameters [Table 2](#en-us_topic_0283136686_en-us_topic_0237120444_en-us_topic_0059779333_t3c729a4a94d145c7bdc4ca788236d8a7) describes the preceding parameter levels. **Table 2** Description of log level parameters --- --- url: /en/docs/latest/developer_guide/commissioning.md --- # Commissioning To control the output of log files and better understand the operating status of the database, modify specific configuration parameters in the **postgresql.conf** file in the instance data directory. [Table 1](#en-us_topic_0283136686_en-us_topic_0237120444_en-us_topic_0059779333_tec23904511dd4695b8b01f8c7c04563a) describes the adjustable configuration parameters. **Table 1** Configuration parameters [Table 2](#en-us_topic_0283136686_en-us_topic_0237120444_en-us_topic_0059779333_t3c729a4a94d145c7bdc4ca788236d8a7) describes the preceding parameter levels. **Table 2** Description of log level parameters --- --- url: /zh/docs/latest/ograc/sql_reference/commit.md --- # COMMIT ## 功能描述 提交当前事务,使事务中的所有数据操作永久生效并结束该事务。 ## 注意事项 数据操作(`SELECT`、`DELETE`、`UPDATE`)默认不会自动提交。会话退出时,必须显式执行 `COMMIT`,否则所有未提交的更改将会丢失。 关于事务的提交机制,说明如下: 1. 对于 DML的事务操作,必须通过显式执行 `COMMIT` 或 `ROLLBACK` 来完成提交或回滚。 **特殊情况**:如果事务中执行了 DDL语句,则该 DDL 语句执行时,会自动提交之前所有未提交的 DML 操作。 此外,若 DML 操作在执行过程中部分失败,不影响后面DML的继续执行和事务提交操作。 2. 在执行了一个DDL语句后,不能对之前的DML操作进行回滚。 同时,DDL 操作本身在成功执行后会自动提交,失败则会自动回滚,无需用户显式commit/rollback,且执行成功后不可回滚。 ## 语法格式 ```sql COMMIT [ TRANSACTION ] ``` ## 参数说明 * **COMMIT \[ TRANSACTION ]**: 提交当前事务。TRANSACTION 为可选的增强可读性关键字,与直接执行 COMMIT 效果相同。 ## 示例 创建表training,插入数据并更新数据,提交操作后结束该事务。 ``` --删除表training DROP TABLE IF EXISTS training; --创建表training 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 INTO training(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_date,score) VALUES(10,'zhangsan','cpp','2025-11-23 12:00:00','2025-11-24 12:00:00','2025-11-25 12:00:00',72); --向表中插入第二条记录 INSERT INTO training(staff_id,staff_name,course_name,course_start_date,course_end_date,exam_date,score) VALUES(11,'lisi','cpp','2025-11-26 12:00:00','2025-11-27 12:00:00','2025-11-28 12:00:00',87); --更新第二条记录中的staff_name字段和course_name字段 UPDATE training SET staff_name='lisi', course_name='INFORMATION SAFETY' WHERE staff_id=11; --提交事务。 COMMIT; ``` --- --- url: /en/docs/latest-lite/sql_reference/commit_end.md --- # COMMIT | END ## Function **COMMIT** or **END** commits all operations of a transaction. ## Precautions Only the creator of a transaction or a system administrator can run the **COMMIT** command. The creation and commit operations must be in different sessions. ## Syntax ``` { COMMIT | END } [ WORK | TRANSACTION ] ; ``` ## Parameter Description * **COMMIT | END** Commits the current transaction and makes all changes made by the transaction become visible to others. * **WORK | TRANSACTION** Specifies an optional keyword, which has no effect except increasing readability. ## Examples ``` -- Create a table. openGauss=# CREATE TABLE tpcds.customer_demographics_t2 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- Start a transaction. openGauss=# START TRANSACTION; -- Insert data. openGauss=# INSERT INTO tpcds.customer_demographics_t2 VALUES(1,'M', 'U', 'DOCTOR DEGREE', 1200, 'GOOD', 1, 0, 0); openGauss=# INSERT INTO tpcds.customer_demographics_t2 VALUES(2,'F', 'U', 'MASTER DEGREE', 300, 'BAD', 1, 0, 0); -- Commit the transaction to make all changes permanent. openGauss=# COMMIT; -- Query data. openGauss=# SELECT * FROM tpcds.customer_demographics_t2; -- Delete the tpcds.customer_demographics_t2 table. openGauss=# DROP TABLE tpcds.customer_demographics_t2; ``` ## Helpful Links [ROLLBACK](rollback.md) --- --- url: /en/docs/latest/sql_reference/commit_end.md --- # COMMIT | END ## Function **COMMIT** or **END** commits all operations of a transaction. ## Precautions Only the creator of a transaction or a system administrator can run the **COMMIT** command. The creation and commit operations only be in the same sessions. ## Syntax ``` { COMMIT | END } [ WORK | TRANSACTION ] ; ``` ## Parameter Description * **COMMIT | END** Commits the current transaction and makes all changes made by the transaction become visible to others. * **WORK | TRANSACTION** Specifies an optional keyword, which has no effect except increasing readability. ## Examples ``` -- Create a table. openGauss=# CREATE TABLE tpcds.customer_demographics_t2 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- Start a transaction. openGauss=# START TRANSACTION; -- Insert data. openGauss=# INSERT INTO tpcds.customer_demographics_t2 VALUES(1,'M', 'U', 'DOCTOR DEGREE', 1200, 'GOOD', 1, 0, 0); openGauss=# INSERT INTO tpcds.customer_demographics_t2 VALUES(2,'F', 'U', 'MASTER DEGREE', 300, 'BAD', 1, 0, 0); -- Commit the transaction to make all changes permanent. openGauss=# COMMIT; -- Query data. openGauss=# SELECT * FROM tpcds.customer_demographics_t2; -- Delete the tpcds.customer_demographics_t2 table. openGauss=# DROP TABLE tpcds.customer_demographics_t2; ``` ## Helpful Links [ROLLBACK](rollback.md) --- --- url: /zh/docs/latest-lite/sql_reference/commit_end.md --- # COMMIT | END ## 功能描述 通过COMMIT或者END可完成提交事务的功能,即提交事务的所有操作。 ## 注意事项 执行COMMIT这个命令的时候,命令执行者必须是该事务的创建者或系统管理员,且创建和提交操作只能在同一个会话中。 ## 语法格式 ``` { COMMIT | END } [ WORK | TRANSACTION ] ; ``` ## 参数说明 * **COMMIT | END** 提交当前事务,让所有当前事务的更改为其他事务可见。 * **WORK | TRANSACTION** 可选关键字,除了增加可读性没有其他任何作用。 ## 示例 ``` --创建表。 openGauss=# CREATE TABLE tpcds.customer_demographics_t2 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; --开启事务。 openGauss=# START TRANSACTION; --插入数据。 openGauss=# INSERT INTO tpcds.customer_demographics_t2 VALUES(1,'M', 'U', 'DOCTOR DEGREE', 1200, 'GOOD', 1, 0, 0); openGauss=# INSERT INTO tpcds.customer_demographics_t2 VALUES(2,'F', 'U', 'MASTER DEGREE', 300, 'BAD', 1, 0, 0); --提交事务,让所有更改永久化。 openGauss=# COMMIT; --查询数据。 openGauss=# SELECT * FROM tpcds.customer_demographics_t2; --删除表tpcds.customer_demographics_t2。 openGauss=# DROP TABLE tpcds.customer_demographics_t2; ``` ## 相关链接 [ROLLBACK](rollback.md) --- --- url: /zh/docs/latest/sql_reference/commit_end.md --- # COMMIT | END ## 功能描述 通过COMMIT或者END可完成提交事务的功能,即提交事务的所有操作。 ## 注意事项 执行COMMIT这个命令的时候,命令执行者必须是该事务的创建者或系统管理员,且创建和提交操作只能在同一个会话中。 ## 语法格式 ``` { COMMIT | END } [ WORK | TRANSACTION ] ; ``` ## 参数说明 * **COMMIT | END** 提交当前事务,让所有当前事务的更改为其他事务可见。 * **WORK | TRANSACTION** 可选关键字,除了增加可读性没有其他任何作用。 ## 示例 ``` --创建表。 openGauss=# CREATE TABLE tpcds.customer_demographics_t2 ( CD_DEMO_SK INTEGER NOT NULL, CD_GENDER CHAR(1) , CD_MARITAL_STATUS CHAR(1) , CD_EDUCATION_STATUS CHAR(20) , CD_PURCHASE_ESTIMATE INTEGER , CD_CREDIT_RATING CHAR(10) , CD_DEP_COUNT INTEGER , CD_DEP_EMPLOYED_COUNT INTEGER , CD_DEP_COLLEGE_COUNT INTEGER ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; --开启事务。 openGauss=# START TRANSACTION; --插入数据。 openGauss=# INSERT INTO tpcds.customer_demographics_t2 VALUES(1,'M', 'U', 'DOCTOR DEGREE', 1200, 'GOOD', 1, 0, 0); openGauss=# INSERT INTO tpcds.customer_demographics_t2 VALUES(2,'F', 'U', 'MASTER DEGREE', 300, 'BAD', 1, 0, 0); --提交事务,让所有更改永久化。 openGauss=# COMMIT; --查询数据。 openGauss=# SELECT * FROM tpcds.customer_demographics_t2; --删除表tpcds.customer_demographics_t2。 openGauss=# DROP TABLE tpcds.customer_demographics_t2; ``` ## 相关链接 [ROLLBACK](rollback.md) --- --- url: /en/docs/latest-lite/sql_reference/commit_prepared.md --- # COMMIT PREPARED ## Function **COMMIT PREPARED** commits a prepared two-phase transaction. ## Precautions * The function is only available in maintenance mode (when the GUC parameter **xc\_maintenance\_mode** is **on**). Exercise caution when enabling the mode. It is used by maintenance engineers for troubleshooting. Common users should not use the mode. * Only the transaction creators or system administrators can run the **COMMIT PREPARED** command. The creation and commit operations must be in different sessions. * The transaction function is maintained automatically by the database, and should be not visible to users. ## Syntax ``` COMMIT PREPARED transaction_id ; COMMIT PREPARED transaction_id WITH CSN; ``` ## Parameter Description * **transaction\_id** Specifies the identifier of the transaction to be committed. The identifier must be different from those for current prepared transactions. * **CSN (commit sequence number)** Specifies the sequence number of the transaction to be committed. It is a 64-bit, incremental, unsigned number. ## Examples ``` COMMIT PREPARED commits a transaction whose identifier is trans_test. openGauss=# COMMIT PREPARED 'trans_test'; ``` ## Helpful Links [PREPARE TRANSACTION](prepare_transaction.md) and [ROLLBACK PREPARED](rollback_prepared.md) --- --- url: /en/docs/latest/sql_reference/commit_prepared.md --- # COMMIT PREPARED ## Function **COMMIT PREPARED** commits a prepared two-phase transaction. ## Precautions * The function is only available in maintenance mode (when the GUC parameter **xc\_maintenance\_mode** is **on**). Exercise caution when enabling the mode. It is used by maintenance engineers for troubleshooting. Common users should not use the mode. * Only the transaction creators or system administrators can run the **COMMIT PREPARED** command. The creation and commit operations only be in the same sessions. * The transaction function is maintained automatically by the database, and should be not visible to users. ## Syntax ``` COMMIT PREPARED transaction_id ; COMMIT PREPARED transaction_id WITH CSN; ``` ## Parameter Description * **transaction\_id** Specifies the identifier of the transaction to be committed. The identifier must be different from those for current prepared transactions. * **CSN (commit sequence number)** Specifies the sequence number of the transaction to be committed. It is a 64-bit, incremental, unsigned number. ## Examples ``` COMMIT PREPARED commits a transaction whose identifier is trans_test. openGauss=# COMMIT PREPARED 'trans_test'; ``` ## Helpful Links [PREPARE TRANSACTION](prepare_transaction.md) and [ROLLBACK PREPARED](rollback_prepared.md) --- --- url: /zh/docs/latest-lite/sql_reference/commit_prepared.md --- # COMMIT PREPARED ## 功能描述 提交一个早先为两阶段提交准备好的事务。 ## 注意事项 * 该功能仅在维护模式(GUC参数xc\_maintenance\_mode为on时)下可用。该模式谨慎打开,一般供维护人员排查问题使用,一般用户不应使用该模式。 * 命令执行者必须是该事务的创建者或系统管理员,且创建和提交操作只能在同一个会话中。 * 事务功能由数据库自动维护,不应显式使用事务功能。 ## 语法格式 ``` COMMIT PREPARED transaction_id ; COMMIT PREPARED transaction_id WITH CSN; ``` ## 参数说明 * **transaction\_id** 待提交事务的标识符。它不能和任何当前预备事务已经使用了的标识符同名。 * **CSN(commit sequence number)** 待提交事务的序列号。它是一个64位递增无符号数。 ## 示例 ``` --提交标识符为的trans_test的事务。 openGauss=# COMMIT PREPARED 'trans_test'; ``` ## 相关链接 [PREPARE TRANSACTION](prepare_transaction.md),[ROLLBACK PREPARED](rollback_prepared.md)。 --- --- url: /zh/docs/latest/sql_reference/commit_prepared.md --- # COMMIT PREPARED ## 功能描述 提交一个早先为两阶段提交准备好的事务。 ## 注意事项 * 该功能仅在维护模式(GUC参数xc\_maintenance\_mode为on时)下可用。该模式谨慎打开,一般供维护人员排查问题使用,一般用户不应使用该模式。 * 命令执行者必须是该事务的创建者或系统管理员,且创建和提交操作只能在同一个会话中。 * 事务功能由数据库自动维护,不应显式使用事务功能。 ## 语法格式 ``` COMMIT PREPARED transaction_id ; COMMIT PREPARED transaction_id WITH CSN; ``` ## 参数说明 * **transaction\_id** 待提交事务的标识符。它不能和任何当前预备事务已经使用了的标识符同名。 * **CSN(commit sequence number)** 待提交事务的序列号。它是一个64位递增无符号数。 ## 示例 ``` --提交标识符为的trans_test的事务。 openGauss=# COMMIT PREPARED 'trans_test'; ``` ## 相关链接 [PREPARE TRANSACTION](prepare_transaction.md),[ROLLBACK PREPARED](rollback_prepared.md)。 --- --- url: /en/docs/latest/database_om_guide/committing_the_upgrade_task.md --- # Committing the Upgrade Task After the upgrade is complete, if no problem is found during the verification, you can commit the upgrade task. > \[!NOTE]NOTE > Once the committal is complete, no rollback can be performed. ## Procedure 1. Log in to the node as a database user (for example, **omm**). 2. Run the following command to commit the upgrade task: ``` gs_upgradectl -t commit-upgrade -X /opt/software/GaussDB_Kernel/clusterconfig.xml ``` 3. For a rolling upgrade, upgrade all nodes before performing the upgrade commit command. --- --- url: /en/docs/latest-lite/database_om_guide/common_fault_locating_methods.md --- # Common Fault Locating Methods ## Locating OS Faults If all instances on a node are abnormal, an OS fault may have occurred. Use one of the following methods to check whether any OS fault occurs: * Log in to the node using SSH or other remote login tools. If the login fails, run the **ping** command to check the network status. * If no response is returned, the server is down or being restarted, or its network connection is abnormal. The restart takes a long time (about 20 minutes) if the system crashes due to an OS kernel panic. Try to connect the host every 5 minutes. If the connection failed 20 minutes later, the server is down or the network connection is abnormal. In this case, contact the administrator to locate the fault on site. * If ping operations succeed but SSH login fails or commands cannot be executed, the server 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 fault persists within 5 minutes, contact the administrator for further fault locating on site. * If login is successful but responses are slow, check the system running status, such as collecting system information as well as checking system version, hardware, parameter setting, and login users. The following are common commands for reference: * Use the **who** command to check online users. ``` [root@openGauss36 ~]# who root pts/0 2020-11-07 16:32 (10.70.223.238) wyc pts/1 2020-11-10 09:54 (10.70.223.222) root pts/2 2020-10-10 14:20 (10.70.223.238) root pts/4 2020-10-09 10:14 (10.70.223.233) root pts/5 2020-10-09 10:14 (10.70.223.233) root pts/7 2020-10-31 17:03 (10.70.223.222) root pts/9 2020-10-20 10:03 (10.70.220.85) ``` ``` - Use the **cat /etc/openEuler-release** and **uname -a** commands to check the system version and kernel information. ``` ``` [root@openGauss36 ~]# cat /etc/openEuler-release openEuler release 20.03 (LTS) [root@openGauss36 ~]# uname -a Linux openGauss36 4.19.90-2003.4.0.0036.oe1.aarch64 #1 SMP Mon Mar 23 19:06:43 UTC 2020 aarch64 aarch64 aarch64 GNU/Linux [root@openGauss36 ~]# ``` ```` - Use the **sysctl -a** \(run this command as user **root**\) and **cat /etc/sysctl.conf** commands to obtain system parameter information. - Use the **cat /proc/cpuinfo** and **cat /proc/meminfo** commands to obtain CPU and memory information. ``` [root@openGauss ~]# cat /proc/cpuinfo processor : 0 BogoMIPS : 200.00 Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma dcpop asimddp asimdfhm CPU implementer : 0x48 CPU architecture: 8 CPU variant : 0x1 CPU part : 0xd01 CPU revision : 0 [root@openGauss36 ~]# cat /proc/meminfo MemTotal: 534622272 kB MemFree: 253322816 kB MemAvailable: 369537344 kB Buffers: 2429504 kB Cached: 253063168 kB SwapCached: 0 kB Active: 88570624 kB Inactive: 171801920 kB Active(anon): 4914880 kB Inactive(anon): 67011456 kB Active(file): 83655744 kB Inactive(file): 104790464 kB ``` - Use the **top -H** command to query the CPU usage and check whether the CPU usage is high due to a specific process. If it is, use the **gdb** or **gstack** command to print the stack trace of this process and check whether this process is in an infinite loop. - Use the **iostat -x 1 3** command to query the I/O usage and check whether the I/O usage of the current disk is full. View the ongoing jobs to determine whether to handle the jobs with high I/O usage. - Use the **vmstat 1 3** command to query the memory usage in the current system and use the **top** command to obtain the processes with unexpectedly high memory usage. - View the OS logs \(**/var/log/messages**\) or dmseg information as user **root** to check whether errors have occurred in the OS. - The watchdog of an OS is a mechanism to ensure that the OS runs properly or exits from the infinite loop or deadlock state. If the watchdog times out \(the default value is 60s\), the system resets. ```` ## Locating Network Faults 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. Common exceptions caused by network faults are as follows: * Network error reported due to database startup failure. * Abnormal status, for example, all instances on a host are in the **UnKnown** state, or all services are switched over to standby instances. * Network connection failure. * Network disconnection reported during database sql query. * Process response failures during database connection or query execution. When a network fault occurs in a database, locate and analyze the fault by using network-related Linux command tools (such as **ping**, **ifconfig**, **netstat**, and **lsof**) and process stack viewers (such as **gdb** and **gstack**) based on database log information. This section lists common network faults and describes how to analyze and locate faults. Common faults are as follows: * Network error reported due to a startup failure **Symptom 1**: The log contains the following error information. The port may be listened on by another process. ``` LOG: could not bind socket at the 10 time, is another postmaster already running on port 54000? ``` **Solution**: Run the following command to check the process that listens on the port. Replace the port number with the actual one. ``` [root@openGauss36 ~]# netstat -anop | grep 15970 tcp 0 0 127.0.0.1:15970 0.0.0.0:* LISTEN 3920251/gaussdb off (0.00/0/0) tcp6 0 0 ::1:15970 :::* LISTEN 3920251/gaussdb off (0.00/0/0) unix 2 [ ACC ] STREAM LISTENING 197399441 3920251/gaussdb /tmp/.s.PGSQL.15970 unix 3 [ ] STREAM CONNECTED 197461142 3920251/gaussdb /tmp/.s.PGSQL.15970 ``` Forcibly stop the process that is occupying the port or change the listening port of the database based on the query result. **Symptom 2**: When the **gs\_ctl query** command is used to query status, the command output shows that the connection between the primary and standby nodes is not established. **Solution**: In openEuler, run the **systemctl status firewalld.service** command to check whether the firewall is enabled on this node. If it is enabled, run the **systemctl stop firewalld.service** command to disable it. ``` [root@openGauss36 mnt]# systemctl status firewalld.service ●firewalld.service - firewalld - dynamic firewall daemon Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled) Active: inactive (dead) Docs: man:firewalld(1) ``` The command varies according to the operating system. You can run the corresponding command to view and modify the configuration. * The database is abnormal. **Symptom**: The following problems occur on a node: * All instances are in the **Unknown** state. * All primary instances are switched to standby instances. * Errors "Connection reset by peer" and "Connection timed out" are frequently displayed. **Solution** * If you cannot connect to the faulty server through SSH, run the **ping** command on other servers to send data packages to the faulty server. If the ping operation succeeds, connection fails because resources such as memory, CPUs, and disks, on the faulty server are used up. * Connect to the faulty server through SSH and run the **/sbin/ifconfig eth***?* command every other second (replace the question mark (?) with the number indicating the position of the NIC). Check value changes of **dropped** and **errors**. If they increase rapidly, the NIC or NIC driver may be faulty. ``` [root@openGauss36 ~]# ifconfig enp125s0f0 enp125s0f0: flags=4163 mtu 1500 inet 10.90.56.36 netmask 255.255.255.0 broadcast 10.90.56.255 inet6 fe80::7be7:8038:f3dc:f916 prefixlen 64 scopeid 0x20 ether 44:67:47:7d:e6:84 txqueuelen 1000 (Ethernet) RX packets 129344246 bytes 228050833914 (212.3 GiB) RX errors 0 dropped 647228 overruns 0 frame 0 TX packets 96689431 bytes 97279775245 (90.5 GiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 ``` * Check whether the following parameters are correctly configured: ``` net.ipv4.tcp_retries1 = 3 net.ipv4.tcp_retries2 = 15 ``` * Network connection failure. **Symptom 1**: A node fails to connect to other nodes, and the "Connection refused" error is reported in the log. **Solution** * Check whether the port is incorrectly configured, resulting in that the port used for connection is not the listening port of the peer end. Check whether the port number recorded in the **postgresql.conf** configuration file of the faulty node is the same as the listening port number of the peer end. * Check whether the peer listening port is normal (for example, by running the **netstat –anp** command). * Check whether the peer process exists. ## Locating Disk Faults Common disk faults include insufficient disk space, bad blocks of disks, and unmounted disks. Disk faults such as unmount of disks damage the file system. The database management mechanism identifies this kind of faults and stops the instance, and the instance status is **Unknown**. However, disk faults such as insufficient disk space do not damage the file system. The database management mechanism cannot identify this kind of faults and service processes exit unexpectedly when accessing a faulty disk. Failures cover database startup, checksum verification, page read and write operation, and page verification. * For faults that result in file system damages, the instance status is **Unknown** when you view the host status. Perform the following operations to locate the disk fault: * Check the logs. If the logs contain information similar to "data path disc writable test failed", the file system is damaged. * The possible cause of file system damage may be unmounted disks. Run the **ls –l** command and you can view that the disk directory permission is abnormal, as shown in the following: * Another possible cause is that the disk has bad blocks. In this case, the OS rejects read and write operations to protect the file system. You can use a bad block check tool, for example, **badblocks**, to check whether bad blocks exist. ``` [root@openeuler123 mnt]# badblocks /dev/sdb1 -s -v Checking blocks 0 to 2147482623 Checking for bad blocks (read-only test): done Pass completed, 0 bad blocks found. (0/0/0 errors) ``` * For faults that do not damage the file system, the service process will report an exception and exit when it accesses the faulty disk. Perform the following operations to locate the disk fault: View logs. The log contains read and write errors, such as "No space left on device" and "invalid page header n block 122838 of relation base/16385/152715". 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@openeuler123 mnt]# df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 255G 0 255G 0% /dev tmpfs 255G 35M 255G 1% /dev/shm tmpfs 255G 57M 255G 1% /run tmpfs 255G 0 255G 0% /sys/fs/cgroup /dev/mapper/openeuler-root 196G 8.8G 178G 5% / tmpfs 255G 1.0M 255G 1% /tmp /dev/sda2 9.8G 144M 9.2G 2% /boot /dev/sda1 10G 5.8M 10G 1% /boot/efi /dev/mapper/openeuler-home 1.5T 69G 1.4T 5% /home tmpfs 51G 0 51G 0% /run/user/0 tmpfs 51G 0 51G 0% /run/user/1004 /dev/sdb1 2.0T 169G 1.9T 9% /data ``` ## Locating Database Faults * Logs. Database logs record the operations (starting, running, and stopping) on servers. Database users can view logs to quickly locate fault causes and rectify the faults accordingly. * View. A database provides different views to display its internal status. When locating a fault, you can use: * **pg\_stat\_activity**: shows the status of each session on the current instance. * **pg\_thread\_wait\_status**: shows the wait events of each thread on the current instance. * **pg\_locks**: shows the status of locks on the current instance. * Core files. Abnormal termination of a database process will trigger a core dump. A core dump file helps locate faults and determine fault causes. Once a core dump occurs during process running, collect the core file immediately for further analyzing and locating the fault. * The OS performance is affected, especially when errors occur frequently. * The OS disk space will be occupied by core files. Therefore, after core files are discovered, locate and rectify the errors as soon as possible. The OS is delivered with 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. * Set the path for generating core files. Modify the **/proc/sys/kernel/core\_pattern** file. ``` [root@openeuler123 mnt]# cat /proc/sys/kernel/core_pattern /data/jenkins/workspace/openGaussInstall/dbinstall/cluster/corefile/core-%e-%p-%t ``` --- --- url: /en/docs/latest/resource_pooling/common_fault_locating_methods.md --- # Common Fault Locating Methods ## **Locating OS Faults** If all instances on a node are abnormal, an OS fault may have occurred. Use one of the following methods to check whether any OS fault occurs: * Log in to the node using SSH or other remote login tools. If the login fails, run the **ping** command to check the network status. * If no response is returned, the server is down or being restarted, or its network connection is abnormal. The restart takes a long time (about 20 minutes) if the system crashes due to an OS kernel panic. Try to connect the host every 5 minutes. If the connection failed 20 minutes later, the server is down or the network connection is abnormal. In this case, contact the administrator to locate the fault on site. * If ping operations succeed but SSH login fails or commands cannot be executed, the server 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 fault persists within 5 minutes, contact the administrator for further fault locating on site. * If login is successful but responses are slow, check the system running status, such as collecting system information as well as checking system version, hardware, parameter setting, and login users. The following are common commands for reference: * Use the **who** command to check online users. ``` [root@openGauss36 ~]# who root pts/0 2020-11-07 16:32 (10.70.223.238) wyc pts/1 2020-11-10 09:54 (10.70.223.222) root pts/2 2020-10-10 14:20 (10.70.223.238) root pts/4 2020-10-09 10:14 (10.70.223.233) root pts/5 2020-10-09 10:14 (10.70.223.233) root pts/7 2020-10-31 17:03 (10.70.223.222) root pts/9 2020-10-20 10:03 (10.70.220.85) ``` ``` - Use the **cat /etc/openEuler-release** and **uname -a** commands to check the system version and kernel information. ``` ``` [root@openGauss36 ~]# cat /etc/openEuler-release openEuler release 20.03 (LTS) [root@openGauss36 ~]# uname -a Linux openGauss36 4.19.90-2003.4.0.0036.oe1.aarch64 #1 SMP Mon Mar 23 19:06:43 UTC 2020 aarch64 aarch64 aarch64 GNU/Linux [root@openGauss36 ~]# ``` ```` - Use the **sysctl -a** \(run this command as user **root**\) and **cat /etc/sysctl.conf** commands to obtain system parameter information. - Use the **cat /proc/cpuinfo** and **cat /proc/meminfo** commands to obtain CPU and memory information. ``` [root@openGauss36 ~]# cat /proc/cpuinfo processor : 0 BogoMIPS : 200.00 Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma dcpop asimddp asimdfhm CPU implementer : 0x48 CPU architecture: 8 CPU variant : 0x1 CPU part : 0xd01 CPU revision : 0 [root@openGauss36 ~]# cat /proc/meminfo MemTotal: 534622272 kB MemFree: 253322816 kB MemAvailable: 369537344 kB Buffers: 2429504 kB Cached: 253063168 kB SwapCached: 0 kB Active: 88570624 kB Inactive: 171801920 kB Active(anon): 4914880 kB Inactive(anon): 67011456 kB Active(file): 83655744 kB Inactive(file): 104790464 kB ``` - Use the **top -H** command to query the CPU usage and check whether the CPU usage is high due to a specific process. If it is, use the **gdb** or **gstack** command to print the stack trace of this process and check whether this process is in an infinite loop. - Use the **iostat -x 1 3** command to query the I/O usage and check whether the I/O usage of the current disk is full. View the ongoing jobs to determine whether to handle the jobs with high I/O usage. - Use the **vmstat 1 3** command to query the memory usage in the current system and use the **top** command to obtain the processes with unexpectedly high memory usage. - View the OS logs \(**/var/log/messages**\) or dmseg information as user **root** to check whether errors have occurred in the OS. - The watchdog of an OS is a mechanism to ensure that the OS runs properly or exits from the infinite loop or deadlock state. If the watchdog times out \(the default value is 60s\), the system resets. ```` ## **Locating Network Faults** 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. Common exceptions caused by network faults are as follows: * Network error reported due to database startup failure. * Abnormal status, for example, all instances on a host are in the **UnKnown** state, or all services are switched over to standby instances. * Network connection failure. * Network disconnection reported during database sql query. * Process response failures during database connection or query execution. When a network fault occurs in a database, locate and analyze the fault by using network-related Linux command tools (such as **ping**, **ifconfig**, **netstat**, and **lsof**) and process stack viewers (such as **gdb** and **gstack**) based on database log information. This section lists common network faults and describes how to analyze and locate faults. Common faults are as follows: * Network error reported due to a startup failure **Symptom 1**: The log contains the following error information. The port may be listened on by another process. ``` LOG: could not bind socket at the 10 time, is another postmaster already running on port 54000? ``` **Solution**: Run the following command to check the process that listens on the port. Replace the port number with the actual one. ``` [root@openGauss36 ~]# netstat -anop | grep 15970 tcp 0 0 127.0.0.1:15970 0.0.0.0:* LISTEN 3920251/gaussdb off (0.00/0/0) tcp6 0 0 ::1:15970 :::* LISTEN 3920251/gaussdb off (0.00/0/0) unix 2 [ ACC ] STREAM LISTENING 197399441 3920251/gaussdb /tmp/.s.PGSQL.15970 unix 3 [ ] STREAM CONNECTED 197461142 3920251/gaussdb /tmp/.s.PGSQL.15970 ``` Forcibly stop the process that is occupying the port or change the listening port of the database based on the query result. **Symptom 2**: When the **gs\_om -t status --detail** command is used to query status, the command output shows that the connection between the primary and standby nodes is not established. **Solution**: In openEuler, run the **systemctl status firewalld.service** command to check whether the firewall is enabled on this node. If it is enabled, run the **systemctl stop firewalld.service** command to disable it. ``` [root@openGauss36 mnt]# systemctl status firewalld.service ●firewalld.service - firewalld - dynamic firewall daemon Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled) Active: inactive (dead) Docs: man:firewalld(1) ``` The command varies according to the operating system. You can run the corresponding command to view and modify the configuration. * The database is abnormal. **Symptom**: The following problems occur on a node: * All instances are in the **Unknown** state. * All primary instances are switched to standby instances. * Errors "Connection reset by peer" and "Connection timed out" are frequently displayed. **Solution** * If you cannot connect to the faulty server through SSH, run the **ping** command on other servers to send data packages to the faulty server. If the ping operation succeeds, connection fails because resources such as memory, CPUs, and disks, on the faulty server are used up. * Connect to the faulty server through through SSH and run the **/sbin/ifconfig eth***?* command every other second (replace the question mark (?) with the number indicating the position of the NIC). Check value changes of **dropped** and **errors**. If they increase rapidly, the NIC or NIC driver may be faulty. ``` [root@openGauss36 ~]# ifconfig enp125s0f0 enp125s0f0: flags=4163 mtu 1500 inet 10.90.56.36 netmask 255.255.255.0 broadcast 10.90.56.255 inet6 fe80::7be7:8038:f3dc:f916 prefixlen 64 scopeid 0x20 ether 44:67:47:7d:e6:84 txqueuelen 1000 (Ethernet) RX packets 129344246 bytes 228050833914 (212.3 GiB) RX errors 0 dropped 647228 overruns 0 frame 0 TX packets 96689431 bytes 97279775245 (90.5 GiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 ``` * Check whether the following parameters are correctly configured: ``` net.ipv4.tcp_retries1 = 3 net.ipv4.tcp_retries2 = 15 ``` * Network connection failure. **Symptom 1**: A node fails to connect to other nodes, and the "Connection refused" error is reported in the log. **Solution** * Check whether the port is incorrectly configured, resulting in that the port used for connection is not the listening port of the peer end. Check whether the port number recorded in the **postgresql.conf** configuration file of the faulty node is the same as the listening port number of the peer end. * Check whether the peer listening port is normal (for example, by running the **netstat –anp** command). * Check whether the peer process exists. **Symptom 2**: When SQL operations are performed on the database, the connection descriptor fails to be obtained. The following error information is displayed: ``` WARNING: 29483313: incomplete message from client:4905,9 WARNING: 29483313: failed to receive connDefs at the time:1. ERROR: 29483313: failed to get pooled connections ``` In logs, locate and view the log content before the preceding error messages, which are generated due to incorrect active and standby information. Error details are displayed as follows. ``` FATAL: dn_6001_6002: can not accept connection in pending mode. FATAL: dn_6001_6002: the database system is starting up FATAL: dn_6009_6010: can not accept connection in standby mode. ``` **Solution** * Run the **gs\_om -t status --detail** command to query the status and check whether an primary/standby switchover has occurred. Reset the instance status. * In addition, check whether a core dump or restart occurs on the node that fails to be connected. In the om log, check whether restart occurs. * Network disconnection reported during database sql query. **Symptom 1**: The query fails, and the following error information is displayed: ``` ERROR: dn_6065_6066: Failed to read response from Datanodes. Detail: Connection reset by peer. Local: dn_6065_6066 Remote: dn_6023_6024 ERROR: Failed to read response from Datanodes Detail: Remote close socket unexpectedly ERROR: dn_6155_6156: dn_6151_6152: Failed to read vector response from Datanodes ``` If the connection fails, the error information may be as follows: ``` ERROR: Distribute Query unable to connect 10.145.120.79:14600 [Detail:stream connect connect() fail: Connection timed out ERROR: Distribute Query unable to connect 10.144.192.214:12600 [Detail:receive accept response fail: Connection timed out ``` **Solution** 1. Use **gs\_check** to check whether the network configuration meets requirements. For network check, see "Server Tools > gs\_check" in the *Tool Reference*. 2. Check whether a process core dump, restart, or switchover occurs. 3. If problems still exist, contact network technical engineers. ## **Locating Disk Faults** Common disk faults include insufficient disk space, bad blocks of disks, and unmounted disks. Disk faults such as unmount of disks damage the file system. The cluster management mechanism identifies this kind of faults and stops the instance, and the instance status is **Unknown**. However, disk faults such as insufficient disk space do not damage the file system. The cluster management mechanism cannot identify this kind of faults and service processes exit abnormally when accessing a faulty disk. Failures cover database startup, checksum verification, page read and write operation, and page verification. * For faults that result in file system damages, the instance status is **Unknown** when you view the host status. Perform the following operations to locate the disk fault: * Check the logs. If the logs contain information similar to "data path disc writable test failed", the file system is damaged. * The possible cause of file system damage may be unmounted disks. Run the **ls –l** command and you can view that the disk directory permission is abnormal, as shown in the following: * Another possible cause is that the disk has bad blocks. In this case, the OS rejects read and write operations to protect the file system. You can use a bad block check tool, for example, **badblocks**, to check whether bad blocks exist. ``` [root@openeuler123 mnt]# badblocks /dev/sdb1 -s -v Checking blocks 0 to 2147482623 Checking for bad blocks (read-only test): done Pass completed, 0 bad blocks found. (0/0/0 errors) ``` * For faults that do not damage the file system, the service process will report an exception and exit when it accesses the faulty disk. Perform the following operations to locate the disk fault: View logs. The log contains read and write errors, such as "No space left on device" and "invalid page header n block 122838 of relation base/16385/152715". 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@openeuler123 mnt]# df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 255G 0 255G 0% /dev tmpfs 255G 35M 255G 1% /dev/shm tmpfs 255G 57M 255G 1% /run tmpfs 255G 0 255G 0% /sys/fs/cgroup /dev/mapper/openeuler-root 196G 8.8G 178G 5% / tmpfs 255G 1.0M 255G 1% /tmp /dev/sda2 9.8G 144M 9.2G 2% /boot /dev/sda1 10G 5.8M 10G 1% /boot/efi /dev/mapper/openeuler-home 1.5T 69G 1.4T 5% /home tmpfs 51G 0 51G 0% /run/user/0 tmpfs 51G 0 51G 0% /run/user/1004 /dev/sdb1 2.0T 169G 1.9T 9% /data ``` ## **Locating Database Faults** * Logs. Database logs record the operations (starting, running, and stopping) on servers. Database users can view logs to quickly locate fault causes and rectify the faults accordingly. * View. A database provides different views to display its internal status. When locating a fault, you can use: * **pg\_stat\_activity**: shows the status of each session on the current instance. * **pg\_thread\_wait\_status**: shows the wait events of each thread on the current instance. * **pg\_locks**: shows the status of locks on the current instance. * Core files. Abnormal termination of a database process will trigger a core dump. A core dump file helps locate faults and determine fault causes. Once a core dump occurs during process running, collect the core file immediately for further analyzing and locating the fault. * The OS performance is affected, especially when errors occur frequently. * The OS disk space will be occupied by core files. Therefore, after core files are discovered, locate and rectify the errors as soon as possible. The OS is delivered with 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. * Set the path for generating core files. Modify the **/proc/sys/kernel/core\_pattern** file. ``` [root@openeuler123 mnt]# cat /proc/sys/kernel/core_pattern /data/jenkins/workspace/openGaussInstall/dbinstall/cluster/corefile/core-%e-%p-%t ``` --- --- url: /en/docs/latest-lite/developer_guide/common_jdbc_parameters.md --- # Common JDBC Parameters ## targetServerType **Principle**: If the value is **master**, JDBC attempts to connect to the IP addresses configured in the string in sequence until the primary node in the cluster is connected. If the value is **slave**, JDBC attempts to connect to the IP addresses configured in the string in sequence until the standby node in the cluster is connected. The query statement is **select local\_role, db\_state from pg\_stat\_get\_stream\_replications();**. **Suggestion**: You are advised to set this parameter to **master** for services with write operations to ensure that the primary node can be properly connected after a primary/standby switchover. However, if the standby node is not completely promoted to primary during the primary/standby switchover, the connection cannot be established. As a result, service statements cannot be executed. ## hostRecheckSeconds **Principle**: Specifies the period during which the DN list stored in JDBC remains trusted. Within this period, the DN list is directly read from the host addresses stored in JDBC. After that (or the primary node fails to be connected within the specified period), the node status in the DN list is updated and other IP addresses are connected. **Suggestion**: The default value is **10s**. You are advised to adjust the value based on service requirements. This parameter is used together with the **targetServerType** parameter. ## allowReadOnly **Principle**: Checks whether the transaction access mode can be modified through **setReadOnly**. If the value is **true**, the transaction access mode can be modified. If the value is **false**, the transaction access mode cannot be modified through this interface. To modify the transaction access mode, execute **SET SESSION CHARACTERISTICS AS TRANSACTION + READ ONLY / READ WEITE**. **Suggestion**: The default value **true** is recommended. ## fetchsize **Principle**: After **fetchsize** is set to *n* and the database server executes a query, JDBC communicates with the server when the invoker executes **resultset.next()**, fetches *n* pieces of data to the JDBC client, and returns the first piece of data to the invoker. When the invoker fetches the (*n*+1)th data record, the invoker fetches data from the database server again. **Function**: This prevents the database from transmitting all results to the client at a time, which exhausts the memory resources of the client. **Suggestion**: You are advised to set this parameter based on the amount of data queried by services and the memory of the client. When setting **fetchsize**, disable automatic commit (**autocommit**=**false**). Otherwise, the setting of **fetchsize** does not take effect. ## defaultRowFetchSize **Function**: The default value of **fetchsize** is **0**. Setting **defaultRowFetchSize** will change the default value of **fetchsize**. ## batchMode **Function**: This parameter specifies whether to connect the database in batch mode. The default value is **on**. After the function is enabled, the batch update performance is improved, and the return value is also batch updated. For example, if three data records are inserted in batches, the return value is **\[3,0,0]** when the function is enabled, and the return value is **\[1,1,1]** when the function is disabled. **Suggestion**: If the service framework (such as hibernate) checks the return value during batch update, you can set this parameter to solve the problem. ## loginTimeout **Function**: Controls the time for establishing a connection with the database. The time includes connection timeout and socket timeout. If the time elapsed exceeds the threshold, the connection exits. The calculation formula is as follows: **loginTimeout** = **connectiontimeout** x Number of nodes + Connection authentication time + Initialization statement execution time. **Suggestion**: After this parameter is set, an asynchronous thread is started each time a connection is established. If there are a large number of connections, the pressure on the client may increase. If this parameter needs to be set, you are advised to set it to 3 x **connectTimeout** in centralized deployment to prevent connection failures when the network is abnormal and the third IP address is the IP address of the primary node. > \[!TIP]NOTICE > After this parameter is set, for multiple IP addresses, the value of this parameter is the time for attempting to connect to all the IP addresses. If this parameter is set to a small value, the subsequent IP addresses may fail to be connected. For example, if three IP addresses are set, **logintimeout** is set to **5s**, and it takes 5s to connect to the first two IP addresses, the third IP address cannot be connected. In the centralized deployment environment, the last IP address is the IP address of the primary node. As a result, the automatic search for the primary node may fail. ## cancelSignalTimeout **Function**: Canceling messages may cause a block. This parameter controls **connectTimeout** and **socketTimeout** in a cancel message, in seconds. in seconds. It is used to prevent timeout detection from being performed when the connection is canceled due to timeout. **Suggestion**: The default value is **10s**. You are advised to adjust the value based on service requirements. ## connectTimeout **Function**: Controls the socket timeout threshold during connection setup. In this case, this timeout threshold is the time when the JDBC connects to the database through the socket, not the time when the connection object is returned. If the time elapsed exceeds the threshold, JDBC searches for the next IP address. **Suggestion**: This parameter determines the maximum timeout interval for establishing a TCP connection on each node. If a network fault occurs on a node, JDBC attempts to connect to the node until the time specified by **connectTimeout** elapses, and then attempts to connect to the next node. Considering the network jitter and delay, you are advised to set this parameter to **3s**. ## socketTimeout **Function**: Controls the timeout threshold of socket operations. If the time of executing service statements or reading data streams from the network exceeds the threshold (that is, when the statement execution time exceeds the specified threshold and no data is returned), the connection is interrupted. **Suggestion**: This parameter specifies the maximum execution time of a single SQL statement. If the execution time of a single SQL statement exceeds the value of this parameter, an error is reported and the statement exits. You are advised to set this parameter based on service characteristics. ## autosave **Function**: If the value is **always**, you can set a savepoint before each statement in a transaction. If an error is reported during statement execution in a transaction, the system returns to the latest savepoint. In this way, subsequent statements in the transaction can be properly executed and committed. **Suggestion**: You are not advised to set this parameter because the performance deteriorates severely. ## currentSchema **Function**: Specifies the schema of the current connection. If this parameter is not set, the default schema is the username used for the connection. **Suggestion**: You are advised to set this parameter to the schema where the service data is located. ## prepareThreshold **Function**: The default value is **5**. If an SQL statement is executed for multiple consecutive times in a session and the number of execution times specified by **prepareThreshold** is reached, JDBC does not send the PARSE command to the SQL statement but caches the SQL statement to improve the execution speed. **Suggestion**: The default value is **5**. Adjust the value based on service requirements. ## preparedStatementCacheQueries **Function**: Specifies the number of queries cached in each connection. The default value is **256**. If more than 256 different queries are used in the **prepareStatement()** call, the least recently used query cache will be discarded. **Suggestion**: The default value is **256**. Adjust the value based on service requirements. This parameter is used together with **prepareThreshold**. ## blobMode **Function**: Sets the **setBinaryStream** method to assign values to different types of data. The value **on** indicates that values are assigned to BLOB data. The value **off** indicates that values are assigned to bytea data. The default value is **on**. For example, you can assign values to parameters in the **preparestatement** and **callablestatement** objects. **Suggestion**: The default value is **true**. ## setAutocommit **Function**: If the value is **true**, a transaction is automatically started when each statement is executed. After the execution is complete, the transaction is automatically committed. That is, each statement is a transaction. If the value is **false**, a transaction is automatically started. However, you need to manually commit the transaction. **Suggestion**: Adjust the value based on service characteristics. If autocommit needs to be disabled for performance or other purposes, the application must ensure that transactions can be committed. For example, explicitly commit translations after specifying service SQL statements. Particularly, ensure that all transactions are committed before the client exits. --- --- url: /en/docs/latest/developer_guide/common_jdbc_parameters.md --- # Common JDBC Parameters ## targetServerType **Principle**: If the value is **master**, JDBC attempts to connect to the IP addresses configured in the string in sequence until the primary node in the cluster is connected. If the value is **slave**, JDBC attempts to connect to the IP addresses configured in the string in sequence until the standby node in the cluster is connected. The query statement is **select local\_role, db\_state from pg\_stat\_get\_stream\_replications();**. **Suggestion**: You are advised to set this parameter to **master** for services with write operations to ensure that the primary node can be properly connected after a primary/standby switchover. However, if the standby node is not completely promoted to primary during the primary/standby switchover, the connection cannot be established. As a result, service statements cannot be executed. ## hostRecheckSeconds **Principle**: Specifies the period during which the DN list stored in JDBC remains trusted. Within this period, the DN list is directly read from the host addresses stored in JDBC. After that (or the primary node fails to be connected within the specified period), the node status in the DN list is updated and other IP addresses are connected. **Suggestion**: The default value is **10s**. You are advised to adjust the value based on service requirements. This parameter is used together with the **targetServerType** parameter. ## allowReadOnly **Principle**: Checks whether the transaction access mode can be modified through **setReadOnly**. If the value is **true**, the transaction access mode can be modified. If the value is **false**, the transaction access mode cannot be modified through this interface. To modify the transaction access mode, execute **SET SESSION CHARACTERISTICS AS TRANSACTION + READ ONLY / READ WEITE**. **Suggestion**: The default value **true** is recommended. ## fetchsize **Principle**: After **fetchsize** is set to *n* and the database server executes a query, JDBC communicates with the server when the invoker executes **resultset.next()**, fetches *n* pieces of data to the JDBC client, and returns the first piece of data to the invoker. When the invoker fetches the (*n*+1)th data record, the invoker fetches data from the database server again. **Function**: This prevents the database from transmitting all results to the client at a time, which exhausts the memory resources of the client. **Suggestion**: You are advised to set this parameter based on the amount of data queried by services and the memory of the client. When setting **fetchsize**, disable automatic commit (**autocommit**=**false**). Otherwise, the setting of **fetchsize** does not take effect. ## defaultRowFetchSize **Function**: The default value of **fetchsize** is **0**. Setting **defaultRowFetchSize** will change the default value of **fetchsize**. ## batchMode **Function**: This parameter specifies whether to connect the database in batch mode. The default value is **on**. After the function is enabled, the batch update performance is improved, and the return value is also batch updated. For example, if three data records are inserted in batches, the return value is **\[3,0,0]** when the function is enabled, and the return value is **\[1,1,1]** when the function is disabled. **Suggestion**: If the service framework (such as hibernate) checks the return value during batch update, you can set this parameter to solve the problem. ## loginTimeout **Function**: Controls the time for establishing a connection with the database. The time includes connection timeout and socket timeout. If the time elapsed exceeds the threshold, the connection exits. The calculation formula is as follows: **loginTimeout** = **connectiontimeout** x Number of nodes + Connection authentication time + Initialization statement execution time. **Suggestion**: After this parameter is set, an asynchronous thread is started each time a connection is established. If there are a large number of connections, the pressure on the client may increase. If this parameter needs to be set, you are advised to set it to 3 x **connectTimeout** in centralized deployment to prevent connection failures when the network is abnormal and the third IP address is the IP address of the primary node. > \[!TIP]NOTICE > After this parameter is set, for multiple IP addresses, the value of this parameter is the time for attempting to connect to all the IP addresses. If this parameter is set to a small value, the subsequent IP addresses may fail to be connected. For example, if three IP addresses are set, **logintimeout** is set to **5s**, and it takes 5s to connect to the first two IP addresses, the third IP address cannot be connected. In the centralized deployment environment, the last IP address is the IP address of the primary node. As a result, the automatic search for the primary node may fail. ## cancelSignalTimeout **Function**: Cancel messages may cause a block. This parameter controls **connectTimeout** and **socketTimeout** in a cancel message, in seconds. It is used to prevent timeout detection from being performed when the connection is canceled due to timeout. **Suggestion**: The default value is **10s**. You are advised to adjust the value based on service requirements. ## connectTimeout **Function**: Controls the socket timeout threshold during connection setup. In this case, this timeout threshold is the time when the JDBC connects to the database through the socket, not the time when the connection object is returned. If the time elapsed exceeds the threshold, JDBC searches for the next IP address. **Suggestion**: This parameter determines the maximum timeout interval for establishing a TCP connection on each node. If a network fault occurs on a node, JDBC attempts to connect to the node until the time specified by **connectTimeout** elapses, and then attempts to connect to the next node. Considering the network jitter and delay, you are advised to set this parameter to **3s**. ## socketTimeout **Function**: Controls the timeout threshold of socket operations. If the time of executing service statements or reading data streams from the network exceeds the threshold (that is, when the statement execution time exceeds the specified threshold and no data is returned), the connection is interrupted. **Suggestion**: This parameter specifies the maximum execution time of a single SQL statement. If the execution time of a single SQL statement exceeds the value of this parameter, an error is reported and the statement exits. You are advised to set this parameter based on service characteristics. ## autosave **Function**: If the value is **always**, you can set a savepoint before each statement in a transaction. If an error is reported during statement execution in a transaction, the system returns to the latest savepoint. In this way, subsequent statements in the transaction can be properly executed and committed. **Suggestion**: You are not advised to set this parameter because the performance deteriorates severely. ## currentSchema **Function**: Specifies the schema of the current connection. If this parameter is not set, the default schema is the username used for the connection. **Suggestion**: You are advised to set this parameter to the schema where the service data is located. ## prepareThreshold **Function**: The default value is **5**. If an SQL statement is executed for multiple consecutive times in a session and the number of execution times specified by **prepareThreshold** is reached, JDBC does not send the PARSE command to the SQL statement but caches the SQL statement to improve the execution speed. **Suggestion**: The default value is **5**. Adjust the value based on service requirements. ## preparedStatementCacheQueries **Function**: Specifies the number of queries cached in each connection. The default value is **256**. If more than 256 different queries are used in the **prepareStatement()** call, the least recently used query cache will be discarded. **Suggestion**: The default value is **256**. Adjust the value based on service requirements. This parameter is used together with **prepareThreshold**. ## blobMode **Function**: Sets the **setBinaryStream** method to assign values to different types of data. The value **on** indicates that values are assigned to BLOB data. The value **off** indicates that values are assigned to bytea data. The default value is **on**. For example, you can assign values to parameters in the **preparestatement** and **callablestatement** objects. **Suggestion**: The default value is **true**. ## setAutocommit **Function**: If the value is **true**, a transaction is automatically started when each statement is executed. After the execution is complete, the transaction is automatically committed. That is, each statement is a transaction. If the value is **false**, a transaction is automatically started. However, you need to manually commit the transaction. **Suggestion**: Adjust the value based on service characteristics. If autocommit needs to be disabled for performance or other purposes, the application must ensure that transactions can be committed. For example, explicitly commit translations after specifying service SQL statements. Particularly, ensure that all transactions are committed before the client exits. --- --- url: >- /en/docs/latest/database_administration_guide/opengauss_common_primary_standby_deployment_solutions.md --- # Common Primary/Standby Deployment Solutions ## Single-Center Deployment **Figure 1** Single-center deployment Networking features: If a single AZ is deployed, one synchronous standby node and one asynchronous standby node can be configured. Advantages: 1. Three nodes are equivalent. If any node is faulty, the other nodes can still provide services. 2. The cost is low. Disadvantages: The high availability (HA) is low. If an AZ-level fault occurs, you can only restore the entire node. Applicability: Applicable to service systems that have low requirements on HA. ## Intra-City Dual-Center Deployment **Figure 2** Intra-city dual-center deployment Networking features: Two intra-city AZs are more reliable than a single AZ. A synchronous standby node can be configured for the primary center and the intra-city center respectively. Advantages: 1. Intra-city synchronous replication. If one data center is faulty, the other data center can still provide services without data loss. RPO = 0. 2. The cost is reasonable. Disadvantages: 1. The intra-city distance should not be too long. It is recommended that the distance be within 70 km. The total latency caused by excessive read/write times should be considered during service design. 2. Remote DR is not supported. Applicability: Applicable to common service systems. ## Two-City Three-DC Deployment **Figure 3** Two-city three-dc deployment Networking features: In the two-city three-DC deployment, each AZ must have at least one synchronous standby node. The cluster reliability can reach the highest level when the number of cities and data centers increases. Advantages: It supports zero data loss in remote DR, and has the highest reliability. RPO = 0. Disadvantages: 1. If the remote DR distance is long and synchronous standby node is configured in the remote center, the performance may be affected. 2. The cost is relatively high. Applicability: Applicable to core and important service systems. ## Two-City Three-DC Streaming DR Solution **Figure 4** Two-city three-DC streaming DR solution Networking features: Two independent clusters are deployed in the dual-cluster DR solution. The primary and DR cluster networking modes can be selected as required. The DR cluster selects the first standby DN to connect to the primary DN of the primary cluster. In the DR cluster, the first standby DN is connected in cascading standby mode. Advantages: 1. The primary cluster has the advantage of single-cluster networking. You need to manually switch to the standby cluster only when the primary cluster is unavailable. 2. There is only one cross-cluster (remote) replication link regardless of whether a DR switchover occurs. Therefore, less network bandwidth is occupied. 3. The networking is more flexible. The primary cluster and DR cluster can use different networking modes. Disadvantages: 1. DR clusters need to be added, increasing costs. 2. Remote DR RPO > 0 Applicability: Applicable to core and important service systems. For more information, see [Two-City Three-DC DR](two_city_three_dc_dr.md). > \[!NOTE]NOTE > > The preceding deployments are typical solutions. You can adjust the deployment solutions based on actual service scenarios, for example, adding or deleting standby nodes, adjusting the number of centers, properly deploying synchronous and asynchronous standby nodes, and properly using cascaded standby nodes. --- --- url: /en/docs/latest-lite/database_reference/communication_library_parameters.md --- # Communication Library Parameters This section describes parameter settings and value ranges for communication libraries. ## tcp\_keepalives\_idle **Parameter description**: Specifies the interval for transmitting keepalive signals on an OS that supports the **TCP\_KEEPIDLE** socket option. If no keepalive signal is transmitted, the connection is in idle mode. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * If the OS does not support **TCP\_KEEPIDLE**, set this parameter to **0**. > * The parameter is ignored on an OS where connections are established using the Unix domain socket. > * If this parameter is set to **0**, the system value is used. > * This parameter is not shared among different sessions. That is, different session connections may have different values. > * The parameter value in the current session connection, not the value of the GUC copy, is displayed. **Value range:** 0 to 3600. The unit is s. **Default value**: **0** ## tcp\_keepalives\_interval **Parameter description:** Specifies the response time before retransmission on an OS that supports the **TCP\_KEEPINTVL** socket option. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: 0 to 180. The unit is s. **Default value**: **300** > \[!TIP]NOTICE > > * If the OS does not support **TCP\_KEEPINTVL**, set this parameter to **0**. > * The parameter is ignored on an OS where connections are established using the Unix domain socket. > * If this parameter is set to **0**, the system value is used. > * This parameter is not shared among different sessions. That is, different session connections may have different values. > * The parameter value in the current session connection, not the value of the GUC copy, is displayed. ## tcp\_keepalives\_count **Parameter description**: Specifies the number of keepalive signals that can be waited before the openGauss server is disconnected from the client on an OS that supports the **TCP\_KEEPCNT** socket option. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * If the OS does not support **TCP\_KEEPCNT**, set this parameter to **0**. > * The parameter is ignored on an OS where connections are established using the Unix domain socket. > * If this parameter is set to **0**, the system value is used. > * This parameter is not shared among different sessions. That is, different session connections may have different values. > * The parameter value in the current session connection, not the value of the GUC copy, is displayed. **Value range**: 0 to 100. **0** indicates that the connection is immediately broken if openGauss does not receive a keepalived signal from the client. **Default value:** **0** ## comm\_proxy\_attr **Parameter description**: Specifies the parameters related to the communication proxy library. > \[!NOTE]NOTE > > * This parameter applies only to the centralized ARM standalone system running EulerOS 2.9. > * This function takes effect when the thread pool is enabled, that is, **enable\_thread\_pool** is set to **on**. > * When setting this parameter, you need to set the GUC parameter **local\_bind\_address** to the IP address of the NIC of the **libos\_kni**. > * **Parameter template**: comm\_proxy\_attr = '{enable\_libnet:true, enable\_dfx:false, numa\_num:4, numa\_bind:\[\[30,31],\[62,63],\[94,95],\[126,127]]}' > * Parameters that need to be configured include: > * **enable\_libnet**: whether to enable the user-mode protocol. The options are as follows: **true** and **false**. > * **enable\_dfx**: whether to enable the communication proxy library view. The options are as follows: **true** and **false**. > * **numa\_num**: number of NUMA nodes in the system. 2P and 4P servers are supported. The value can be: **4** or **8**. > * **numa\_bind**: core binding parameter of the agent thread. Each numa has two CPUs. There are a total of **numa\_num** groups. The value range is as follows: \[0, Number of CPUs – 1]. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string, consisting of one or more characters **Default value**: **none** --- --- url: /en/docs/latest/database_reference/communication_library_parameters.md --- # Communication Library Parameters This section describes parameter settings and value ranges for communication libraries. ## tcp\_keepalives\_idle **Parameter description**: Specifies the interval for transmitting keepalive signals on an OS that supports the **TCP\_KEEPIDLE** socket option. If no keepalive signal is transmitted, the connection is in idle mode. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * If the OS does not support **TCP\_KEEPIDLE**, set this parameter to **0**. > * The parameter is ignored on an OS where connections are established using the Unix domain socket. > * If this parameter is set to **0**, the system value is used. > * This parameter is not shared among different sessions. That is, different session connections may have different values. > * The parameter value in the current session connection, not the value of the GUC copy, is displayed. **Value range:** 0 to 3600. The unit is s. **Default value**: **0** ## tcp\_keepalives\_interval **Parameter description:** Specifies the response time before retransmission on an OS that supports the **TCP\_KEEPINTVL** socket option. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: 0 to 180. The unit is s. **Default value**: **300** > \[!TIP]NOTICE > > * If the OS does not support **TCP\_KEEPINTVL**, set this parameter to **0**. > * The parameter is ignored on an OS where connections are established using the Unix domain socket. > * If this parameter is set to **0**, the system value is used. > * This parameter is not shared among different sessions. That is, different session connections may have different values. > * The parameter value in the current session connection, not the value of the GUC copy, is displayed. ## tcp\_keepalives\_count **Parameter description**: Specifies the number of keepalive signals that can be waited before the openGauss server is disconnected from the client on an OS that supports the **TCP\_KEEPCNT** socket option. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!TIP]NOTICE > > * If the OS does not support **TCP\_KEEPCNT**, set this parameter to **0**. > * The parameter is ignored on an OS where connections are established using the Unix domain socket. > * If this parameter is set to **0**, the system value is used. > * This parameter is not shared among different sessions. That is, different session connections may have different values. > * The parameter value in the current session connection, not the value of the GUC copy, is displayed. **Value range**: 0 to 100. **0** indicates that the connection is immediately broken if openGauss does not receive a keepalived signal from the client. **Default value:** **0** ## comm\_proxy\_attr **Parameter description**: Specifies the parameters related to the communication proxy library. > \[!NOTE]NOTE > > * This parameter applies only to the centralized ARM standalone system running EulerOS 2.9. > * This function takes effect when the thread pool is enabled, that is, **enable\_thread\_pool** is set to **on**. > * When setting this parameter, you need to set the GUC parameter **local\_bind\_address** to the IP address of the NIC of the **libos\_kni**. > * **Parameter template**: comm\_proxy\_attr = '{enable\_libnet:true, enable\_dfx:false, numa\_num:4, numa\_bind:\[\[30,31],\[62,63],\[94,95],\[126,127]]}' > * Parameters that need to be configured include: > * **enable\_libnet**: whether to enable the user-mode protocol. The options are as follows: **true** and **false**. > * **enable\_dfx**: whether to enable the communication proxy library view. The options are as follows: **true** and **false**. > * **numa\_num**: number of NUMA nodes in the system. 2P and 4P servers are supported. The value can be: **4** or **8**. > * **numa\_bind**: core binding parameter of the agent thread. Each numa has two CPUs. There are a total of **numa\_num** groups. The value range is as follows: \[0, Number of CPUs – 1]. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string, consisting of one or more characters **Default value**: **none** --- --- url: /en/docs/latest/database_reference/communication_matrix.md --- # Communication Matrix **Table 1** Communication matrix --- --- url: /en/docs/latest/database_administration_guide/comparison_disk_vs_mot.md --- # Comparison – Disk vs. MOT The following table briefly compares the various features of the openGauss disk-based storage engine and the MOT storage engine. **Table 1** Comparison – Disk-based vs. MOT # Appendices ## Glossary **Table 2** Glossary --- --- url: /en/docs/latest-lite/sql_reference/comparison_operators.md --- # Comparison Operators Comparison operators are available for the most data types and return Boolean values. 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 1](#en-us_topic_0283137685_en-us_topic_0237121966_en-us_topic_0059777421_en-us_topic_0058965550_table65067702) describes comparison operators provided by openGauss. **Table 1** Comparison operators Comparison operators are available for all relevant data types. All comparison operators are binary operators that returned values of Boolean type. The calculation priority of the inequality sign is higher than that of the equality sign. If the entered data is different and cannot be implicitly converted, the comparison fails. For example, an expression such as 1<2<3 is invalid because the less-than sign (<) cannot be used to compare Boolean values and 3. --- --- url: /en/docs/latest/sql_reference/comparison_operators.md --- # Comparison Operators Comparison operators are available for the most data types and return Boolean values. 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 1](#en-us_topic_0283137685_en-us_topic_0237121966_en-us_topic_0059777421_en-us_topic_0058965550_table65067702) describes comparison operators provided by openGauss. **Table 1** Comparison operators Comparison operators are available for all relevant data types. All comparison operators are binary operators that returned values of Boolean type. The calculation priority of the inequality sign is higher than that of the equality sign. If the entered data is different and cannot be implicitly converted, the comparison fails. For example, an expression such as 1<2<3 is invalid because the less-than sign (<) cannot be used to compare Boolean values and 3. --- --- url: /en/docs/latest-lite/database_administration_guide/comparison_disk_vs_mot.md --- # Comparison: Disk vs. MOT The following table briefly compares the various features of the openGauss disk-based storage engine and the MOT storage engine. Comparison: Disk-based vs. MOT In the preceding information: * RR: Repeatable Reads * RC: Read Committed * SI: Snapshot Isolation --- --- url: /en/docs/latest-lite/database_reference/compatibility_with_earlier_versions.md --- # Compatibility with Earlier Versions This section describes the parameters that control the backward compatibility and external compatibility of openGauss. A backward compatible database supports applications of earlier versions. This section describes parameters used for controlling backward compatibility of a database. ## array\_nulls **Parameter description**: Controls whether the array input parser recognizes unquoted NULL as a null array element. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that null values can be entered in arrays. * **off** indicates backward compatibility with the old behavior. Arrays containing the value **NULL** can still be created when this parameter is set to **off**. **Default value**: **on** ## backslash\_quote **Parameter description**: Controls whether a single quotation mark can be represented by \\' in a string text. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). > \[!TIP]NOTICE > When the string text meets the SQL standards, \ has no other meanings. This parameter only affects the handling of non-standard-conforming string texts, including escape string syntax (E'...'). **Value range**: enumerated values * **on** indicates that the use of \\' is always allowed. * **off** indicates that the use of \\' is rejected. * **safe\_encoding** indicates that the use of \\' is allowed only when client encoding does not allow ASCII \ within a multibyte character. **Default value**: **safe\_encoding** ## escape\_string\_warning **Parameter description**: Specifies whether to issue a warning when a backslash (\\) is used as an escape in an ordinary character string. * Applications that wish to use a backslash (\\) as an escape need to be modified to use escape string syntax (E'...'). This is because the default behavior of ordinary character strings treats the backslash as an ordinary character in each SQL standard. * This variable can be enabled to help locate codes that need to be changed. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean **Default value**: **on** ## lo\_compat\_privileges **Parameter description**: Specifies whether to enable backward compatibility for the privilege check of large objects. This parameter is a SUSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean **on** indicates that the privilege check is disabled when users read or modify large objects. This setting is compatible with versions earlier than PostgreSQL 9.0. **Default value**: **off** ## quote\_all\_identifiers **Parameter description**: Specifies whether to forcibly quote all identifiers even if they are not keywords when the database generates SQL. This will affect the output of **EXPLAIN** and the results of functions, such as pg\_get\_viewdef. For details, see the **--quote-all-identifiers** parameter of **gs\_dump**. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that the forcible quoting is enabled. * **off** indicates that the forcible quoting is disabled. **Default value**: **off** ## sql\_inheritance **Parameter description**: Controls the inheritance semantics. This parameter specifies the access policy of descendant tables. **off** indicates that subtables cannot be accessed by commands. That is, the ONLY keyword is used by default. This setting is compatible with earlier versions. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that subtables can be accessed. * **off** indicates that subtables cannot be accessed. **Default value**: **on** ## standard\_conforming\_strings **Parameter description**: Controls whether ordinary string texts ('...') treat backslashes as ordinary texts as specified in the SQL standard. * Applications can check this parameter to determine how string texts will be processed. * It is recommended that characters be escaped by using the escape string syntax (E'...'). This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that backslashes are treated as ordinary texts. * **off** indicates that backslashes are not treated as ordinary texts. **Default value**: **on** ## synchronize\_seqscans **Parameter description**: Controls sequential scans of tables to synchronize with each other, so that concurrent scans read the same data block at about the same time and share the I/O workload. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that a scan may start in the middle of the table and then "wrap around" the end to cover all rows to synchronize with the activity of scans already in progress. This may result in unpredictable changes in the row ordering returned by queries that have no ORDER BY clause. * **off** indicates that the scan always starts from the table heading. **Default value**: **on** ## enable\_beta\_features **Parameter description**: Specifies whether to enable some features that are not officially released and are used only for POC verification. Exercise caution when enabling these extended features because they may cause errors in some scenarios. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that the features are enabled for forward compatibility. Note that enabling them may cause errors in certain scenarios. * **off** indicates that the features are disabled. **Default value**: **off** ## default\_with\_oids **Parameter description**: Specifies whether **CREATE TABLE** and **CREATE TABLE AS** include an **OID** field in newly-created tables if neither **WITH OIDS** nor **WITHOUT OIDS** is specified. It also determines whether OIDs will be included in tables created by **SELECT INTO**. It is not recommended that OIDs be used in user tables. Therefore, this parameter is set to **off** by default. When OIDs are required for a particular table, **WITH OIDS** needs to be specified during the table creation. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that **CREATE TABLE** and **CREATE TABLE AS** can include an **OID** field in newly-created tables. * **off** indicates that **CREATE TABLE** and **CREATE TABLE AS** cannot include any OID field in newly-created tables. **Default value**: **off** --- --- url: /en/docs/latest/database_reference/compatibility_with_earlier_versions.md --- # Compatibility with Earlier Versions This section describes the parameters that control the backward compatibility and external compatibility of openGauss. A backward compatible database supports applications of earlier versions. This section describes parameters used for controlling backward compatibility of a database. ## array\_nulls **Parameter description**: Controls whether the array input parser recognizes unquoted NULL as a null array element. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that null values can be entered in arrays. * **off** indicates backward compatibility with the old behavior. Arrays containing the value **NULL** can still be created when this parameter is set to **off**. **Default value**: **on** ## backslash\_quote **Parameter description**: Controls whether a single quotation mark can be represented by \\' in a string text. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). > \[!TIP]NOTICE > When the string text meets the SQL standards, \ has no other meanings. This parameter only affects the handling of non-standard-conforming string texts, including escape string syntax (E'...'). **Value range**: enumerated values * **on** indicates that the use of \\' is always allowed. * **off** indicates that the use of \\' is rejected. * **safe\_encoding** indicates that the use of \\' is allowed only when client encoding does not allow ASCII \ within a multibyte character. **Default value**: **safe\_encoding** ## escape\_string\_warning **Parameter description**: Specifies whether to issue a warning when a backslash (\\) is used as an escape in an ordinary character string. * Applications that wish to use a backslash (\\) as an escape need to be modified to use escape string syntax (E'...'). This is because the default behavior of ordinary character strings treats the backslash as an ordinary character in each SQL standard. * This variable can be enabled to help locate codes that need to be changed. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean **Default value**: **on** ## lo\_compat\_privileges **Parameter description**: Specifies whether to enable backward compatibility for the privilege check of large objects. This parameter is a SUSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean **on** indicates that the privilege check is disabled when users read or modify large objects. This setting is compatible with versions earlier than PostgreSQL 9.0. **Default value**: **off** ## quote\_all\_identifiers **Parameter description**: Specifies whether to forcibly quote all identifiers even if they are not keywords when the database generates SQL. This will affect the output of **EXPLAIN** and the results of functions, such as pg\_get\_viewdef. For details, see the **--quote-all-identifiers** parameter of **gs\_dump**. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that the forcible quoting is enabled. * **off** indicates that the forcible quoting is disabled. **Default value**: **off** ## sql\_inheritance **Parameter description**: Controls the inheritance semantics. This parameter specifies the access policy of descendant tables. **off** indicates that subtables cannot be accessed by commands. That is, the ONLY keyword is used by default. This setting is compatible with earlier versions. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that subtables can be accessed. * **off** indicates that subtables cannot be accessed. **Default value**: **on** ## standard\_conforming\_strings **Parameter description**: Controls whether ordinary string texts ('...') treat backslashes as ordinary texts as specified in the SQL standard. * Applications can check this parameter to determine how string texts will be processed. * It is recommended that characters be escaped by using the escape string syntax (E'...'). This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that backslashes are treated as ordinary texts. * **off** indicates that backslashes are not treated as ordinary texts. **Default value**: **on** ## synchronize\_seqscans **Parameter description**: Controls sequential scans of tables to synchronize with each other, so that concurrent scans read the same data block at about the same time and share the I/O workload. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that a scan may start in the middle of the table and then "wrap around" the end to cover all rows to synchronize with the activity of scans already in progress. This may result in unpredictable changes in the row ordering returned by queries that have no ORDER BY clause. * **off** indicates that the scan always starts from the table heading. **Default value**: **on** ## enable\_beta\_features **Parameter description**: Specifies whether to enable some features that are not officially released and are used only for POC verification. Exercise caution when enabling these extended features because they may cause errors in some scenarios. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that the features are enabled for forward compatibility. Note that enabling them may cause errors in certain scenarios. * **off** indicates that the features are disabled. **Default value**: **off** ## default\_with\_oids **Parameter description**: Specifies whether **CREATE TABLE** and **CREATE TABLE AS** include an **OID** field in newly-created tables if neither **WITH OIDS** nor **WITHOUT OIDS** is specified. It also determines whether OIDs will be included in tables created by **SELECT INTO**. It is not recommended that OIDs be used in user tables. Therefore, this parameter is set to **off** by default. When OIDs are required for a particular table, **WITH OIDS** needs to be specified during the table creation. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: Boolean * **on** indicates that **CREATE TABLE** and **CREATE TABLE AS** can include an **OID** field in newly-created tables. * **off** indicates that **CREATE TABLE** and **CREATE TABLE AS** cannot include any OID field in newly-created tables. **Default value**: **off** --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_compatible_operators_and_operations.md --- # Compatible Operators and Operations If **dolphin.b\_compatibility\_mode** is set to **on**, MySQL-compatible four arithmetic operations are enabled. Compared with the original openGauss, Dolphin modifies the four arithmetic operations as follows: 1. The following types of arithmetic operations are supported: * Numeric types: tinyint (**unsigned**), smallint (**unsigned**), integer (**unsigned**), bigint (**unsigned**), float4, float8, decimal/numeric, and bit. * Character string types: char, varchar, binary, varbinary, tinyblob, blob, mediumblob, longblob, enum, set, json, and text (Currently, openGauss does not have tinytext, mediumtext, and longtext. Therefore, they are not considered.) * Date and time types: date, datetime, timestamp, time, and year. 2. The return values of some original operators are compatible with MySQL. The compatibility rules are as follows: * Integer x integer: For the +, -, and \* operators, if both operators are signed integers, the returned result is also signed integers. Otherwise, the returned result is unsigned integers. For the / operator, the returned value is of the fixed-point type (numeric type). * Integer x fixed-point type: For the +, -, \*, and / arithmetic operations, the fixed-point type is returned. Note: The openGauss fixed-point numbers are not unsigned. Therefore, the returned results are signed. * Integer x floating-point type: For the +, -, \*, and / arithmetic operations, the floating-point type is returned. Note: The openGauss floating-point numbers are not unsigned. Therefore, the returned results are signed. * Fixed-point type x fixed-point type: For the +, -, \*, and / arithmetic operations, the fixed-point type is returned. * Fixed-point type x floating-point type: For the +, -, \*, and / arithmetic operations, the floating-point type is returned. * Floating-point type x floating-point type: For the +, -, \*, and / arithmetic operations, the floating-point type is returned. Based on the preceding rules, you only need to use the type conversion rules of the character string type and time type to calculate the return values of these types during hybrid calculation. The type conversion rules are as follows: * The character string type is converted to the floating-point type in four arithmetic operations. * Date and time types: The date type is converted to a signed integer, and the year type is converted to an unsigned integer. If typmod (indicating millisecond and microsecond) is not specified, the datetime, timestamp, and time types are converted to signed integers; otherwise, they are converted to fixed-point numbers with the same number of decimal places as the specified typmod. ## Example Test case: ``` create database test_db dbcompatibility 'B'; \c test_db set dolphin.b_compatibility_mode to on; -- Integer x integer select 1::int4 + 1::int4; select 1::int4 - 1::int4; select 1::int4 * 1::int4; select 1::int4 / 1::int4; -- Integer x unsigned integer select 1::int4 + 1::uint4; select 1::int4 - 1::uint4; select 1::int4 * 1::uint4; select 1::int4 / 1::uint4; -- Integer x fixed-point type select 1::int4 + 1::numeric; select 1::int4 - 1::numeric; select 1::int4 * 1::numeric; select 1::int4 / 1::numeric; -- Integer x floating-point type select 1::int4 + 1::float8; select 1::int4 - 1::float8; select 1::int4 * 1::float8; select 1::int4 / 1::float8; -- Fixed-point type x floating-point type select 1::numeric + 1::float8; select 1::numeric - 1::float8; select 1::numeric * 1::float8; select 1::numeric / 1::float8; -- Integer x character string select 1::int4 + '1.23'::text; select 1::int4 - '1.23'::text; select 1::int4 * '1.23'::text; select 1::int4 / '1.23'::text; -- Integer x date select 1::int4 + '2022-01-01'::date; select 1::int4 - '2022-01-01'::date; select 1::int4 * '2022-01-01'::date; select 1::int4 / '2022-01-01'::date; -- Integer x time (without microseconds) select 1::int4 + '12:12:12'::time; select 1::int4 - '12:12:12'::time; select 1::int4 * '12:12:12'::time; select 1::int4 / '12:12:12'::time; -- Integer x time (with microseconds) select 1::int4 + '12:12:12.36'::time(3); select 1::int4 - '12:12:12.36'::time(3); select 1::int4 * '12:12:12.36'::time(3); select 1::int4 / '12:12:12.36'::time(3); ``` Results: ``` openGauss=# create database test_db dbcompatibility 'B'; CREATE DATABASE openGauss=# \c test_db test_db=# set dolphin.b_compatibility_mode to on; SET test_db=# -- Integer x integer test_db=# select 1::int4 + 1::int4; ?column? ---------- 2 (1 row) test_db=# select 1::int4 - 1::int4; ?column? ---------- 0 (1 row) test_db=# select 1::int4 * 1::int4; ?column? ---------- 1 (1 row) test_db=# select 1::int4 / 1::int4; ?column? ------------------------ 1.00000000000000000000 (1 row) test_db=# -- Integer x unsigned integer test_db=# select 1::int4 + 1::uint4; ?column? ---------- 2 (1 row) test_db=# select 1::int4 - 1::uint4; ?column? ---------- 0 (1 row) test_db=# select 1::int4 * 1::uint4; ?column? ---------- 1 (1 row) test_db=# select 1::int4 / 1::uint4; ?column? ------------------------ 1.00000000000000000000 (1 row) test_db=# -- Integer x fixed-point type test_db=# select 1::int4 + 1::numeric; ?column? ---------- 2 (1 row) test_db=# select 1::int4 - 1::numeric; ?column? ---------- 0 (1 row) test_db=# select 1::int4 * 1::numeric; ?column? ---------- 1 (1 row) test_db=# select 1::int4 / 1::numeric; ?column? ------------------------ 1.00000000000000000000 (1 row) test_db=# -- Integer x floating-point type test_db=# select 1::int4 + 1::float8; ?column? ---------- 2 (1 row) test_db=# select 1::int4 - 1::float8; ?column? ---------- 0 (1 row) test_db=# select 1::int4 * 1::float8; ?column? ---------- 1 (1 row) test_db=# select 1::int4 / 1::float8; ?column? ---------- 1 (1 row) test_db=# -- Fixed-point type x floating-point type test_db=# select 1::numeric + 1::float8; ?column? ---------- 2 (1 row) test_db=# select 1::numeric - 1::float8; ?column? ---------- 0 (1 row) test_db=# select 1::numeric * 1::float8; ?column? ---------- 1 (1 row) test_db=# select 1::numeric / 1::float8; ?column? ---------- 1 (1 row) test_db=# -- Integer x character string test_db=# select 1::int4 + '1.23'::text; ?column? ---------- 2.23 (1 row) test_db=# select 1::int4 - '1.23'::text; ?column? ---------- -0.23 (1 row) test_db=# select 1::int4 * '1.23'::text; ?column? ---------- 1.23 (1 row) test_db=# select 1::int4 / '1.23'::text; ?column? ------------------- 0.813008130081301 (1 row) test_db=# -- Integer x date test_db=# select 1::int4 + '2022-01-01'::date; ?column? ---------- 20220102 (1 row) test_db=# select 1::int4 - '2022-01-01'::date; ?column? ----------- -20220100 (1 row) test_db=# select 1::int4 * '2022-01-01'::date; ?column? ---------- 20220101 (1 row) test_db=# select 1::int4 / '2022-01-01'::date; ?column? ---------------------------- 0.000000049455737139987580 (1 row) test_db=# -- Integer x time (without microseconds) test_db=# select 1::int4 + '12:12:12'::time; ?column? ---------- 121213 (1 row) test_db=# select 1::int4 - '12:12:12'::time; ?column? ---------- -121211 (1 row) test_db=# select 1::int4 * '12:12:12'::time; ?column? ---------- 121212 (1 row) test_db=# select 1::int4 / '12:12:12'::time; ?column? ---------------------------- 0.000008250008250008250008 (1 row) test_db=# -- Integer x time (with microseconds) test_db=# select 1::int4 + '12:12:12.36'::time(3); ?column? --------------- 121213.360000 (1 row) test_db=# select 1::int4 - '12:12:12.36'::time(3); ?column? ---------------- -121211.360000 (1 row) test_db=# select 1::int4 * '12:12:12.36'::time(3); ?column? --------------- 121212.360000 (1 row) test_db=# select 1::int4 / '12:12:12.36'::time(3); ?column? ---------------------------- 0.000008249983747532017362 (1 row) ``` --- --- url: /en/docs/latest-lite/compilation_guide/compiling_the_version.md --- # Compiling the Version A **build/script/cmake\_package\_mini.sh** script is provided for building openGauss Lite and generating the installation package. This section describes how to build and package the openGauss Lite. ## Preparations ### Downloading Code **Prerequisites** Git and Git Large File Storage (LFS) have been installed and configured on the local host. **Procedure** 1. Run the following command to download the openGauss-server code. In the command, *\[git ssh address]* indicates the code download address, which can be obtained from the openGauss community. ``` [user@linux sda]$ git clone [git ssh address] openGauss-server ``` > \[!NOTE]NOTE > > * **openGauss-server**: openGauss code repository. > * Database compilation depends on open-source third-party software. You can obtain the open-source third-party software from [Building Open-source Software](#en-us_topic_0283136302_section13890105116714). Since open-source software build takes a long time, we have built **binarylibs** using **openGauss-third\_party** and compressed and uploaded it to the Internet. > The community provides binary files compiled on three platforms. The download links are as follows:\ > **openEuler\_arm:** > **openEuler\_x86:** > **Centos\_x86:** 2. When the progress of each download reaches 100%, the download is successful. ### Building Open-source Software The community provides built third-party binary files. If you directly use the built file, skip this step. **Downloading the Code of the Open-Source Third-Party Software Repository** Install git and git-lfs, and then run the following commands to download the openGauss-third\_party repository code: \[user@linux sda]$ git clone *\[git ssh address]* openGauss-third\_party **Building Open-source Software** Before building openGauss, build the open-source third-party software on which openGauss depends. The open-source third-party software is stored in the **openGauss-third\_party** code repository. After downloading the software, you can use **git lfs pull** to obtain large files from the code repository. Generally, you only need to build the software once. If the open-source software is updated, rebuild the software. Since this step takes a long time, we have built **binarylibs** using **openGauss-third\_party**. You can download the package by referring to [Downloading Code](#en-us_topic_0283136302_section188203481850). **Table 1** openGauss open-source third-party software required before build Prepare GCC 7.3 before building the third-party libraries. You are advised to use the released and built third-party library GCC and configure environment variables. After installing the software listed in [Table 1](#en-us_topic_0283136302_table1212531681911), point the default Python version to **python3.x** and perform the following operations: 1. Perform the following operations to go to the directory of the open-source third-party software on which the kernel depends, build the open-source third-party software, and generate binary programs or library files. **/sda/openGauss-third\_party** is the directory for downloading open-source third-party software. ``` [user@linux sda]$ cd /sda/openGauss-third_party/build [user@linux build]$ sh build_all.sh ``` 2. After the preceding commands are executed, the open-source third-party software required for openGauss build is automatically generated. To generate any open-source third-party software independently, go to the corresponding directory and run the **build.sh** script. For example: ``` [user@linux sda]$ cd /sda/openGauss-third_party/dependency/openssl [user@linux openssl]$ sh build.sh ``` The OpenSSL is generated. > \[!NOTE]NOTE > For error logs, you can view the corresponding log in the build directory and the log in the corresponding module. For example, you can view the OpenSSL build and installation logs in the **dependency** module. > > * /sda/openGauss-third\_party/build/dependency\_build.log > * /sda/openGauss-third\_party/dependency/build/openssl\_build.log > * /sda/openGauss-third\_party/dependency/openssl/build\_openssl.log **Build Result** After the preceding script is executed, the final build result is stored in **output** under the **openGauss-third\_party** directory These files will be used during the **openGauss-server** build. ### Introduction to cmake\_package\_mini.sh **openGauss-server/build/script/cmake\_package\_mini.sh** is the build script of openGauss Lite. Lite compilation and packaging can be quickly performed. The following table describes the parameters. **Table 2** cmake\_package\_mini.sh parameters > \[!NOTE]NOTE > > 1. **-m \[debug | release | memcheck]** indicates that three target versions can be selected: > > * **release**: indicates that the binary program of the release version is generated. During this version build, the GCC high-level optimization option is configured to remove the kernel debugging code. This option is usually used in the production environment or performance test environment. > * **debug**: indicates that a binary program of the debug version is generated. During this version build, the kernel code debugging function is added, which is usually used in the development self-test environment. > * **memcheck**: indicates that a binary program of the memcheck version is generated. During this version build, the ASAN function is added based on the debug version to locate memory problems. > 2. **-3rd \[binarylibs path]** is the path of **binarylibs**. You need to specify the absolute path of the third-party library. > 3. **-nopkg** performs only lite compilation, and no packaging is performed. The compilation result is stored in the **openGauss-server/mppdb\_temp\_install** directory. If this parameter is not specified, the file is packaged by default and the packaging result is stored in the **openGauss-server/output** directory. > 4. Each option in this script has a default value. The number of options is small and the dependency is simple. Therefore, this script is easy to use. If the required value is different from the default value, set this parameter based on the actual requirements. ## Building the Lite Installation Package Use the **build/script/cmake\_package\_mini.sh** script to build the openGauss Lite installation package. ### Prerequisites * The software and hardware have been prepared based on the requirements in [Setting up the Build Environment](setting_up_the_build_environment.md), and the code has been downloaded by referring to [Downloading Code](#en-us_topic_0283136302_section188203481850). * Open-source software has been built. For details, see [Building Open-source Software](#en-us_topic_0283136302_section13890105116714). * You are familiar with the parameter options and functions of the **cmake\_package\_mini.sh** script. ### Procedure 1. Run the following command to go to the code directory: ``` [user@linux sda]$ cd /sda/openGauss-server/build/script ``` 2. Run the following command to build the openGauss installation package: ``` [user@linux openGauss-server]$ sh cmake_package_mini.sh -3rd [binarylibs path] -m [release | debug | memcheck] ``` For example: ``` sh cmake_package_mini.sh -m release -3rd /sdc/binarylibs # Generate the openGauss Lite installation package of the release version. ``` 3. If the following information is displayed, the installation package build is successful: ``` success! ``` * The generated installation package is stored in the **./output** directory. * The build and packaging log file is stored in **./build/script/makemppdb\_pkg.log**. --- --- url: /en/docs/latest/compilation_guide/compiling_the_version.md --- # Compiling the Version A **build.sh** script is provided for compiling openGauss and generating the installation package. You can compile openGauss by using the script. You can also configure environment variables and run commands to compile openGauss. This section describes the prerequisites and procedure for openGauss compilation. The following figure shows the compilation process. ![](figures/绘图1.png) ## Preparation Before Compiling ### Downloading Code **Prerequisites** The git and git-lfs have been installed and configured on the local host. **Procedure** 1. Run the following command to download the code and open-source and third-party software repository. *\[git ssh address]* indicates the actual code download address. You can obtain them from the openGauss community. ``` [user@linux sda]$ git clone [git ssh address] openGauss-server [user@linux sda]$ git clone [git ssh address] openGauss-third_party [user@linux sda]$ # mkdir binarylibs For details about this comment, see the following note. ``` > \[!NOTE]NOTE > > * **openGauss-server**: openGauss code repository. > * **openGauss-third\_party**: open-source third-party software repository on which openGauss depends. > * **binarylibs**: package for storing the built open-source third-party software. You can obtain the package by referring to [Compiling Open-source Software](#compiling-open-source-software) . Since compiling and building open-source software take a long time, we have compiled and built **binarylibs** using **openGauss-third\_party** and compress and upload **binarylibs** to the Internet.\ > The community provides binary files compiled on three platforms. The download links are as follows:\ > **openEuler\_arm:** > **openEuler\_x86:** > **Centos\_x86:** > After the download is complete, decompress and rename the package: **mv openGauss-third\_party\_binarylibs binarylibs**. 2. When the progress of each download reaches 100%, the download is successful. ### Compiling Open-source Software **Compiling Open-source Software** Before compiling the openGauss, compile and build the open-source and third-party software on which the openGauss depends. These open-source and third-party software is stored in the **openGauss-third\_party** code repository. After downloading the software, you can use **git lfs pull** to obtain large files from the code repository. Generally, you only need to build the software once. If the open-source software is updated, rebuild the software. Since this step takes a long time, we have compiled and built **binarylibs** using **openGauss-third\_party**. You can download the package by referring to [Downloading Code](#downloading-code). **Table 1** openGauss open-source third-party software required before build Prepare GCC 7.3 before building the third-party libraries. You are advised to use the released and built third-party library GCC and configure environment variables. After installing the software listed in [Table 1](#en-us_topic_0283136302_table1212531681911), point the default Python version to **python3.x** and perform the following operations: 1. Run the following commands to go to the directory of the open-source and third-party software on which the kernel depends, compile and build the open-source and third-party software, and generate binary programs or library files. **/sda/openGauss-third\_party** is the directory for downloading open-source third-party software. ``` [user@linux sda]$ cd /sda/openGauss-third_party/build [user@linux build]$ sh build_all.sh ``` 2. After the preceding commands are executed, the open-source third-party software required for openGauss build is automatically generated. To generate any open-source third-party software independently, go to the corresponding directory and run the **build.sh** script. For example: ``` [user@linux sda]$ cd /sda/openGauss-third_party/dependency/openssl [user@linux openssl]$ sh build.sh ``` The openssl is generated. 3. > \[!NOTE]NOTE > For error logs, you can view the corresponding log in the build directory and the log in the corresponding module. For example, you can view the OpenSSL compilation and installation logs in the **dependency** module. > > * /sda/openGauss-third\_party/build/dependency\_build.log > * /sda/openGauss-third\_party/dependency/build/openssl\_build.log > * /sda/openGauss-third\_party/dependency/openssl/build\_openssl.log **Compilation and Build Result** After the preceding script is executed, the final compilation and build result is stored in the **output**directory under the **openGauss-third\_party** directory These files will be used during the compilation of **openGauss-server**. ### Introduction to compile script **openGauss-server/build.sh** is an important script tool during compilation. It integrates software installation and compilation and product installation package compilation functions to quickly compile and package code. The following table describes the parameters. **Table 2** build.sh parameters > \[!NOTE]NOTE > > 1. **-m \[debug | release | memcheck]** indicates that three target versions can be selected: > > * **release**: indicates that the binary program of the release version is generated. During compilation of this version, the GCC high-level optimization option is configured to remove the kernel debugging code. This option is usually used in the production environment or performance test environment. > * **debug**: indicates that a binary program of the debug version is generated. During compilation of this version, the kernel code debugging function is added, which is usually used in the development self-test environment. > * **memcheck**: indicates that a binary program of the memcheck version is generated. During compilation of this version, the ASAN function is added based on the debug version to locate memory problems. > 2. **-3rd \[binarylibs path]** is the path of **binarylibs**. By default, **binarylibs** exists in the current code folder. If **binarylibs** is moved to **openGauss-server** or a soft link to **binarylibs** is created in **openGauss-server**, you do not need to specify the parameter. However, if you do so, please note that the file is easy to be deleted by the **git clean** command. > 3. Each option in this script has a default value. The number of options is small and the dependency is simple. Therefore, this script is easy to use. If the required value is different from the default value, set this parameter based on the actual requirements. ## Software Compilation and Installation Software build and installation are to build code to generate software and install the software on a computer. The one-click build script **build.sh** is provided. You can also manually configure environment variables. The two methods are described below in this section. ### Prerequisites * The software and hardware have been prepared based on the requirements in [Setting up the Compilation Environment](setting_up_the_compilation_environment.md), and the code has been downloaded by referring to [Downloading Code](#downloading-code). * Open-source software has been compiled and built. For details, see [Compiling Open-source Software](#compiling-open-source-software). GCC 7.3 has been placed in the **output** directory based on the directory structure of the released and compiled third-party library. * You are familiar with the parameter options and functions of the [Introduction to build.sh](#introduction-to-compile-script) script. * The code environment is clean, and no file is generated before the current compilation. For details, see [FAQ](faqs.md). ### Compilation Using the One-click Script 1. Run the following command to go to the directory where the software code compilation script is stored: ``` [user@linux sda]$ cd /sda/openGauss-server ``` 2. Run the following command to compile openGauss: ``` [user@linux openGauss-server]$ sh build.sh -m [debug | release | memcheck] -3rd [binarylibs path] ``` For example: ``` sh build.sh # Compile and install openGauss of the release version. binarylibs or its soft link must exist in the code directory. Otherwise, the operation fails. sh build.sh -m debug -3rd /sdc/binarylibs # Compile and install openGauss of the debug version. ``` 3. If the following information is displayed, the compilation is successful: ``` make compile sucessfully! ``` * The software installation path after compilation is **/sda/openGauss-server/mppdb\_temp\_install**. * The compiled binary files are stored in **/sda/openGauss-server/mppdb\_temp\_install/bin**. * Compilation log: **./build/script/makemppdb\_pkg.log** 4. Import environment variables to initialize and start the database. ``` export CODE_BASE=________ # openGauss-server path export GAUSSHOME=$CODE_BASE/mppdb_temp_install/ export LD_LIBRARY_PATH=$GAUSSHOME/lib::$LD_LIBRARY_PATH export PATH=$GAUSSHOME/bin:$PATH ``` ### Manual Compilation 1. Run the following command to go to the software code directory: ``` [user@linux sda]$ cd /sda/openGauss-server ``` 2. Obtain the third-party library binary file of the corresponding platform. 3. Configure environment variables, add **\_\_\_\_** based on the code download location. ``` export CODE_BASE=________ # Path of the openGauss-server file export BINARYLIBS=________ # Path of the binarylibs file export GAUSSHOME=$CODE_BASE/dest/ export GCC_PATH=$BINARYLIBS/buildtools/gcc7.3/ export CC=$GCC_PATH/gcc/bin/gcc export CXX=$GCC_PATH/gcc/bin/g++ export LD_LIBRARY_PATH=$GAUSSHOME/lib:$GCC_PATH/gcc/lib64:$GCC_PATH/isl/lib:$GCC_PATH/mpc/lib/:$GCC_PATH/mpfr/lib/:$GCC_PATH/gmp/lib/:$LD_LIBRARY_PATH export PATH=$GAUSSHOME/bin:$GCC_PATH/gcc/bin:$PATH ``` 4. Select a version and configure it. **debug** version: ``` ./configure --gcc-version=7.3.0 CC=g++ CFLAGS='-O0' --prefix=$GAUSSHOME --3rd=$BINARYLIBS --enable-debug --enable-cassert --enable-thread-safety --with-readline --without-zlib ``` **release** version: ``` ./configure --gcc-version=7.3.0 CC=g++ CFLAGS="-O2 -g3" --prefix=$GAUSSHOME --3rd=$BINARYLIBS --enable-thread-safety --with-readline --without-zlib ``` **memcheck** version: ``` ./configure --gcc-version=7.3.0 CC=g++ CFLAGS='-O0' --prefix=$GAUSSHOME --3rd=$BINARYLIBS --enable-debug --enable-cassert --enable-thread-safety --with-readline --without-zlib --enable-memory-check ``` > \[!NOTE]NOTE > > * *\[debug | release | memcheck]* indicates that three target versions are available. The three target versions are as follows: > * **release**: indicates that the binary program of the release version is generated. During this version build, the GCC high-level optimization option is configured to remove the kernel debugging code. This option is usually used in the production environment or performance test environment. > * **debug**: indicates that a binary program of the debug version is generated. During this version build, the kernel code debugging function is added, which is usually used in the development self-test environment. > * **memcheck**: indicates that a binary program of the memcheck version is generated. During this version build, the ASAN function is added based on the debug version to locate memory problems. > * On the ARM-based platform, **-D\_\_USE\_NUMA** needs to be added to **CFLAGS**. > * On the **ARMv8.1** platform or a later version (for example, Kunpeng 920), **-D\_\_ARM\_LSE** needs to be added to **CFLAGS**. > * If **binarylibs** is moved to **openGauss-server** or a soft link to **binarylibs** is created in **openGauss-server**, you do not need to specify the **--3rd** parameter. However, if you do so, please note that the file is easy to be deleted by the **git clean** command. > * To use the MOT, you need to add **--enable-mot** to the command. 5. Run the following commands to compile openGauss: ``` [user@linux openGauss-server]$ make -sj [user@linux openGauss-server]$ make install -sj ``` 6. If the following information is displayed, the compilation and installation are successful: ``` openGauss installation complete. ``` * The software installation path after compilation is *$GAUSSHOME*. * The compiled binary files are stored in *$GAUSSHOME*\*\*/bin\*\*. ## Compiling the Installation Package To compile the installation package is to compile the code and generate the software installation package. The compilation and packaging process of the installation package is also integrated in **build.sh**. ### Prerequisites * TThe software and hardware have been prepared based on the requirements for setting up the compilation environment, and the code has been downloaded by referring to [Downloading Code](#downloading-code). * The open-source software has been compiled and built. For details, see [Compiling Open-source Software](#compiling-open-source-software). * You are familiar with the parameter options and functions of the [Introduction to build.sh](#introduction-to-compile-script) script. * The code environment is clean, and no file is generated before the current compilation. For details, see [FAQ](faqs.md). ### Procedure 1. Run the following command to go to the code directory: ``` [user@linux sda]$ cd /sda/openGauss-server ``` 2. Run the following command to compile the openGauss installation package: ``` [user@linux openGauss-server]$ sh build.sh -m [debug | release | memcheck] -3rd [binarylibs path] -pkg ``` For example: ``` sh build.sh -pkg # Generate the openGauss installation package of the release version. binarylibs or its soft link must exist in the code directory. Otherwise, the operation fails. sh build.sh -m debug -3rd /sdc/binarylibs -pkg # Generate the openGauss installation package of the debug version. ``` Compared with [Software Compilation and Installation](#software-compilation-and-installation), this operation involves the process of generating software by one-click compilation and the process of encapsulating the software into an installation package. Compared with the **build.sh** command in [Software Compilation and Installation](#software-compilation-and-installation), only the **-pkg** option is added. 3. If the following information is displayed, the installation package compilation is successful: ``` success! ``` * The build and packaging log file is stored in **./build/script/makemppdb\_pkg.log**. ## Verification After Build After the build is complete, perform the following steps to verify openGauss: 1. Run the following command to create user **omm** as user **root**: ``` [user@linux sda]# useradd omm -g dbgrp [user@linux sda]# passwd omm ``` 2. Add the following environment variables to **~/.bashrc** as user **omm**: ``` export GAUSSHOME=/root/openGauss-server/dest/ ## Path of the build result. You can change the path as required. export LD_LIBRARY_PATH=$GAUSSHOME/lib:$LD_LIBRARY_PATH export PATH=$GAUSSHOME/bin:$PATH ``` Run the following command for environment variables to take effect: ``` [user@linux sda]$ source ~/.bashrc ``` 3. Create the data directory and log directory. ``` [user@linux sda]$ mkdir ~/data [user@linux sda]$ mkdir ~/log [user@linux sda]$ chown -R omm:dbgrp /root/openGauss-server ``` 4. Initialize the database. ``` [user@linux sda]$ gs_initdb -D /home/omm/data --nodename=db1 ``` 5. Start the database. ``` [user@linux sda]$ gs_ctl start -D /home/omm/data -Z single_node -l /home/omm/log/opengauss.log ``` After the database is started, you can run the **ps -ef | grep gaussdb** command to check the database process status, run the **gs\_ctl query -D /home/omm/data** command to check the database status, or run the **gsql -d postgres** command to enter the **gsql** command line to view database information. ## openGauss-OM Build After the openGauss-server code repository is built using the source code, gs\_om does not exist. To use gs\_om, you need to compile openGauss-OM separately, copy the built **openGauss-***xxx***-om.tar.gz** package to the directory where the openGauss-server installation package is located, and install the openGauss-OM in the same way as the enterprise edition. ## Procedure 1. Run the **git clone** command to clone the OM code repository: ``` [user@linux sda]$ git clone https://gitcode.com/opengauss/openGauss-OM.git ``` 2. Run the following build command: ``` [user@linux sda]$ cd openGauss-OM [user@linux sda]$ chmod +x build.sh [user@linux sda]$ export BINARYLIBS_PATH=/root/binarylibs (Enter the directory generated after the third-party software package is decompressed.) [user@linux sda]$ ./build.sh -3rd $BINARYLIBS_PATH ``` 3. The Gauss-OM is built successfully if the following information is displayed: ``` ROOT_DIR: /root/binarylibs Everything is ready. success! ``` --- --- url: /en/docs/latest-lite/sql_reference/complete_refresh_materialized_view.md --- # Complete-refresh Materialized View ## Overview Complete-refresh materialized views can be fully refreshed only. The syntax for creating a complete-refresh materialized view is similar to the CREATE TABLE AS syntax. ## Usage ### Syntax * Create a complete-refresh materialized view. ``` CREATE MATERIALIZED VIEW [ view_name ] AS { query_block }; ``` * Fully refresh a materialized view. ``` REFRESH MATERIALIZED VIEW [ view_name ]; ``` * Delete a materialized view. ``` DROP MATERIALIZED VIEW [ view_name ]; ``` * Query a materialized view. ``` SELECT * FROM [ view_name ]; ``` ### Examples ``` -- Prepare data. openGauss=# CREATE TABLE t1(c1 int, c2 int); openGauss=# INSERT INTO t1 VALUES(1, 1); openGauss=# INSERT INTO t1 VALUES(2, 2); -- Create a complete-refresh materialized view. openGauss=# CREATE MATERIALIZED VIEW mv AS select count(*) from t1; CREATE MATERIALIZED VIEW -- Query the materialized view result. openGauss=# SELECT * FROM mv; count ------- 2 (1 row) -- Insert data into the base table in the materialized view. openGauss=# INSERT INTO t1 VALUES(3, 3); INSERT 0 1 -- Fully refresh the complete-refresh materialized view. openGauss=# REFRESH MATERIALIZED VIEW mv; REFRESH MATERIALIZED VIEW -- Query the materialized view result. openGauss=# SELECT * FROM mv; count ------- 3 (1 row) -- Delete the materialized view. openGauss=# DROP MATERIALIZED VIEW mv; DROP MATERIALIZED VIEW ``` ## Support and Constraints ### Supported Scenarios * Supports the same query scope as the CREATE TABLE AS statement does. * Supports index creation in complete-refresh materialized views. * Supports ANALYZE and EXPLAIN. ### Unsupported Scenarios Materialized views cannot be added, deleted, or modified. They support only query statements. ### Constraints When a complete-refresh materialized view is refreshed or deleted, a high-level lock is added to the base table. If the definition of a materialized view involves multiple tables, pay attention to the service logic to avoid deadlock. --- --- url: /en/docs/latest/sql_reference/full_materialized_view.md --- # Complete-refresh Materialized View ## Overview Complete-refresh materialized views can be fully refreshed only. The syntax for creating a complete-refresh materialized view is similar to the CREATE TABLE AS syntax. ## Usage ### Syntax * Create a complete-refresh materialized view. ``` CREATE MATERIALIZED VIEW [ view_name ] AS { query_block }; ``` * Fullly refresh a materialized view. ``` REFRESH MATERIALIZED VIEW [ view_name ]; ``` * Delete a materialized view. ``` DROP MATERIALIZED VIEW [ view_name ]; ``` * Query a materialized view. ``` SELECT * FROM [ view_name ]; ``` ### Examples ``` -- Prepare data. postgres=# CREATE TABLE t1(c1 int, c2 int); postgres=# INSERT INTO t1 VALUES(1, 1); postgres=# INSERT INTO t1 VALUES(2, 2); -- Create a complete-refresh materialized view. postgres=# CREATE MATERIALIZED VIEW mv AS select count(*) from t1; CREATE MATERIALIZED VIEW -- Query the materialized view result. postgres=# SELECT * FROM mv; count ------- 2 (1 row) -- Insert data into the base table in the materialized view. postgres=# INSERT INTO t1 VALUES(3, 3); -- Fully refresh a complete-refresh materialized view. postgres=# REFRESH MATERIALIZED VIEW mv; REFRESH MATERIALIZED VIEW -- Query the materialized view result. postgres=# SELECT * FROM mv; count ------- 3 (1 row) -- Delete a materialized view. postgres=# DROP MATERIALIZED VIEW mv; DROP MATERIALIZED VIEW ``` ## Support and Constraints ### Supported Scenarios * Supports the same query scope as the CREATE TABLE AS statement does. * Supports index creation in complete-refresh materialized view. * Supports ANALYZE and EXPLAIN. ### Unsupported Scenarios Materialized views cannot be added, deleted, or modified. They support only query statements. --- --- url: /en/docs/latest/characteristic_description/aifeature_guide/component.md --- # component This subcommand can be used to start DBMind components, including the exporter for monitoring metrics and other AI functions. It forwards the commands passed by the user through the CLI client to the corresponding components. For details about the commands of different components, see the corresponding sections of the components. ## Command Reference You can use the **--help** option to obtain the help information about this mode. For example: ``` gs_dbmind component --help ``` ``` usage: component [-h] COMPONENT_NAME ... positional arguments: COMPONENT_NAME choice a component to start. ['extract_log', 'forecast', 'index_advisor', 'opengauss_exporter', 'reprocessing_exporter', 'slow_query_diagnosis', 'sqldiag', 'xtuner'] ARGS arguments for the component to start optional arguments: -h, --help show this help message and exit ``` **Table 1** Parameters of the gs\_dbmind component subcommand --- --- url: /zh/docs/latest/characteristic_description/aifeature_guide/component.md --- # component子命令 该子命令可以用于启动DBMind的子组件(或插件),包括可用于监控指标的exporter,以及AI功能等。该命令可以将用户通过命令行传入的命令转发给对应的子组件,故不同的子组件命令需参考其功能的对应说明,详见后文各个子组件对应章节,此处不再赘述。 ## 命令参考 用户可以通过“--help”选项获得该模式的帮助信息,例如: ``` gs_dbmind component --help ``` ``` usage: component [-h] COMPONENT_NAME ... positional arguments: COMPONENT_NAME choice a component to start. For centralized/distributed instance: ['anomaly_detection', 'cluster_diagnosis', 'cmd_exporter', 'dkr', 'extract_log', 'index_advisor', 'opengauss_exporter', 'reprocessing_exporter', 'slow_query_diagnosis', 'sql_rewriter', 'sqldiag', 'xtuner'], for cloud-native instance: ['opengauss_exporter', 'reprocessing_exporter', 'sqldiag'] ARGS arguments for the component to start optional arguments: -h, --help show this help message and exit ``` **表 1** gs\_dbmind component 子命令说明 --- --- url: /en/docs/latest-lite/database_administration_guide/database_concepts.md --- # Concepts ## Database Databases manage various data objects and are isolated from each other. While creating a database, you can specify a tablespace. If you do not specify it, the object will be saved to the **PG\_DEFAULT** tablespace by default. Objects managed by a database can be distributed to multiple tablespaces. ## Tablespace In openGauss, a tablespace is a directory storing physical files of the databases the tablespace contains. Multiple tablespaces can coexist. Files are physically isolated using tablespaces and managed by a file system. ## Schema openGauss schemas logically separate databases. All database objects are created under certain schemas. In openGauss, schemas and users are loosely bound. When you create a user, a schema with the same name as the user will be created automatically. You can also create a schema or specify another schema. ## User and Role openGauss uses users and roles to control the access to databases. A role can be a database user or a group of database users, depending on role settings. In openGauss, the difference between roles and users is that a role does not have the **LOGIN** permission by default. In openGauss, one user can have only one role, but you can put a user's role under a parent role to grant multiple permissions to the user. ## Transaction In openGauss, transactions are managed by multi-version concurrency control (MVCC) and two-phase locking (2PL). It enables smooth data reads and writes. openGauss MVCC saves historical version data together with the current tuple version. openGauss uses a VACUUM thread instead of rollback segments to periodically delete historical version data. Unless in performance optimization, you do not need to pay attention to the **VACUUM** process. In addition, openGauss automatically commits transactions. --- --- url: /en/docs/latest/database_administration_guide/database_concepts.md --- # Concepts ## Database Databases manage various data objects and are isolated from each other. While creating a database, you can specify a tablespace. If you do not specify it, the object will be saved to the **PG\_DEFAULT** tablespace by default. Objects managed by a database can be distributed to multiple tablespaces. ## Tablespace In openGauss, a tablespace is a directory storing physical files of the databases the tablespace contains. Multiple tablespaces can coexist. Files are physically isolated using tablespaces and managed by a file system. ## Schema openGauss schemas logically separate databases. All database objects are created under certain schemas. In openGauss, schemas and users are loosely bound. When you create a user, a schema with the same name as the user will be created automatically. You can also create a schema or specify another schema. ## User and Role openGauss uses users and roles to control the access to databases. A role can be a database user or a group of database users, depending on role settings. In openGauss, the difference between roles and users is that a role does not have the **LOGIN** permission by default. In openGauss, one user can have only one role, but you can put a user's role under a parent role to grant multiple permissions to the user. ## Transaction In openGauss, transactions are managed by multi-version concurrency control (MVCC) and two-phase locking (2PL). It enables smooth data reads and writes. openGauss stores them together with the version of the current tuple. A VACUUM thread is introduced to periodically clear historical version data. Unless in performance optimization, you do not need to pay attention to the **VACUUM** process. In addition, openGauss automatically commits transactions. --- --- url: /en/docs/latest-lite/database_administration_guide/mot_concept.md --- # Concepts of MOT This chapter describes how openGauss MOT is designed and how it works. It also sheds light on its advanced features and capabilities and how to use them. This chapter serves to educate the reader about various technical details of how MOT operates, details of important MOT features and innovative differentiators. The content of this chapter may be useful for decision\_making regarding MOT's suitability to specific application requirements and for using and managing it most efficiently. * **[MOT Scale\_up Architecture](mot_scale_up_architecture.md)** * **[MOT Concurrency Control Mechanism](mot_concurrency_control_mechanism.md)** * **[Extended FDW and Other openGauss Features](extended_fdw_and_other_opengauss_features.md)** * **[NUMA Awareness Allocation and Affinity](numa_awareness_allocation_and_affinity.md)** * **[MOT Indexes](mot_index.md)** * **[MOT Durability Concepts](mot_durability_concepts.md)** * **[MOT Recovery Concepts](mot_recovery_concepts.md)** * **[MOT Query Native Compilation (JIT)](mot_query_native_compilation_jit.md)** * **[Comparison: Disk vs. MOT](comparison_disk_vs_mot.md)** --- --- url: /en/docs/latest/database_administration_guide/mot_concept.md --- # Concepts of MOT This chapter describes how openGauss MOT is designed and how it works. It also sheds light on its advanced features and capabilities and how to use them. This chapter serves to educate the reader about various technical details of how MOT operates, details of important MOT features and innovative differentiators. The content of this chapter may be useful for decision-making regarding MOT's suitability to specific application requirements and for using and managing it most efficiently. * **[MOT Scale-up Architecture](mot_scale_up_architecture.md)** * **[MOT Concurrency Control Mechanism](mot_concurrency_control_mechanism.md)** * **[Extended FDW and Other openGauss Features](extended_fdw_and_other_opengauss_features.md)** * **[NUMA Awareness Allocation and Affinity](numa_awareness_allocation_and_affinity.md)** * **[MOT Indexes](mot_index.md)** * **[MOT Durability Concepts](mot_durability_concepts.md)** * **[MOT Recovery Concepts](mot_recovery_concepts.md)** * **[MOT Query Native Compilation (JIT)](mot_query_native_compilation_jit.md)** * **[Comparison – Disk vs. MOT](comparison_disk_vs_mot.md)** --- --- url: /en/docs/latest-lite/database_om_guide/concurrent_write_example.md --- # Concurrent Write Examples This section uses the **test** table as an example to describe how to perform concurrent **INSERT** and **DELETE** in the same table, concurrent **INSERT** in the same table, concurrent **UPDATE** in the same table, and concurrent import and queries. ``` CREATE TABLE test(id int, name char(50), address varchar(255)); ``` ## Concurrent INSERT in the Same Table Transaction T1: ``` START TRANSACTION; INSERT INTO test VALUES(2,'test2','test123'); COMMIT; ``` Transaction T2: ``` START TRANSACTION; INSERT INTO test VALUES(3,'test3','test123'); COMMIT; ``` Scenario 1: T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, **INSERT** of T2 is executed and succeeds. At the **READ COMMITTED** and **REPEATABLE READ** levels, the **SELECT** statement of T1 cannot see data inserted by T2, and a query in T2 cannot see data inserted by T1. Scenario 2: * **READ COMMITTED** level T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, T1 is committed. In T2, a query executed after **INSERT** can see the data inserted by T1. * **REPEATABLE READ** level T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, T1 is committed. In T2, a query executed after **INSERT** cannot see the data inserted by T1. ## Concurrent INSERT and DELETE in the Same Table Transaction T1: ``` START TRANSACTION; INSERT INTO test VALUES(1,'test1','test123'); COMMIT; ``` Transaction T2: ``` START TRANSACTION; DELETE test WHERE NAME='test1'; COMMIT; ``` Scenario 1: T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, **DELETE** of T2 is performed. In this case, **DELETE 0** is displayed, because T1 is not committed and T2 cannot see the data inserted by T1. Scenario 2: * **READ COMMITTED** level T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, T1 is committed and **DELETE** of T2 is executed. In this case, **DELETE 1** is displayed, because T2 can see the data inserted by T1. * **REPEATABLE READ** level T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, T1 is committed and **DELETE** of T2 is executed. In this case, **DELETE 0** is displayed, because the data obtained in queries is consistent in a transaction. ## Concurrent UPDATE in the Same Table Transaction T1: ``` START TRANSACTION; UPDATE test SET address='test1234' WHERE name='test1'; COMMIT; ``` Transaction T2: ``` START TRANSACTION; UPDATE test SET address='test1234' WHERE name='test2'; COMMIT; ``` Transaction T3: ``` START TRANSACTION; UPDATE test SET address='test1234' WHERE name='test1'; COMMIT; ``` Scenario 1: T1 is started but not committed. At this time, T2 is started. **UPDATE** of T1 and then T2 starts, and both of them succeed. This is because the **UPDATE** operations use row-level locks and do not conflict when they update different rows. Scenario 2: T1 is started but not committed. At this time, T3 is started. **UPDATE** of T1 and then T3 starts, and **UPDATE** of T1 succeeds. **UPDATE** of T3 times out. This is because T1 and T3 update the same row and the lock is held by T1 at the time of the update. ## Concurrent Data Import and Queries Transaction T1: ``` START TRANSACTION; COPY test FROM '...'; COMMIT; ``` Transaction T2: ``` START TRANSACTION; SELECT * FROM test; COMMIT; ``` Scenario 1: T1 is started but not committed. At this time, T2 is started. **COPY** of T1 and then **SELECT** of T2 starts, and both of them succeed. In this case, T2 cannot see the data added by **COPY** of T1. Scenario 2: * **READ COMMITTED** level T1 is started but not committed. At this time, T2 is started. **COPY** of T1 is complete and T1 is committed. In this case, T2 can see the data added by **COPY** of T1. * **REPEATABLE READ** level T1 is started but not committed. At this time, T2 is started. **COPY** of T1 is complete and T1 is committed. In this case, T2 cannot see the data added by **COPY** of T1. --- --- url: /en/docs/latest/database_om_guide/concurrent_write_example.md --- # Concurrent Write Examples ## Concurrent INSERT and DELETE in the Same Table Transaction T1: ``` START TRANSACTION; INSERT INTO test VALUES(1,'test1','test123'); COMMIT; ``` Transaction T2: ``` START TRANSACTION; DELETE test WHERE NAME='test1'; COMMIT; ``` Scenario 1: T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, **DELETE** of T2 is performed. In this case, **DELETE 0** is displayed, because T1 is not committed and T2 cannot see the data inserted by T1. Scenario 2: * **READ COMMITTED** level T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, T1 is committed and **DELETE** of T2 is executed. In this case, **DELETE 1** is displayed, because T2 can see the data inserted by T1. * **REPEATABLE READ** level T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, T1 is committed and **DELETE** of T2 is executed. In this case, **DELETE 0** is displayed, because the data obtained in queries is consistent in a transaction. ## Concurrent INSERT in the Same Table Transaction T1: ``` START TRANSACTION; INSERT INTO test VALUES(2,'test2','test123'); COMMIT; ``` Transaction T2: ``` START TRANSACTION; INSERT INTO test VALUES(3,'test3','test123'); COMMIT; ``` Scenario 1: T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, **INSERT** of T2 is executed and succeeds. At the **READ COMMITTED** and **REPEATABLE READ** levels, the **SELECT** statement of T1 cannot see data inserted by T2, and a query in T2 cannot see data inserted by T1. Scenario 2: * **READ COMMITTED** level T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, T1 is committed. In T2, a query executed after **INSERT** can see the data inserted by T1. * **REPEATABLE READ** level T1 is started but not committed. At this time, T2 is started. After **INSERT** of T1 is complete, T1 is committed. In T2, a query executed after **INSERT** cannot see the data inserted by T1. ## Concurrent UPDATE in the Same Table Transaction T1: ``` START TRANSACTION; UPDATE test SET address='test1234' WHERE name='test1'; COMMIT; ``` Transaction T2: ``` START TRANSACTION; UPDATE test SET address='test1234' WHERE name='test2'; COMMIT; ``` Transaction T3: ``` START TRANSACTION; UPDATE test SET address='test1234' WHERE name='test1'; COMMIT; ``` Scenario 1: T1 is started but not committed. At this time, T2 is started. **UPDATE** of T1 and then T2 starts, and both of them succeed. This is because the **UPDATE** operations use row-level locks and do not conflict when they update different rows. Scenario 2: T1 is started but not committed. At this time, T3 is started. **UPDATE** of T1 and then T3 starts, and **UPDATE** of T1 succeeds. **UPDATE** of T3 times out. This is because T1 and T3 update the same row and the lock is held by T1 at the time of the update. ## Concurrent Data Import and Queries Transaction T1: ``` START TRANSACTION; COPY test FROM '...'; COMMIT; ``` Transaction T2: ``` START TRANSACTION; SELECT * FROM test; COMMIT; ``` Scenario 1: T1 is started but not committed. At this time, T2 is started. **COPY** of T1 and then **SELECT** of T2 starts, and both of them succeed. In this case, T2 cannot see the data added by **COPY** of T1. Scenario 2: * **READ COMMITTED** level T1 is started but not committed. At this time, T2 is started. **COPY** of T1 is complete and T1 is committed. In this case, T2 can see the data added by **COPY** of T1. * **REPEATABLE READ** level T1 is started but not committed. At this time, T2 is started. **COPY** of T1 is complete and T1 is committed. In this case, T2 cannot see the data added by **COPY** of T1. This section uses the **test** table as an example to describe how to perform concurrent **INSERT** and **DELETE** in the same table, concurrent **INSERT** in the same table, concurrent **UPDATE** in the same table, and concurrent import and queries. ``` CREATE TABLE test(id int, name char(50), address varchar(255)); ``` --- --- url: /en/docs/latest-lite/sql_reference/condition_expressions.md --- # Condition Expressions Data that meets the requirements specified by conditional expressions are filtered during SQL statement execution. Conditional expressions include the following types: * CASE **CASE** expressions are similar to the **CASE** statements in other coding languages. [Figure 1](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f6defc8307fd0434380b6ba22838ed5f1) shows the syntax of a **CASE** expression. **Figure 1** case::=\ ![](figures/case.jpg "case") A **CASE** clause can be used in a valid expression. **condition** is an expression that returns a value of Boolean type. * If the result is true, the result of the **CASE** expression is the required result. * If the result is false, the following **WHEN** or **ELSE** clauses are processed in the same way. * If every **WHEN condition** is false, the result of the expression is the result of the **ELSE** clause. If the **ELSE** clause is omitted and has no match condition, the result is NULL. Example: ``` openGauss=# CREATE TABLE tpcds.case_when_t1(CW_COL1 INT); openGauss=# INSERT INTO tpcds.case_when_t1 VALUES (1), (2), (3); openGauss=# SELECT * FROM tpcds.case_when_t1; cw_col1 --------- 1 2 3 (3 rows) openGauss=# SELECT CW_COL1, CASE WHEN CW_COL1=1 THEN 'one' WHEN CW_COL1=2 THEN 'two' ELSE 'other' END FROM tpcds.case_when_t1 ORDER BY 1; cw_col1 | case ---------+------- 1 | one 2 | two 3 | other (3 rows) openGauss=# DROP TABLE tpcds.case_when_t1; ``` * DECODE [Figure 2](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f8e62b15fa92349339fcdb77fcc5fef4d) shows the syntax of a **DECODE** expression. **Figure 2** decode::=\ ![](figures/decode.png "decode") Compare each following **compare(n)** with **base\_expr**. **value(n)** is returned if a **compare(n)** matches the **base\_expr** expression. If **base\_expr** does not match each **compare(n)**, the default value is returned. [Conditional Expression Functions](conditional_expression_functions.md) describes the examples. ``` openGauss=# SELECT DECODE('A','A',1,'B',2,0); case ------ 1 (1 row) ``` * COALESCE [Figure 3](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f1877c9f8d2ac4964828a6eaaddf5f35f) shows the syntax of a **COALESCE** expression. **Figure 3** coalesce::=\ ![](figures/coalesce.png "coalesce") **COALESCE** returns its first not-**NULL** value. If all the parameters are **NULL**, **NULL** is returned. This value is replaced by the default value when data is displayed. Like a **CASE** expression, **COALESCE** only evaluates the parameters that are needed to determine the result. That is, parameters to the right of the first non-null parameter are not evaluated. Example: ``` openGauss=# CREATE TABLE tpcds.c_tabl(description varchar(10), short_description varchar(10), last_value varchar(10)) ; openGauss=# INSERT INTO tpcds.c_tabl VALUES('abc', 'efg', '123'); openGauss=# INSERT INTO tpcds.c_tabl VALUES(NULL, 'efg', '123'); openGauss=# INSERT INTO tpcds.c_tabl VALUES(NULL, NULL, '123'); openGauss=# SELECT description, short_description, last_value, COALESCE(description, short_description, last_value) FROM tpcds.c_tabl ORDER BY 1, 2, 3, 4; description | short_description | last_value | coalesce -------------+-------------------+------------+---------- abc | efg | 123 | abc | efg | 123 | efg | | 123 | 123 (3 rows) openGauss=# DROP TABLE tpcds.c_tabl; ``` If **description** is not **NULL**, the value of **description** is returned. Otherwise, parameter **short\_description** is calculated. If **short\_description** is not **NULL**, the value of **short\_description** is returned. Otherwise, parameter **last\_value** is calculated. If **last\_value** is not **NULL**, the value of **last\_value** is returned. Otherwise, **none** is returned. ``` openGauss=# SELECT COALESCE(NULL,'Hello World'); coalesce --------------- Hello World (1 row) ``` * NULLIF [Figure 4](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f6c5bc64bf5de4b728ed1d73d97768e6e) shows the syntax of a **NULLIF** expression. **Figure 4** nullif::=\ ![](figures/nullif.png "nullif") Only if **value1** is equal to **value2** can **NULLIF** return the **NULL** value. Otherwise, **value1** is returned. Example: ``` openGauss=# CREATE TABLE tpcds.null_if_t1 ( NI_VALUE1 VARCHAR(10), NI_VALUE2 VARCHAR(10) ); openGauss=# INSERT INTO tpcds.null_if_t1 VALUES('abc', 'abc'); openGauss=# INSERT INTO tpcds.null_if_t1 VALUES('abc', 'efg'); openGauss=# SELECT NI_VALUE1, NI_VALUE2, NULLIF(NI_VALUE1, NI_VALUE2) FROM tpcds.null_if_t1 ORDER BY 1, 2, 3; ni_value1 | ni_value2 | nullif -----------+-----------+-------- abc | abc | abc | efg | abc (2 rows) openGauss=# DROP TABLE tpcds.null_if_t1; ``` If the value of **value1** is equal to that of **value2**, **NULL** is returned. Otherwise, the value of **value1** is returned. ``` openGauss=# SELECT NULLIF('Hello','Hello World'); nullif -------- Hello (1 row) ``` * GREATEST (maximum value) and LEAST (minimum value) [Figure 5](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f23a83b0f987a49e0b6890280568afbd2) shows the syntax of a **GREATEST** expression. **Figure 5** greatest::=\ ![](figures/greatest.png "greatest") You can select the maximum value from any numerical expression list. ``` openGauss=# SELECT greatest(9000,155555,2.01); greatest ---------- 155555 (1 row) ``` [Figure 6](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f30a16b0edbde4750a42053619840b384) shows the syntax of a **LEAST** expression. **Figure 6** least::=\ ![](figures/least.png "least") You can select the minimum value from any numerical expression list. Each of the preceding numeric expressions can be converted into a common data type, which will be the data type of the result. The NULL values in the list will be ignored. The result is **NULL** only if the results of all expressions are **NULL**. ``` openGauss=# SELECT least(9000,2); least ------- 2 (1 row) ``` [Conditional Expression Functions](conditional_expression_functions.md) describes the examples. * NVL [Figure 7](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f69cd4e01dd6e4280b756eb98d3c77c91) shows the syntax of an **NVL** expression. **Figure 7** nvl::=\ ![](figures/nvl.jpg "nvl") If the value of **value1** is **NULL**, the value of **value2** is returned. Otherwise, the value of **value1** is returned. Example: ``` openGauss=# SELECT nvl(null,1); nvl ----- 1 (1 row) ``` ``` openGauss=# SELECT nvl ('Hello World' ,1); nvl --------------- Hello World (1 row) ``` --- --- url: /en/docs/latest/sql_reference/conditional_expressions.md --- # Condition Expressions Data that meets the requirements specified by conditional expressions are filtered during SQL statement execution. Conditional expressions include the following types: * CASE **CASE** expressions are similar to the **CASE** statements in other coding languages. [Figure 1](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f6defc8307fd0434380b6ba22838ed5f1) shows the syntax of a **CASE** expression. **Figure 1** case::=\ ![](figures/case.jpg "case") A **CASE** clause can be used in a valid expression. **condition** is an expression that returns a value of Boolean type. * If the result is true, the result of the **CASE** expression is the required result. * If the result is false, the following **WHEN** or **ELSE** clauses are processed in the same way. * If every **WHEN condition** is false, the result of the expression is the result of the **ELSE** clause. If the **ELSE** clause is omitted and has no match condition, the result is NULL. Example: ``` openGauss=# CREATE TABLE tpcds.case_when_t1(CW_COL1 INT); openGauss=# INSERT INTO tpcds.case_when_t1 VALUES (1), (2), (3); openGauss=# SELECT * FROM tpcds.case_when_t1; cw_col1 --------- 1 2 3 (3 rows) openGauss=# SELECT CW_COL1, CASE WHEN CW_COL1=1 THEN 'one' WHEN CW_COL1=2 THEN 'two' ELSE 'other' END FROM tpcds.case_when_t1 ORDER BY 1; cw_col1 | case ---------+------- 1 | one 2 | two 3 | other (3 rows) openGauss=# DROP TABLE tpcds.case_when_t1; ``` * DECODE [Figure 2](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f8e62b15fa92349339fcdb77fcc5fef4d) shows the syntax of a **DECODE** expression. **Figure 2** decode::=\ ![](figures/decode.png "decode") Compare each following **compare(n)** with **base\_expr**. **value(n)** is returned if a **compare(n)** matches the **base\_expr** expression. If **base\_expr** does not match each **compare(n)**, the default value is returned. [Conditional Expression Functions](conditional_expression_functions.md) describes the examples. ``` openGauss=# SELECT DECODE('A','A',1,'B',2,0); case ------ 1 (1 row) ``` * COALESCE [Figure 3](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f1877c9f8d2ac4964828a6eaaddf5f35f) shows the syntax of a **COALESCE** expression. **Figure 3** coalesce::=\ ![](figures/coalesce.png "coalesce") **COALESCE** returns its first not-**NULL** value. If all the parameters are **NULL**, **NULL** is returned. This value is replaced by the default value when data is displayed. Like a **CASE** expression, **COALESCE** only evaluates the parameters that are needed to determine the result. That is, parameters to the right of the first non-null parameter are not evaluated. Example: ``` openGauss=# CREATE TABLE tpcds.c_tabl(description varchar(10), short_description varchar(10), last_value varchar(10)) ; openGauss=# INSERT INTO tpcds.c_tabl VALUES('abc', 'efg', '123'); openGauss=# INSERT INTO tpcds.c_tabl VALUES(NULL, 'efg', '123'); openGauss=# INSERT INTO tpcds.c_tabl VALUES(NULL, NULL, '123'); openGauss=# SELECT description, short_description, last_value, COALESCE(description, short_description, last_value) FROM tpcds.c_tabl ORDER BY 1, 2, 3, 4; description | short_description | last_value | coalesce -------------+-------------------+------------+---------- abc | efg | 123 | abc | efg | 123 | efg | | 123 | 123 (3 rows) openGauss=# DROP TABLE tpcds.c_tabl; ``` If **description** is not **NULL**, the value of **description** is returned. Otherwise, parameter **short\_description** is calculated. If **short\_description** is not **NULL**, the value of **short\_description** is returned. Otherwise, parameter **last\_value** is calculated. If **last\_value** is not **NULL**, the value of **last\_value** is returned. Otherwise, **none** is returned. ``` openGauss=# SELECT COALESCE(NULL,'Hello World'); coalesce --------------- Hello World (1 row) ``` * NULLIF [Figure 4](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f6c5bc64bf5de4b728ed1d73d97768e6e) shows the syntax of a **NULLIF** expression. **Figure 4** nullif::=\ ![](figures/nullif.png "nullif") Only if **value1** is equal to **value2** can **NULLIF** return the **NULL** value. Otherwise, **value1** is returned. Example: ``` openGauss=# CREATE TABLE tpcds.null_if_t1 ( NI_VALUE1 VARCHAR(10), NI_VALUE2 VARCHAR(10) ); openGauss=# INSERT INTO tpcds.null_if_t1 VALUES('abc', 'abc'); openGauss=# INSERT INTO tpcds.null_if_t1 VALUES('abc', 'efg'); openGauss=# SELECT NI_VALUE1, NI_VALUE2, NULLIF(NI_VALUE1, NI_VALUE2) FROM tpcds.null_if_t1 ORDER BY 1, 2, 3; ni_value1 | ni_value2 | nullif -----------+-----------+-------- abc | abc | abc | efg | abc (2 rows) openGauss=# DROP TABLE tpcds.null_if_t1; ``` If the value of **value1** is equal to that of **value2**, **NULL** is returned. Otherwise, the value of **value1** is returned. ``` openGauss=# SELECT NULLIF('Hello','Hello World'); nullif -------- Hello (1 row) ``` * GREATEST (maximum value) and LEAST (minimum value) [Figure 5](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f23a83b0f987a49e0b6890280568afbd2) shows the syntax of a **GREATEST** expression. **Figure 5** greatest::=\ ![](figures/greatest.png "greatest") You can select the maximum value from any numerical expression list. ``` openGauss=# SELECT greatest(9000,155555,2.01); greatest ---------- 155555 (1 row) ``` [Figure 6](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f30a16b0edbde4750a42053619840b384) shows the syntax of a **LEAST** expression. **Figure 6** least::=\ ![](figures/least.png "least") You can select the minimum value from any numerical expression list. Each of the preceding numeric expressions can be converted into a common data type, which will be the data type of the result. The NULL values in the list will be ignored. The result is **NULL** only if the results of all expressions are **NULL**. ``` openGauss=# SELECT least(9000,2); least ------- 2 (1 row) ``` [Conditional Expression Functions](conditional_expression_functions.md) describes the examples. * NVL [Figure 7](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f69cd4e01dd6e4280b756eb98d3c77c91) shows the syntax of an **NVL** expression. **Figure 7** nvl::=\ ![](figures/nvl.jpg "nvl") If the value of **value1** is **NULL**, the value of **value2** is returned. Otherwise, the value of **value1** is returned. Example: ``` openGauss=# SELECT nvl(null,1); nvl ----- 1 (1 row) ``` ``` openGauss=# SELECT nvl ('Hello World' ,1); nvl --------------- Hello World (1 row) ``` --- --- url: /en/docs/latest-lite/sql_reference/conditional_expression_functions.md --- # Conditional Expression Functions ## Conditional Expression Functions * coalesce(expr1, expr2, ..., exprn) Description: Returns the first of its parameters that are not null. **COALESCE(expr1, expr2)** is equivalent to **CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE expr2 END**. Example: ``` openGauss=# SELECT coalesce(NULL,'hello'); coalesce ---------- hello (1 row) ``` Note: * If all the expressions are equivalent to NULL in the expression list, this function returns **NULL**. * This value is replaced by the default value when data is displayed. * Like a **CASE** expression, **COALESCE** only evaluates the parameters that are needed to determine the result. That is, parameters to the right of the first not-**NULL** parameter are not evaluated. * decode(base\_expr, compare1, value1, Compare2,value2, ... default) Description: Compares **base\_expr** with each **compare(n)** and **returns value(n)** if they are matched. If **base\_expr** does not match each **compare(n)**, the default value is returned. Example: ``` openGauss=# SELECT decode('A','A',1,'B',2,0); case ------ 1 (1 row) ``` * nullif(expr1, expr2) Description: Returns **NULL** only when **expr1** is equal to **expr2**. Otherwise, **expr1** is returned. **nullif(expr1, expr2)** is equivalent to **CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END**. Example: ``` openGauss=# SELECT nullif('hello','world'); nullif -------- hello (1 row) ``` Note: Assume the two parameter data types are different: * If implicit conversion exists between the two data types, implicitly convert the parameter of lower priority to this data type using the data type of higher priority. If the conversion succeeds, computation is performed. Otherwise, an error is returned. Example: ``` openGauss=# SELECT nullif('1234'::VARCHAR,123::INT4); nullif -------- 1234 (1 row) ``` ``` openGauss=# SELECT nullif('1234'::VARCHAR,'2012-12-24'::DATE); ERROR: invalid input syntax for type timestamp: "1234" ``` * If implicit conversion is not applied between two data types, an error is returned. Example: ``` openGauss=# SELECT nullif(TRUE::BOOLEAN,'2012-12-24'::DATE); ERROR: operator does not exist: boolean = timestamp without time zone LINE 1: SELECT nullif(TRUE::BOOLEAN,'2012-12-24'::DATE) FROM sys_dummy; ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. ``` * nvl( expr1 , expr2 ) Description: * If **expr1** is **NULL**, **expr2** is returned. * If **expr1** is not **NULL**, **expr1** is returned. Example: ``` openGauss=# SELECT nvl('hello','world'); nvl ------- hello (1 row) ``` Note: Parameters **expr1** and **expr2** can be of any data type. If **expr1** and **expr2** are of different data types, NVL checks whether **expr2** can be implicitly converted to **expr1**. If it can, the data type of **expr1** is returned. Otherwise, an error is returned. * greatest(expr1 \[, ...]) Description: Selects the largest value from a list of any number of expressions. Return type: Example: ``` openGauss=# SELECT greatest(1*2,2-3,4-1); greatest ---------- 3 (1 row) ``` ``` openGauss=# SELECT greatest('HARRY', 'HARRIOT', 'HAROLD'); greatest ---------- HARRY (1 row) ``` * least(expr1 \[, ...]) Description: Selects the smallest value from a list of any number of expressions. Example: ``` openGauss=# SELECT least(1*2,2-3,4-1); least ------- -1 (1 row) ``` ``` openGauss=# SELECT least('HARRY','HARRIOT','HAROLD'); least -------- HAROLD (1 row) ``` * EMPTY\_BLOB() Description: Initiates a BLOB variable in an **INSERT** or an **UPDATE** statement to a **NULL** value. Return type: BLOB Example: ``` -- Create a table. openGauss=# CREATE TABLE blob_tb(b blob,id int); -- Insert data. openGauss=# INSERT INTO blob_tb VALUES (empty_blob(),1); --Delete the table. openGauss=# DROP TABLE blob_tb; ``` Note: The length is 0 obtained using **DBE\_LOB.GET\_LENGTH**. --- --- url: /en/docs/latest/sql_reference/conditional_expression_functions.md --- # Conditional Expression Functions ## Conditional Expression Functions * coalesce(expr1, expr2, ..., exprn) Description: Returns the first of its parameters that are not null. **COALESCE(expr1, expr2)** is equivalent to **CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE expr2 END**. Example: ``` openGauss=# SELECT coalesce(NULL,'hello'); coalesce ---------- hello (1 row) ``` Note: * If all the expressions are equivalent to NULL in the expression list, this function returns **NULL**. * This value is replaced by the default value when data is displayed. * Like a **CASE** expression, **COALESCE** only evaluates the parameters that are needed to determine the result. That is, parameters to the right of the first not-**NULL** parameter are not evaluated. * decode(base\_expr, compare1, value1, Compare2,value2, ... default) Description: Compares **base\_expr** with each **compare(n)** and **returns value(n)** if they are matched. If **base\_expr** does not match each **compare(n)**, the default value is returned. Example: ``` openGauss=# SELECT decode('A','A',1,'B',2,0); case ------ 1 (1 row) ``` * nullif(expr1, expr2) Description: Returns **NULL** only when **expr1** is equal to **expr2**. Otherwise, **expr1** is returned. **nullif(expr1, expr2)** is equivalent to **CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END**. Example: ``` openGauss=# SELECT nullif('hello','world'); nullif -------- hello (1 row) ``` Note: Assume the two parameter data types are different: * If implicit conversion exists between the two data types, implicitly convert the parameter of lower priority to this data type using the data type of higher priority. If the conversion succeeds, computation is performed. Otherwise, an error is returned. Example: ``` openGauss=# SELECT nullif('1234'::VARCHAR,123::INT4); nullif -------- 1234 (1 row) ``` ``` openGauss=# SELECT nullif('1234'::VARCHAR,'2012-12-24'::DATE); ERROR: invalid input syntax for type timestamp: "1234" ``` * If implicit conversion is not applied between two data types, an error is returned. Example: ``` openGauss=# SELECT nullif(TRUE::BOOLEAN,'2012-12-24'::DATE); ERROR: operator does not exist: boolean = timestamp without time zone LINE 1: SELECT nullif(TRUE::BOOLEAN,'2012-12-24'::DATE) FROM sys_dummy; ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. ``` * nvl( expr1 , expr2 ) Description: * If **expr1** is **NULL**, **expr2** is returned. * If **expr1** is not **NULL**, **expr1** is returned. Example: ``` openGauss=# SELECT nvl('hello','world'); nvl ------- hello (1 row) ``` Note: Parameters **expr1** and **expr2** can be of any data type. If **expr1** and **expr2** are of different data types, NVL checks whether **expr2** can be implicitly converted to **expr1**. If it can, the data type of **expr1** is returned. Otherwise, an error is returned. * greatest(expr1 \[, ...]) Description: Selects the largest value from a list of any number of expressions. Return type: Example: ``` openGauss=# SELECT greatest(1*2,2-3,4-1); greatest ---------- 3 (1 row) ``` ``` openGauss=# SELECT greatest('HARRY', 'HARRIOT', 'HAROLD'); greatest ---------- HARRY (1 row) ``` * least(expr1 \[, ...]) Description: Selects the smallest value from a list of any number of expressions. Example: ``` openGauss=# SELECT least(1*2,2-3,4-1); least ------- -1 (1 row) ``` ``` openGauss=# SELECT least('HARRY','HARRIOT','HAROLD'); least -------- HAROLD (1 row) ``` * EMPTY\_BLOB() Description: Initiates a BLOB variable in an **INSERT** or an **UPDATE** statement to a **NULL** value. Return type: BLOB Example: ``` -- Create a table. openGauss=# CREATE TABLE blob_tb(b blob,id int); -- Insert data. openGauss=# INSERT INTO blob_tb VALUES (empty_blob(),1); --Delete the table. openGauss=# DROP TABLE blob_tb; ``` Note: The length is 0 obtained using **DBE\_LOB.GET\_LENGTH**. --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_conditional_expression_functions.md --- # Conditional Expression Functions ## Precautions * This section describes only the new conditional expression functions of Dolphin. For details about the conditional expression functions of the original openGauss, see [Conditional Expression Functions](https://docs.opengauss.org/en/docs/latest/sql_reference/conditional_expression_functions.html). ## Conditional Expression Functions * if(bool, expr1, expr2) Description: Condition judgment function. If **bool** is **true**, **expr1** is returned. If **bool** is **false**, **expr2** is returned. Example: ``` openGauss=# select if(true, 1, 2); case ------ 1 (1 row) ``` ``` openGauss=# select if(false, 1, 2); case ------ 2 (1 row) ``` * ifnull( expr1 , expr2 ) Description: * If the value of **expr1** is **NULL**, the value of **expr2** is returned. * If the value of **expr1** is not **NULL**, the value of **expr1** is returned. Example: ``` openGauss=# SELECT ifnull('hello','world'); nvl ------- hello (1 row) ``` Remarks: The parameter conversion logic is the same as that of the NVL. * isnull( expr ) * Returns **true** if **expr** is **NULL**. * Returns **false** if **expr** is not **NULL**. Example: ``` openGauss=# SELECT ifnull('hello'); ?column? -------- f (1 row) ``` Remarks: The null check logic is the same as that of **expr is null**. * interval(base\_expr, expr1, expr2, ..., exprn) Description: * Compares base\_expr with expr(n) one by one until expr(n) is greater than base\_expr and returns value(n-1). If expr(n) is less than or equal to base\_expr, returns value(n). * If base\_expr or expr(n) is non-numeric data: * BOOL: TRUE is converted to 1, and FALSE is converted to 0. * If it can be truncated to a floating point number in float8 format, it is truncated to float8. * If it cannot be truncated to a floating point number float8, it is considered as 0. Example: ``` openGauss=# SELECT interval(5,2,3,4,6,7); interval ---------- 3 (1 row) ``` ``` openGauss=# SELECT interval(false,-1,0,true,2); interval ---------- 2 (1 row) ``` ``` openGauss=# SELECT interval('2022-12-12'::timestamp,'asdf','2020-12-12'::date,2023); interval ---------- 2 (1 row) ``` * strcmp(str1, str2) Description: Compares str1 with str2 from left to right. If str1 is equal to str2, 0 is returned. If str1 is greater than str2, 1 is returned. If str1 is less than str2, -1 is returned. Example: ``` openGauss=# SELECT strcmp('asd','asd'); strcmp -------- 0 (1 row) ``` ``` openGauss=# SELECT strcmp(312,311); strcmp -------- 1 (1 row) ``` ``` openGauss=# SELECT strcmp('2021-12-12'::timestamp,20210::float8); strcmp -------- -1 (1 row) ``` --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin_conditional_expressions.md --- # Conditional Expressions Compared with the original openGauss, Dolphin modifies the condition expressions as follows: 1. The IFNULL and IF expressions are added. * IFNULL It is equivalent to NVL. For the NVL syntax, see [Figure 7](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f69cd4e01dd6e4280b756eb98d3c77c91). **Figure 7** nvl::= ![](figures/nvl.jpg "nvl") If the value of **value1** is **NULL**, the value of **value2** is returned. Otherwise, the value of **value1** is returned. Example: ``` openGauss=# SELECT ifnull(null,1); ifnull ------- 1 (1 row) ``` ``` openGauss=# SELECT ifnull ('Hello World' ,1); ifnull ------------- Hello World (1 row) ``` * IF Only IF(expr1,expr2,expr3) is supported, which is equivalent to CASE WHEN expr1 THEN expr2 ELSE expr3 END. For the CASE syntax, see [Figure 1](#en-us_topic_0283136958_en-us_topic_0237122002_en-us_topic_0059777797_f6defc8307fd0434380b6ba22838ed5f1). **Figure 1** case::= ![](figures/case.jpg "case") A **CASE** clause can be used in a valid expression. **condition** is an expression that returns a value of Boolean type. * If the result is **true**, the result of the **CASE** expression is the required result. * If the result is **false**, the following **WHEN** or **ELSE** clauses are processed in the same way. * If every **WHEN condition** is **false**, the result of the expression is the result of the **ELSE** clause. If the **ELSE** clause is omitted and has no match condition, the result is **NULL**. Example: ``` openGauss=# CREATE TABLE case_when_t1(CW_COL1 INT); openGauss=# INSERT INTO case_when_t1 VALUES (1), (2), (3); openGauss=# SELECT * FROM case_when_t1; cw_col1 --------- 1 2 3 (3 rows) openGauss=# SELECT CW_COL1, IF(CW_COL1=1, 'one', 'other') FROM case_when_t1 ORDER BY 1; cw_col1 | case ---------+------- 1 | one 2 | other 3 | other (3 rows) openGauss=# DROP TABLE case_when_t1; ``` --- --- url: /en/docs/latest-lite/sql_reference/conditional_statements.md --- # Conditional Statements Conditional statements are used to decide whether given conditions are met. Operations are executed based on the decisions made. openGauss supports five usages of **IF**: * IF\_THEN **Figure 1** IF\_THEN::=\ ![](figures/if_then.jpg "if_then") **IF\_THEN** is the simplest form of **IF**. If the condition is true, statements are executed. If it is false, they are skipped. Example: ``` openGauss=# IF v_user_id <> 0 THEN UPDATE users SET email = v_email WHERE user_id = v_user_id; END IF; ``` * IF\_THEN\_ELSE **Figure 2** IF\_THEN\_ELSE::=\ ![](figures/if_then_else.jpg "if_then_else") **IF\_THEN\_ELSE** statements add **ELSE** branches and can be executed if the condition is false. Example: ``` openGauss=# IF parentid IS NULL OR parentid = '' THEN RETURN; ELSE hp_true_filename(parentid); -- Call the stored procedure. END IF; ``` * IF\_THEN\_ELSE IF **IF** statements can be nested in the following way: ``` openGauss=# IF sex = 'm' THEN pretty_sex := 'man'; ELSE IF sex = 'f' THEN pretty_sex := 'woman'; END IF; END IF; ``` Actually, this is a way of an **IF** statement nesting in the **ELSE** part of another **IF** statement. Therefore, an **END IF** statement is required for each nesting **IF** statement and another **END IF** statement is required to end the parent **IF-ELSE** statement. To set multiple options, use the following form: * IF\_THEN\_ELSIF\_ELSE **Figure 3** IF\_THEN\_ELSIF\_ELSE::=\ ![](figures/if_then_elsif_else.png "if_then_elsif_else") Example: ``` IF number_tmp = 0 THEN result := 'zero'; ELSIF number_tmp > 0 THEN result := 'positive'; ELSIF number_tmp < 0 THEN result := 'negative'; ELSE result := 'NULL'; END IF; ``` * IF\_THEN\_ELSEIF\_ELSE **ELSEIF** is an alias of **ELSIF**. Example: ``` CREATE OR REPLACE PROCEDURE proc_control_structure(i in integer) AS BEGIN IF i > 0 THEN raise info 'i:% is greater than 0. ',i; ELSIF i < 0 THEN raise info 'i:% is smaller than 0. ',i; ELSE raise info 'i:% is equal to 0. ',i; END IF; RETURN; END; / CALL proc_control_structure(3); -- Delete the stored procedure. DROP PROCEDURE proc_control_structure; ``` --- --- url: /en/docs/latest/sql_reference/conditional_statements.md --- # Conditional Statements Conditional statements are used to decide whether given conditions are met. Operations are executed based on the decisions made. openGauss supports five usages of **IF**: * IF\_THEN **Figure 1** IF\_THEN::=\ ![](figures/if_then.jpg "if_then") **IF\_THEN** is the simplest form of **IF**. If the condition is true, statements are executed. If it is false, they are skipped. Example: ``` postgres=# IF v_user_id <> 0 THEN UPDATE users SET email = v_email WHERE user_id = v_user_id; END IF; ``` * IF\_THEN\_ELSE **Figure 2** IF\_THEN\_ELSE::=\ ![](figures/if_then_else.jpg "if_then_else") **IF-THEN-ELSE** statements add **ELSE** branches and can be executed if the condition is false. Example: ``` postgres=# IF parentid IS NULL OR parentid = '' THEN RETURN; ELSE hp_true_filename(parentid); -- Call the stored procedure. END IF; ``` * IF\_THEN\_ELSE IF **IF** statements can be nested in the following way: ``` postgres=# IF sex = 'm' THEN pretty_sex := 'man'; ELSE IF sex = 'f' THEN pretty_sex := 'woman'; END IF; END IF; ``` Actually, this is a way of an **IF** statement nesting in the **ELSE** part of another **IF** statement. Therefore, an **END IF** statement is required for each nesting **IF** statement and another **END IF** statement is required to end the parent **IF-ELSE** statement. To set multiple options, use the following form: * IF\_THEN\_ELSIF\_ELSE **Figure 3** IF\_THEN\_ELSIF\_ELSE::=\ ![](figures/if_then_elsif_else.png "if_then_elsif_else") Example: ``` IF number_tmp = 0 THEN result := 'zero'; ELSIF number_tmp > 0 THEN result := 'positive'; ELSIF number_tmp < 0 THEN result := 'negative'; ELSE result := 'NULL'; END IF; ``` * IF\_THEN\_ELSEIF\_ELSE **ELSEIF** is an alias of **ELSIF**. Example: ``` CREATE OR REPLACE PROCEDURE proc_control_structure(i in integer) AS BEGIN IF i > 0 THEN raise info 'i:% is greater than 0. ',i; ELSIF i < 0 THEN raise info 'i:% is smaller than 0. ',i; ELSE raise info 'i:% is equal to 0. ',i; END IF; RETURN; END; / CALL proc_control_structure(3); -- Delete the stored procedure. DROP PROCEDURE proc_control_structure; ``` --- --- url: /en/docs/latest-lite/sql_reference/config_settings.md --- # CONFIG\_SETTINGS **CONFIG\_SETTINGS** displays information about parameters of the running database. **Table 1** CONFIG\_SETTINGS columns --- --- url: /en/docs/latest/sql_reference/config_settings.md --- # CONFIG\_SETTINGS **CONFIG\_SETTINGS** displays information about parameters of the running database. **Table 1** CONFIG\_SETTINGS columns --- --- url: /zh/docs/latest-lite/sql_reference/config_settings.md --- # CONFIG\_SETTINGS CONFIG\_SETTINGS视图显示数据库运行时参数的相关信息。 **表 1** CONFIG\_SETTINGS字段 --- --- url: /zh/docs/latest/sql_reference/config_settings.md --- # CONFIG\_SETTINGS CONFIG\_SETTINGS视图显示数据库运行时参数的相关信息。 **表 1** CONFIG\_SETTINGS字段 --- --- url: /en/docs/latest-lite/sql_reference/configuration_examples.md --- # Configuration Examples Text search configuration specifies the following components required for converting a document into a **tsvector**: * A parser, decomposes a text into tokens. * Dictionary list, converts each token into a lexeme. Each time when the **to\_tsvector** or **to\_tsquery** function is invoked, a text search configuration is required to specify a processing procedure. The GUC parameter [default\_text\_search\_config](../database_reference/locale_and_formatting.md#en-us_topic_0283136798_en-us_topic_0237124733_en-us_topic_0059778109_sd9a07d429cd4498383931c621742b816) specifies the default text search configuration, which will be used if the text search function does not explicitly specify a text search configuration. openGauss provides some predefined text search configurations. You can also create user-defined text search configurations. In addition, to facilitate the management of text search objects, multiple **gsql** meta-commands are provided to display information about text search objects. For details, see "Client Tool > Meta-Command Reference" in *Tool Reference*. ## Procedure 1. Create a text search configuration **ts\_conf** by copying the predefined text search configuration **english**. ``` openGauss=# CREATE TEXT SEARCH CONFIGURATION ts_conf ( COPY = pg_catalog.english ); CREATE TEXT SEARCH CONFIGURATION ``` 2. Create a **Synonym** dictionary. Assume that the definition file **pg\_dict.syn** of the **Synonym** dictionary contains the following contents: ``` postgres pg pgsql pg postgresql pg ``` Run the following statement to create the **Synonym** dictionary: ``` openGauss=# CREATE TEXT SEARCH DICTIONARY pg_dict ( TEMPLATE = synonym, SYNONYMS = pg_dict, FILEPATH = 'file:///home/dicts' ); ``` 3. Create an **Ispell** dictionary **english\_ispell** (the dictionary definition file is from the open source dictionary). ``` openGauss=# CREATE TEXT SEARCH DICTIONARY english_ispell ( TEMPLATE = ispell, DictFile = english, AffFile = english, StopWords = english, FILEPATH = 'file:///home/dicts' ); ``` 4. Modify the text search configuration **ts\_conf** and change the dictionary list for tokens of certain types. For details about token types, see [Parser](parser.md). ``` openGauss=# ALTER TEXT SEARCH CONFIGURATION ts_conf ALTER MAPPING FOR asciiword, asciihword, hword_asciipart, word, hword, hword_part WITH pg_dict, english_ispell, english_stem; ``` 5. In the text search configuration, set non-index or set the search for tokens of certain types. ``` openGauss=# ALTER TEXT SEARCH CONFIGURATION ts_conf DROP MAPPING FOR email, url, url_path, sfloat, float; ``` 6. Use the text retrieval commissioning function **ts\_debug()** to test the text search configuration **ts\_conf**. ``` openGauss=# SELECT * FROM ts_debug('ts_conf', ' PostgreSQL, the highly scalable, SQL compliant, open source object-relational database management system, is now undergoing beta testing of the next version of our software. '); ``` 7. You can set the default text search configuration of the current session to **ts\_conf**. This setting is valid only for the current session. ``` openGauss=# \dF+ ts_conf Text search configuration "public.ts_conf" Parser: "pg_catalog.default" Token | Dictionaries -----------------+------------------------------------- asciihword | pg_dict,english_ispell,english_stem asciiword | pg_dict,english_ispell,english_stem file | simple host | simple hword | pg_dict,english_ispell,english_stem hword_asciipart | pg_dict,english_ispell,english_stem hword_numpart | simple hword_part | pg_dict,english_ispell,english_stem int | simple numhword | simple numword | simple uint | simple version | simple word | pg_dict,english_ispell,english_stem openGauss=# SET default_text_search_config = 'public.ts_conf'; SET openGauss=# SHOW default_text_search_config; default_text_search_config ---------------------------- public.ts_conf (1 row) ``` --- --- url: /en/docs/latest/sql_reference/configuration_examples.md --- # Configuration Examples Text search configuration specifies the following components required for converting a document into a **tsvector**: * A parser, decomposes a text into tokens. * Dictionary list, converts each token into a lexeme. Each time when the **to\_tsvector** or **to\_tsquery** function is invoked, a text search configuration is required to specify a processing procedure. The GUC parameter [default\_text\_search\_config](../database_reference/locale_and_formatting.md) specifies the default text search configuration, which will be used if the text search function does not explicitly specify a text search configuration. openGauss provides some predefined text search configurations. You can also create user-defined text search configurations. In addition, to facilitate the management of text search objects, multiple **gsql** meta-commands are provided to display information about text search objects. For details, see "Client Tool > Meta-Command Reference" in *Tool Reference*. ## Procedure 1. Create a text search configuration **ts\_conf** by copying the predefined text search configuration **english**. ``` openGauss=# CREATE TEXT SEARCH CONFIGURATION ts_conf ( COPY = pg_catalog.english ); CREATE TEXT SEARCH CONFIGURATION ``` 2. Create a **Synonym** dictionary. Assume that the definition file **pg\_dict.syn** of the **Synonym** dictionary contains the following contents: ``` postgres pg pgsql pg postgresql pg ``` Run the following statement to create the **Synonym** dictionary: ``` openGauss=# CREATE TEXT SEARCH DICTIONARY pg_dict ( TEMPLATE = synonym, SYNONYMS = pg_dict, FILEPATH = 'file:///home/dicts' ); ``` 3. Create an **Ispell** dictionary **english\_ispell** (the dictionary definition file is from the open source dictionary). ``` openGauss=# CREATE TEXT SEARCH DICTIONARY english_ispell ( TEMPLATE = ispell, DictFile = english, AffFile = english, StopWords = english, FILEPATH = 'file:///home/dicts' ); ``` 4. Modify the text search configuration **ts\_conf** and change the dictionary list for tokens of certain types. For details about token types, see [Parser](parser.md). ``` openGauss=# ALTER TEXT SEARCH CONFIGURATION ts_conf ALTER MAPPING FOR asciiword, asciihword, hword_asciipart, word, hword, hword_part WITH pg_dict, english_ispell, english_stem; ``` 5. In the text search configuration, set non-index or set the search for tokens of certain types. ``` openGauss=# ALTER TEXT SEARCH CONFIGURATION ts_conf DROP MAPPING FOR email, url, url_path, sfloat, float; ``` 6. Use the text retrieval commissioning function **ts\_debug()** to test the text search configuration **ts\_conf**. ``` openGauss=# SELECT * FROM ts_debug('ts_conf', ' PostgreSQL, the highly scalable, SQL compliant, open source object-relational database management system, is now undergoing beta testing of the next version of our software. '); ``` 7. You can set the default text search configuration of the current session to **ts\_conf**. This setting is valid only for the current session. ``` openGauss=# \dF+ ts_conf Text search configuration "public.ts_conf" Parser: "pg_catalog.default" Token | Dictionaries -----------------+------------------------------------- asciihword | pg_dict,english_ispell,english_stem asciiword | pg_dict,english_ispell,english_stem file | simple host | simple hword | pg_dict,english_ispell,english_stem hword_asciipart | pg_dict,english_ispell,english_stem hword_numpart | simple hword_part | pg_dict,english_ispell,english_stem int | simple numhword | simple numword | simple uint | simple version | simple word | pg_dict,english_ispell,english_stem openGauss=# SET default_text_search_config = 'public.ts_conf'; SET openGauss=# SHOW default_text_search_config; default_text_search_config ---------------------------- public.ts_conf (1 row) ``` --- --- url: >- /en/docs/latest-lite/database_administration_guide/configuration_file_reference.md --- # Configuration File Reference **Table 1** Parameter description **Table 2** Authentication modes --- --- url: /en/docs/latest/database_administration_guide/configuration_file_reference.md --- # Configuration File Reference **Table 1** Parameter description **Table 2** Authentication modes --- --- url: /en/docs/latest-lite/sql_reference/configuration_settings.md --- # Configuration settings The following table describes columns in the Configuration settings report. **Table 1** Columns in the Configuration settings report --- --- url: /en/docs/latest/sql_reference/configuration_settings_60.md --- # Configuration settings The following table describes columns in the Configuration settings report. **Table 1** Columns in the Configuration settings report --- --- url: /zh/docs/latest-lite/sql_reference/configuration_settings.md --- # Configuration settings Configuration settings列名称及描述如下表所示。 **表 1** Configuration settings报表主要内容 --- --- url: /zh/docs/latest/sql_reference/configuration_settings.md --- # Configuration settings Configuration settings列名称及描述如下表所示。 **表 1** Configuration settings报表主要内容 --- --- url: /en/docs/latest-lite/database_om_guide/configuration_set.md --- # Configuration Settings Publication-subscription requires some configuration options to be set. On the publisher, **wal\_level** must be set to **logical**, and the value of **max\_replication\_slots** must be at least the number of subscriptions expected to be connected plus the number of connections reserved for table synchronization. Value of **max\_wal\_senders** ≥ Value of **max\_replication\_slots** + Number of physical replication slots that are connected at the same time + 1 > \[!NOTE]NOTE > If a subscriber is activated and subscribes to a publication, a temporary connection to the publisher needs to be established to check whether the publication subscribed to by the subscriber exists on the publisher. The publisher creates a temporary WAL sender. After the temporary connection is used up, it is disconnected and released immediately. **max\_replication\_slots** must also be set on the subscriber. It must be set to at least the number of subscriptions that will be added to the subscriber. **max\_logical\_replication\_workers** must be set to at least the number of subscriptions plus the number of connections reserved for table synchronization. --- --- url: /en/docs/latest/database_om_guide/configuration_set.md --- # Configuration Settings Publication-subscription requires some configuration options to be set. On the publisher side, **wal\_level** must be set to **logical**, and the value of **max\_replication\_slots** must be at least the number of subscriptions expected to be connected plus the number of connections reserved for table synchronization. Value of **max\_wal\_senders** ≥ Value of **max\_replication\_slots** + Number of physical replication slots that are connected at the same time + 1 > \[!NOTE]NOTE > If a subscriber is activated and subscribes to a publication, a temporary connection to the publisher needs to be established to check whether the publication subscribed to by the subscriber exists on the publisher. The publisher creates a temporary WAL sender. After the temporary connection is used up, it is disconnected and released immediately. **max\_replication\_slots** must also be set on the subscriber. It must be set to at least the number of subscriptions that will be added to the subscriber. **max\_logical\_replication\_workers** must be set to at least the number of subscriptions plus the number of connections reserved for table synchronization. --- --- url: /en/docs/latest-lite/sql_reference/configuration_settings_functions.md --- # Configuration Settings Functions Configuration setting functions are used for querying and modifying configuration parameters during running. * current\_setting(setting\_name) Description: Specifies the current setting. Return type: text Note: **current\_setting** obtains the current setting of **setting\_name** by query. It is equivalent to the **SHOW** statement. Example: ``` openGauss=# SELECT current_setting('datestyle'); current_setting ----------------- ISO, MDY (1 row) ``` * set\_working\_grand\_version\_num\_manually(tmp\_version) Description: Upgrades new features of the database by switching the authorization version. Return type: void * shell\_in(type) Description: Inputs a route for the shell type that has not yet been filled. Return type: void * shell\_out(type) Description: Outputs a route for the shell type that has not yet been filled. Return type: void * set\_config(setting\_name, new\_value, is\_local) Description: Sets the parameter and returns a new value. Return type: text Note: **set\_config** sets **setting\_name** to **new\_value**. If **is\_local** is set to **true**, **new\_value** applies only to the current transaction. If you want **new\_value** to apply for the current session, set the value to **false** instead. The function corresponds to the **SET** statement. Example: ``` openGauss=# SELECT set_config('log_statement_stats', 'off', false); set_config ------------ off (1 row) ``` --- --- url: /en/docs/latest/sql_reference/configuration_settings_functions.md --- # Configuration Settings Functions Configuration setting functions are used for querying and modifying configuration parameters during running. * current\_setting(setting\_name) Description: Specifies the current setting. Return type: text Note: **current\_setting** obtains the current setting of **setting\_name** by query. It is equivalent to the **SHOW** statement. Example: ``` openGauss=# SELECT current_setting('datestyle'); current_setting ----------------- ISO, MDY (1 row) ``` * set\_working\_grand\_version\_num\_manually(tmp\_version) Description: Upgrades new features of the database by switching the authorization version. Return type: void * shell\_in(type) Description: Inputs a route for the shell type that has not yet been filled. Return type: void * shell\_out(type) Description: Outputs a route for the shell type that has not yet been filled. Return type: void * set\_config(setting\_name, new\_value, is\_local) Description: Sets the parameter and returns a new value. Return type: text Note: **set\_config** sets **setting\_name** to **new\_value**. If **is\_local** is set to **true**, **new\_value** applies only to the current transaction. If you want **new\_value** to apply for the current session, set the value to **false** instead. The function corresponds to the **SET** statement. Example: ``` openGauss=# SELECT set_config('log_statement_stats', 'off', false); set_config ------------ off (1 row) ``` --- --- url: /en/docs/latest-lite/sql_reference/configurations.md --- # Configurations Full text search functionality includes the ability to do many more things: skip indexing certain words (stop words), process synonyms, and use sophisticated parsing, for example, parse based on more than just white space. This functionality is controlled by text search configurations. openGauss comes with predefined configurations for many languages, and you can easily create your own configurations. (The **\dF** command of **gsql** shows all available configurations.) During installation an appropriate configuration is selected and **default\_text\_search\_config** is set accordingly in **postgresql.conf**. If you are using the same text search configuration for openGauss, you can use the value in **postgresql.conf**. To use different configurations throughout openGauss but the same configuration within any one database, use **ALTER DATABASE ...** **SET**. Otherwise, you can set **default\_text\_search\_config** in each session. Each text search function that depends on a configuration has an optional argument, so that the configuration to use can be specified explicitly. **default\_text\_search\_config** is used only when this argument is omitted. To make it easier to build custom text search configurations, a configuration is built up from simpler database objects. openGauss's text search facility provides the following types of configuration-related database objects: * Text search parsers break documents into tokens and classify each token (for example, as words or numbers). * Text search dictionaries convert tokens to normalized form and reject stop words. * Text search templates provide the functions underlying dictionaries. (A dictionary simply specifies a template and a set of parameters for the template.) * Text search configurations select a parser and a set of dictionaries to use to normalize the tokens produced by the parser. --- --- url: /en/docs/latest/sql_reference/configurations.md --- # Configurations Full text search functionality includes the ability to do many more things: skip indexing certain words (stop words), process synonyms, and use sophisticated parsing, for example, parse based on more than just white space. This functionality is controlled by text search configurations. openGauss comes with predefined configurations for many languages, and you can easily create your own configurations. (The **\dF** command of **gsql** shows all available configurations.) During installation an appropriate configuration is selected and **default\_text\_search\_config** is set accordingly in **postgresql.conf**. If you are using the same text search configuration for openGauss, you can use the value in **postgresql.conf**. To use different configurations throughout openGauss but the same configuration within any one database, use **ALTER DATABASE ...** **SET**. Otherwise, you can set **default\_text\_search\_config** in each session. Each text search function that depends on a configuration has an optional argument, so that the configuration to use can be specified explicitly. **default\_text\_search\_config** is used only when this argument is omitted. To make it easier to build custom text search configurations, a configuration is built up from simpler database objects. openGauss's text search facility provides the following types of configuration-related database objects: * Text search parsers break documents into tokens and classify each token (for example, as words or numbers). * Text search dictionaries convert tokens to normalized form and reject stop words. * Text search templates provide the functions underlying dictionaries. (A dictionary simply specifies a template and a set of parameters for the template.) * Text search configurations select a parser and a set of dictionaries to use to normalize the tokens produced by the parser. --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-CONFIGURATIONS.md --- # CONFIGURATIONS 返回参数相关的信息。 **表1** CONFIGURATIONS --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-CONFIGURATIONS.md --- # CONFIGURATIONS 返回参数相关的信息。 **表1** CONFIGURATIONS --- --- url: >- /en/docs/latest-lite/developer_guide/configuring_a_data_source_in_the_linux_os.md --- # Configuring a Data Source in the Linux OS The ODBC DRIVER (**psqlodbcw.so**) provided by openGauss can be used after it has been configured in a data source. To configure a data source, you must configure the **odbc.ini** and **odbcinst.ini** files on the server. The two files are generated during the unixODBC compilation and installation, and are saved in the **/usr/local/etc** directory by default. ## Procedure 1. Obtain the source code package of unixODBC by following link: After the download, validate the integrity based on the integrity validation algorithm provided by the community. 2. Install unixODBC. It does not matter if unixODBC of another version has been installed. Currently, unixODBC-2.2.1 is not supported. For example, to install unixODBC-2.3.0, run the commands below. 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.0.tar.gz cd unixODBC-2.3.0 # Modify the configure file. (If it does not exist, modify the configure.ac file.) Find LIB_VERSION. # Change the value of LIB_VERSION to 1:0:0 to compile a *.so.1 dynamic library with the same dependency on psqlodbcw.so. vim configure ./configure --enable-gui=no #To perform compilation on an ARM server, add the configure parameter --build=aarch64-unknown-linux-gnu. make # The installation may require root permissions. make install ``` 3. Replace the openGauss client driver. 1. Decompress the **openGauss-x.x.x-ODBC.tar.gz** package. After the decompression, the **lib** and **odbc** folders are generated. The **odbc** folder contains another **lib** folder. Copy the **psqlodbca.la**, **psqlodbca.so**, **psqlodbcw.la**, and **psqlodbcw.so** files from **/odbc/lib** to **/usr/local/lib**. 2. Copy the library in the **lib** directory obtained after decompressing **openGauss-x.x.x-ODBC.tar.gz** to the **/usr/local/lib** directory. 4. Configure a data source. 1. Configure the ODBC driver file. Add the following content to the **/usr/local/etc/odbcinst.ini** file: ``` [GaussMPP] Driver64=/usr/local/lib/psqlodbcw.so setup=/usr/local/lib/psqlodbcw.so ``` For descriptions of the parameters in the **odbcinst.ini** file, see [Table 1](#en-us_topic_0283136654_en-us_topic_0237120407_en-us_topic_0059778464_td564f21e7c8e458bbd741b09896f5d91). **Table 1** odbcinst.ini configuration parameters 2. Configure the data source file. Add the following content to the **/usr/local/etc/odbc.ini** file: ``` [MPPODBC] Driver=GaussMPP Servername=10.145.130.26 (IP address of the server where the database resides) Database=postgres (database name) Username=omm (database username) Password= (user password of the database) Port=8000 (listening port of the database) Sslmode = allow ``` For descriptions of the parameters in the **odbc.ini** file, see [Table 2](#en-us_topic_0283136654_en-us_topic_0237120407_en-us_topic_0059778464_t55845a6555f2454297b64ce47ad3d648). **Table 2** odbc.ini configuration parameters The valid values of **Sslmode** are as follows: **Table 3** Sslmode options 5. (Optional) Generate an SSL certificate. For details, see [Generating Certificates](../database_administration_guide/ssl_certificate_management.md). This step and step [6](#en-us_topic_0283136654_li1724551081815) are required only when the server and client are connected in SSL mode. Skip the two steps if the non-SSL connection mode is used. 6. (Optional) Replace an SSL certificate. For details, see [Replacing Certificates](../database_administration_guide/ssl_certificate_management.md). 7. Enable SSL mode. Declare the following environment variables and ensure that the permission for the **client.key\*** series files is set to **600**. ``` Go back to the root directory, create the .postgresql directory, and save root.crt, client.crt, client.key, client.key.cipher, client.key.rand, client.req, server.crt, server.key, server.key.cipher, server.key.rand, and server.req to the .postgresql directory. In the Unix OS, server.crt and server.key must deny the access from the external or any group. Run the following command to set this permission: chmod 0600 server.key Copy the certificate files whose names start with root.crt and server to the install/data directory of the database (the directory is the same as that of the postgresql.conf file). Modify the postgresql.conf file. ssl = on ssl_cert_file = 'server.crt' ssl_key_file = 'server.key' ssl_ca_file = 'root.crt' After modifying the parameters, restart the database. Set the sslmode parameter to require or verify-ca in the odbc.ini file. ``` 8. Configure the database server. 1. Log in as the OS user **omm** to the primary node of the database. 2. Run the following command to add NIC IP addresses or host names, with values separated by commas (,). The NICs and hosts are used to provide external services. In the following command, *NodeName* specifies the name of the current node. ``` gs_guc reload -N NodeName -I all -c "listen_addresses='localhost,192.168.0.100,10.11.12.13'" ``` If direct routing of LVS is used, add the virtual IP address (10.11.12.13) of LVS to the server listening list. You can also set **listen\_addresses** to **\*** or **0.0.0.0** to listen to all NICs, but this incurs security risks and is not recommended. 3. Run the following command to add an authentication rule to the configuration file of the primary database node. In this example, the IP address (10.11.12.13) of the client is the remote host IP address. ``` gs_guc reload -N all -I all -h "host all jack 10.11.12.13/32 sha256" ``` > \[!NOTE]NOTE > > - *** > - **-N all** indicates all hosts in openGauss. > - **-I all** indicates all instances of the host. > - **-h** specifies statements that need to be added in the **pg\_hba.conf** file. > - **all** indicates that a client can connect to any database. > - **jack** indicates the user that accesses the database. > - **\_10.11.12.13/\_*32*** indicates hosts whose IP address is 10.11.12.13 can be connected. Configure the parameter based on your network conditions. **32** indicates that there are 32 bits whose value is 1 in the subnet mask. That is, the subnet mask is 255.255.255.255. > - **sha256** indicates that the password of user **jack** is encrypted using the SHA-256 algorithm. If the ODBC client and the primary database node to connect are deployed on the same machine, you can use the local trust authentication mode. Run the following command: ``` local all all trust ``` If the ODBC client and the primary database node to connect are deployed on different machines, use the SHA-256 authentication mode. Run the following command: ``` host all all xxx.xxx.xxx.xxx/32 sha256 ``` 4. Restart openGauss. ``` gs_om -t stop gs_om -t start ``` 9. Configure the environment variables on the client. ``` vim ~/.bashrc ``` Add the following information to the configuration file: ``` export LD_LIBRARY_PATH=/usr/local/lib/:$LD_LIBRARY_PATH export ODBCSYSINI=/usr/local/etc export ODBCINI=/usr/local/etc/odbc.ini ``` 10. Run the following command to validate the addition: ``` source ~/.bashrc ``` ## Verifying the Data Source Configuration Run the **./isql -v** *MPPODBC* command (***MPPODBC*** is the data source name). * If the following information is displayed, the configuration is correct and the connection succeeds. ``` +---------------------------------------+ | Connected! | | | | sql-statement | | help [tablename] | | quit | | | +---------------------------------------+ SQL> ``` * If error information is displayed, the configuration is incorrect. Check the configuration. ## FAQs * \[UnixODBC]\[Driver Manager]Can't open lib 'xxx/xxx/psqlodbcw.so' : file not found. Possible causes: * The path configured in the **odbcinst.ini** file is incorrect. Run **ls** to check the path in the error information, and ensure that the **psqlodbcw.so** file exists and you have execute permissions on it. * The dependent library of **psqlodbcw.so** does not exist or is not in system environment variables. Run **ldd** to check the path in the error information. If **libodbc.so.1** or other UnixODBC libraries do not exist, configure UnixODBC again following the procedure provided in this section, and add the **lib** directory under its installation directory to **LD\_LIBRARY\_PATH**. If other libraries do not exist, add the **lib** directory under the ODBC driver package to **LD\_LIBRARY\_PATH**. * \[UnixODBC]connect to server failed: no such file or directory Possible causes: * An incorrect or unreachable database IP address or port was configured. Check the **Servername** and **Port** configuration items in data sources. * Server monitoring is improper. If **Servername** and **Port** are correctly configured, ensure the proper network adapter and port are monitored by following the database server configurations in the procedure in this section. * Firewall and network gatekeeper settings are improper. Check firewall settings, and ensure that the database communication port is trusted. Check to ensure network gatekeeper settings are proper (if any). * \[unixODBC]The password-stored method is not supported. Possible causes: The **sslmode** configuration item is not configured in the data sources. Solution: Set the configuration item to **allow** or a higher level. For details, see [Table 3](#en-us_topic_0283136654_en-us_topic_0237120407_en-us_topic_0059778464_table22136585143846). * Server common name "xxxx" does not match host name "xxxxx" Possible causes: When **verify-full** is used for SSL encryption, the driver checks whether the host name in certificates is the same as the actual one. Solution: To solve this problem, use **verify-ca** to stop checking host names, or generate a set of CA certificates containing the actual host names. * Driver's SQLAllocHandle on SQL\_HANDLE\_DBC failed Possible causes: The executable file (such as the **isql** tool of unixODBC) and the database driver (**psqlodbcw.so**) depend on different library versions of ODBC, such as **libodbc.so.1** and **libodbc.so.2**. You can verify this problem by using the following method: ``` ldd `which isql` | grep odbc ldd psqlodbcw.so | grep odbc ``` If the suffix digits of the outputs **libodbc.so** are different or indicate different physical disk files, this problem exists. Both **isql** and **psqlodbcw.so** load **libodbc.so**. If different physical files are loaded, different ODBC libraries with the same function list conflict with each other in a visible domain. As a result, the database driver cannot be loaded. Solution: Uninstall the unnecessary unixODBC, such as libodbc.so.2, and create a soft link with the same name and the .so.2 suffix for the remaining libodbc.so.1 library. * FATAL: Forbid remote connection with trust method! For security purposes, the primary database node forbids access from other nodes in openGauss without authentication. To access the primary database node from inside openGauss, deploy the ODBC program on the host where the primary database node is located and set the server address to **127.0.0.1**. It is recommended that the service system be deployed outside openGauss. If it is deployed inside, database performance may be affected. * \[unixODBC]\[Driver Manager]Invalid attribute value The unixODBC version may not be the recommended one. You are advised to run the **odbcinst --version** command to check the unixODBC version in the environment. * authentication method 10 not supported. If this error occurs on an open-source client, the cause may be: The database stores only the SHA-256 hash of the password, but the open-source client supports only MD5 hashes. > \[!NOTE]NOTE > > * The database stores the hashes of user passwords instead of actual passwords. > * If a password is updated or a user is created, both types of hashes will be stored, compatible with open-source authentication protocols. > * An MD5 hash can only be generated using the original password, but the password cannot be obtained by reversing its SHA-256 hash. Passwords in the old version will only have SHA-256 hashes and not support MD5 authentication. > * The MD5 encryption algorithm has lower security and poses security risks. Therefore, you are advised to use a more secure encryption algorithm. To solve this problem, you can update the user password (see [ALTER USER](../sql_reference/alter_user.md)) or create a user (see [CREATE USER](../sql_reference/create_user.md)) having the same permissions as the faulty user. * unsupported frontend protocol 3.51: server supports 1.0 to 3.0 The database version is too early or the database is an open-source database. Use the driver of the required version to connect to the database. * FATAL: GSS authentication method is not allowed because XXXX user password is not disabled. In **pg\_hba.conf** of the target primary database node, the authentication mode is set to **gss** for authenticating the IP address of the current client. However, this authentication algorithm cannot authenticate clients. Change the authentication algorithm to **sha256** and try again. For details, see [8](#en-us_topic_0283136654_en-us_topic_0237120407_en-us_topic_0059778464_l4c0173b8af93447e91aba24005e368e5). --- --- url: /en/docs/latest/developer_guide/configuring_a_data_source_in_the_linux_os.md --- # Configuring a Data Source in the Linux OS The ODBC DRIVER (**psqlodbcw.so**) provided by openGauss can be used after it has been configured in a data source. To configure a data source, you must configure the **odbc.ini** and **odbcinst.ini** files on the server. The two files are generated during the unixODBC compilation and installation, and are saved in the **/usr/local/etc** directory by default. ## Procedure 1. Obtain the source code package of unixODBC by following link: After the download, validate the integrity based on the integrity validation algorithm provided by the community. 2. Install unixODBC. It does not matter if unixODBC of another version has been installed. Currently, unixODBC-2.2.1 is not supported. For example, to install unixODBC-2.3.0, run the commands below. 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.0.tar.gz cd unixODBC-2.3.0 # Modify the configure file. (If it does not exist, modify the configure.ac file.) Find LIB_VERSION. # Change the value of LIB_VERSION to 1:0:0 to compile a *.so.1 dynamic library with the same dependency on psqlodbcw.so. vim configure ./configure --enable-gui=no #To perform compilation on an ARM server, add the configure parameter --build=aarch64-unknown-linux-gnu. make # The installation may require root permissions. make install ``` 3. Replace the openGauss client driver. 1. Decompress the **openGauss-x.x.x-ODBC.tar.gz** package. After the decompression, the **lib** and **odbc** folders are generated. The **odbc** folder contains another **lib** folder. Copy the **psqlodbca.la**, **psqlodbca.so**, **psqlodbcw.la**, and **psqlodbcw.so** files from **/odbc/lib** to **/usr/local/lib**. 2. Copy the library in the **lib** directory obtained after decompressing **openGauss-x.x.x-ODBC.tar.gz** to the **/usr/local/lib** directory. 4. Configure a data source. 1. Configure the ODBC driver file. Add the following content to the **/usr/local/etc/odbcinst.ini** file: ``` [GaussMPP] Driver64=/usr/local/lib/psqlodbcw.so setup=/usr/local/lib/psqlodbcw.so ``` For descriptions of the parameters in the **odbcinst.ini** file, see [Table 1](#en-us_topic_0283136654_en-us_topic_0237120407_en-us_topic_0059778464_td564f21e7c8e458bbd741b09896f5d91). **Table 1** odbcinst.ini configuration parameters 2. Configure the data source file. Add the following content to the **/usr/local/etc/odbc.ini** file: ``` [MPPODBC] Driver=GaussMPP Servername=10.145.130.26 (IP address of the server where the database resides) Database=postgres (database name) Username=omm (database username) Password= (user password of the database) Port=8000 (listening port of the database) Sslmode = allow ``` For descriptions of the parameters in the **odbc.ini** file, see [Table 2](#en-us_topic_0283136654_en-us_topic_0237120407_en-us_topic_0059778464_t55845a6555f2454297b64ce47ad3d648). **Table 2** odbc.ini configuration parameters The valid values of **Sslmode** are as follows: **Table 3** Sslmode options 5. (Optional) Generate an SSL certificate. For details, see [Generating Certificates](../database_administration_guide/ssl_certificate_management.md). This step and step [6](#en-us_topic_0283136654_li1724551081815) are required only when the server and client are connected in SSL mode. Skip the two steps if the non-SSL connection mode is used. 6. (Optional) Replace an SSL certificate. For details, see [Replacing Certificates](../database_administration_guide/ssl_certificate_management.md). 7. Enable SSL mode. Declare the following environment variables and ensure that the permission for the **client.key\*** series files is set to **600**. ``` Go back to the root directory, create the .postgresql directory, and save root.crt, client.crt, client.key, client.key.cipher, client.key.rand, client.req, server.crt, server.key, server.key.cipher, server.key.rand, and server.req to the .postgresql directory. In the Unix OS, server.crt and server.key must deny the access from the external or any group. Run the following command to set this permission: chmod 0600 server.key Copy the certificate files whose names start with root.crt and server to the install/data directory of the database (the directory is the same as that of the postgresql.conf file). Modify the postgresql.conf file. ssl = on ssl_cert_file = 'server.crt' ssl_key_file = 'server.key' ssl_ca_file = 'root.crt' After modifying the parameters, restart the database. Set the sslmode parameter to require or verify-ca in the odbc.ini file. ``` 8. Configure the database server. 1. Log in as the OS user **omm** to the primary node of the database. 2. Run the following command to add NIC IP addresses or host names, with values separated by commas (,). The NICs and hosts are used to provide external services. In the following command, *NodeName* specifies the name of the current node. ``` gs_guc reload -N NodeName -I all -c "listen_addresses='localhost,192.168.0.100,10.11.12.13'" ``` If direct routing of LVS is used, add the virtual IP address (10.11.12.13) of LVS to the server listening list. You can also set **listen\_addresses** to **\*** or **0.0.0.0** to listen to all NICs, but this incurs security risks and is not recommended. 3. Run the following command to add an authentication rule to the configuration file of the primary database node. In this example, the IP address (10.11.12.13) of the client is the remote host IP address. ``` gs_guc reload -N all -I all -h "host all jack 10.11.12.13/32 sha256" ``` > \[!NOTE]NOTE > > - *** > - **-N all** indicates all hosts in openGauss. > - **-I all** indicates all instances of the host. > - **-h** specifies statements that need to be added in the **pg\_hba.conf** file. > - **all** indicates that a client can connect to any database. > - **jack** indicates the user that accesses the database. > - **\_10.11.12.13/\_*32*** indicates hosts whose IP address is 10.11.12.13 can be connected. Configure the parameter based on your network conditions. **32** indicates that there are 32 bits whose value is 1 in the subnet mask. That is, the subnet mask is 255.255.255.255. > - **sha256** indicates that the password of user **jack** is encrypted using the SHA-256 algorithm. If the ODBC client and the primary database node to connect are deployed on the same machine, you can use the local trust authentication mode. Run the following command: ``` local all all trust ``` If the ODBC client and the primary database node to connect are deployed on different machines, use the SHA-256 authentication mode. Run the following command: ``` host all all xxx.xxx.xxx.xxx/32 sha256 ``` 4. Restart openGauss. ``` gs_om -t stop gs_om -t start ``` 9. Configure the environment variables on the client. ``` vim ~/.bashrc ``` Add the following information to the configuration file: ``` export LD_LIBRARY_PATH=/usr/local/lib/:$LD_LIBRARY_PATH export ODBCSYSINI=/usr/local/etc export ODBCINI=/usr/local/etc/odbc.ini ``` 10. Run the following command to validate the addition: ``` source ~/.bashrc ``` ## Verifying the Data Source Configuration Run the **./isql -v** *MPPODBC* command (***MPPODBC*** is the data source name). * If the following information is displayed, the configuration is correct and the connection succeeds. ``` +---------------------------------------+ | Connected! | | | | sql-statement | | help [tablename] | | quit | | | +---------------------------------------+ SQL> ``` * If error information is displayed, the configuration is incorrect. Check the configuration. ## FAQs * \[UnixODBC]\[Driver Manager]Can't open lib 'xxx/xxx/psqlodbcw.so' : file not found. Possible causes: * The path configured in the **odbcinst.ini** file is incorrect. Run **ls** to check the path in the error information, and ensure that the **psqlodbcw.so** file exists and you have execute permissions on it. * The dependent library of **psqlodbcw.so** does not exist or is not in system environment variables. Run **ldd** to check the path in the error information. If **libodbc.so.1** or other UnixODBC libraries do not exist, configure UnixODBC again following the procedure provided in this section, and add the **lib** directory under its installation directory to **LD\_LIBRARY\_PATH**. If other libraries do not exist, add the **lib** directory under the ODBC driver package to **LD\_LIBRARY\_PATH**. * \[UnixODBC]connect to server failed: no such file or directory Possible causes: * An incorrect or unreachable database IP address or port was configured. Check the **Servername** and **Port** configuration items in data sources. * Server monitoring is improper. If **Servername** and **Port** are correctly configured, ensure the proper network adapter and port are monitored by following the database server configurations in the procedure in this section. * Firewall and network gatekeeper settings are improper. Check firewall settings, and ensure that the database communication port is trusted. Check to ensure network gatekeeper settings are proper (if any). * \[unixODBC]The password-stored method is not supported. Possible causes: The **sslmode** configuration item is not configured in the data sources. Solution: Set the configuration item to **allow** or a higher level. For details, see [Table 3](#en-us_topic_0283136654_en-us_topic_0237120407_en-us_topic_0059778464_table22136585143846). * Server common name "xxxx" does not match host name "xxxxx" Possible causes: When **verify-full** is used for SSL encryption, the driver checks whether the host name in certificates is the same as the actual one. Solution: To solve this problem, use **verify-ca** to stop checking host names, or generate a set of CA certificates containing the actual host names. * Driver's SQLAllocHandle on SQL\_HANDLE\_DBC failed Possible causes: The executable file (such as the **isql** tool of unixODBC) and the database driver (**psqlodbcw.so**) depend on different library versions of ODBC, such as **libodbc.so.1** and **libodbc.so.2**. You can verify this problem by using the following method: ``` ldd `which isql` | grep odbc ldd psqlodbcw.so | grep odbc ``` If the suffix digits of the outputs **libodbc.so** are different or indicate different physical disk files, this problem exists. Both **isql** and **psqlodbcw.so** load **libodbc.so**. If different physical files are loaded, different ODBC libraries with the same function list conflict with each other in a visible domain. As a result, the database driver cannot be loaded. Solution: Uninstall the unnecessary unixODBC, such as libodbc.so.2, and create a soft link with the same name and the .so.2 suffix for the remaining libodbc.so.1 library. * FATAL: Forbid remote connection with trust method! For security purposes, the primary database node forbids access from other nodes in openGauss without authentication. To access the primary database node from inside openGauss, deploy the ODBC program on the host where the primary database node is located and set the server address to **127.0.0.1**. It is recommended that the service system be deployed outside openGauss. If it is deployed inside, database performance may be affected. * \[unixODBC]\[Driver Manager]Invalid attribute value The unixODBC version may not be the recommended one. You are advised to run the **odbcinst --version** command to check the unixODBC version in the environment. * authentication method 10 not supported. If this error occurs on an open-source client, the cause may be: The database stores only the SHA-256 hash of the password, but the open-source client supports only MD5 hashes. > \[!NOTE]NOTE > > * The database stores the hashes of user passwords instead of actual passwords. > * If a password is updated or a user is created, both types of hashes will be stored, compatible with open-source authentication protocols. > * An MD5 hash can only be generated using the original password, but the password cannot be obtained by reversing its SHA-256 hash. Passwords in the old version will only have SHA-256 hashes and not support MD5 authentication. > * The MD5 encryption algorithm has lower security and poses security risks. Therefore, you are advised to use a more secure encryption algorithm. To solve this problem, you can update the user password (see [ALTER USER](../sql_reference/alter_user.md)) or create a user (see [CREATE USER](../sql_reference/create_user.md)) having the same permissions as the faulty user. * unsupported frontend protocol 3.51: server supports 1.0 to 3.0 The database version is too early or the database is an open-source database. Use the driver of the required version to connect to the database. * FATAL: GSS authentication method is not allowed because XXXX user password is not disabled. In **pg\_hba.conf** of the target primary database node, the authentication mode is set to **gss** for authenticating the IP address of the current client. However, this authentication algorithm cannot authenticate clients. Change the authentication algorithm to **sha256** and try again. For details, see [8](#en-us_topic_0283136654_en-us_topic_0237120407_en-us_topic_0059778464_l4c0173b8af93447e91aba24005e368e5). --- --- url: >- /en/docs/latest-lite/database_administration_guide/configuring_client_access_authentication.md --- # Configuring Client Access Authentication ## Background If a host needs to connect to a database remotely, you need to add information about the host in configuration file of the database system and perform client access authentication. The configuration file (**pg\_hba.conf** by default) is stored in the data directory of the database. HBA is short for host-based authentication. * The system supports the following three authentication methods, which all require the **pg\_hba.conf** file. * Host-based authentication: A server checks the configuration file based on the IP address, username, and target database of the client to determine whether the user can be authenticated. * Password authentication: A password can be an encrypted password for remote connection or a non-encrypted password for local connection. * SSL encryption: The OpenSSL is used to provide a secure connection between the server and the client. * In the **pg\_hba.conf** file, each record occupies one row and specifies an authentication rule. An empty row or a row started with a number sign (#) is neglected. * Each authentication rule consists of multiple columns separated by spaces and forward slashes (/), or spaces and tab characters. If a field is enclosed with quotation marks ("), it can contain spaces. One record cannot span different rows. ## Procedure 1. Log in as the OS user **omm** to the primary node of the database. 2. Configure the client authentication mode and enable the client to connect to the host as user **jack**. User **omm** cannot be used for remote connection. Assume you are to allow the client whose IP address is **10.10.0.30** to access the current host. ``` gs_guc reload -D datadir -h "host all jack 10.10.0.30/32 sha256" ``` > \[!NOTE]NOTE > > * Before using user **jack**, connect to the database locally and run the following command in the database to create user **jack**: > ```` > ``` ```` ```` > openGauss=# CREATE USER jack PASSWORD 'xxxxxx'; > ``` ```` > ``` >- **-D** _datadir_ indicates the data directory of the host. ``` ```` >- **-h** specifies statements that need to be added in the **pg\_hba.conf** file. >- **all** indicates that a client can connect to any database. >- **jack** indicates the user that accesses the database. >- _10.10.0.30__/32_ indicates that only the client whose IP address is **10.10.0.30** can connect to the host. The specified IP address must be different from those used in openGauss. **32** indicates that there are 32 bits whose value is 1 in the subnet mask. That is, the subnet mask is 255.255.255.255. >- **sha256** indicates that the password of user **jack** is encrypted using the SHA-256 algorithm. This command adds a rule to the **pg\_hba.conf** file corresponds to the primary node of the database. The rule is used to authenticate clients that access database primary node. Each record in the **pg\_hba.conf** file can be in one of the following four formats. For parameter description of the four formats, see [Configuration File Reference](configuration_file_reference.md). ``` local DATABASE USER METHOD [OPTIONS] host DATABASE USER ADDRESS METHOD [OPTIONS] hostssl DATABASE USER ADDRESS METHOD [OPTIONS] hostnossl DATABASE USER ADDRESS METHOD [OPTIONS] ``` During authentication, the system checks records in the **pg\_hba.conf** file in sequence for connection requests, so the record sequence is vital. >[!NOTE]NOTE >Configure records in the **pg\_hba.conf** file from top to bottom based on communication and format requirements in the descending order of priorities. The IP addresses of openGauss and added hosts are of the highest priority and should be configured prior to those manually configured by users. If the IP addresses manually configured by users and those of added hosts are in the same network segment, delete the manually configured IP addresses before the scale-out and configure them after the scale-out. The suggestions on configuring authentication rules are as follows: - Records placed at the front have strict connection parameters but weak authentication methods. - Records placed at the end have weak connection parameters but strict authentication methods. >[!NOTE]NOTE >- If a user wants to connect to a specified database, the user must be authenticated by the rules in the **pg\_hba.conf** file and have the **CONNECT** permission for the database. If you want to restrict a user from connecting to certain databases, you can grant or revoke the user's **CONNECT** permission, which is easier than setting rules in the **pg\_hba.conf** file. >- The **trust** authentication mode is insecure for a connection between openGauss and an external client. In this case, set the authentication mode to **sha256**. >- After the **pg\_hba.conf** configuration is modified using the **gs\_guc reload** command, the modification takes effect when a new session is created. If you run the **gs\_guc set** command to set parameters or directly edit the **pg\_hba.conf** file to modify parameters, you need to restart the database or run the **gs\_guc reload** command again for the modification to take effect. ```` ## Exception Handling There are many reasons for a user authentication failure. You can view an error message returned from a server to a client to determine the exact cause. [Table 1](#en-us_topic_0283136866_en-us_topic_0237121090_en-us_topic_0059778856_t451d737a3917467b9691ba1306766cdb) lists common error messages and solutions to these errors. **Table 1** Error messages ## Examples ``` TYPE DATABASE USER ADDRESS METHOD "local" is for Unix domain socket connections only # Only the user specified by the -U parameter during installation is allowed to establish a connection from the local server. local all all trust IPv4 local connections: # User jack is allowed to connect to any database from the 10.10.0.50 host. The SHA-256 algorithm is used to encrypt the password. host all jack 10.10.0.50/32 sha256 # Any user is allowed to connect to any database from a host on the 10.10.0.0/24 network segment. The SHA-256 algorithm is used to encrypt the password and SSL transmission is used. hostssl all all 10.10.0.0/24 sha256 ``` --- --- url: >- /en/docs/latest/database_administration_guide/configuring_client_access_authentication.md --- # Configuring Client Access Authentication ## Background If a host needs to connect to a database remotely, you need to add information about the host in configuration file of the database system and perform client access authentication. The configuration file (**pg\_hba.conf** by default) is stored in the data directory of the database. HBA is short for host-based authentication. * The system supports the following three authentication methods, which all require the **pg\_hba.conf** file. * Host-based authentication: A server checks the configuration file based on the IP address, username, and target database of the client to determine whether the user can be authenticated. * Password authentication: A password can be an encrypted password for remote connection or a non-encrypted password for local connection. * SSL encryption: The OpenSSL is used to provide a secure connection between the server and the client. * In the **pg\_hba.conf** file, each record occupies one row and specifies an authentication rule. An empty row or a row started with a number sign (#) is neglected. * Each authentication rule consists of multiple columns separated by spaces and forward slashes (/), or spaces and tab characters. If a field is enclosed with quotation marks ("), it can contain spaces. One record cannot span different rows. ## Procedure 1. Log in as the OS user **omm** to the primary node of the database. 2. Configure the client authentication mode and enable the client to connect to the host as user **jack**. User **omm** cannot be used for remote connection. Assume you are to allow the client whose IP address is **10.10.0.30** to access the current host. ``` gs_guc set -N all -I all -h "host all jack 10.10.0.30/32 sha256" ``` > \[!NOTE]NOTE > > * Before using user **jack**, connect to the database locally and run the following command in the database to create user **jack**: > ```` > ``` sql ```` ```` > CREATE USER jack PASSWORD 'Test@123'; > ``` ```` > ``` >- **-N all** indicates all hosts in openGauss. ``` ``` >- **-I all** indicates all instances on the host. >- **-h** specifies statements that need to be added in the **pg\_hba.conf** file. >- **all** indicates that a client can connect to any database. >- **jack** indicates the user that accesses the database. >- *10.10.0.30*/*32* indicates that only the client whose IP address is **10.10.0.30** can connect to the host. The specified IP address must be different from those used in openGauss. **32** indicates that there are 32 bits whose value is 1 in the subnet mask. That is, the subnet mask is 255.255.255.255. >- **sha256** indicates that the password of user **jack** is encrypted using the SHA-256 algorithm. ``` This command adds a rule to the **pg\_hba.conf** file corresponds to the primary node of the database. The rule is used to authenticate clients that access primary node. Each record in the **pg\_hba.conf** file can be in one of the following four formats. For parameter description of the four formats, see [Configuration File Reference](configuration_file_reference.md). ``` local DATABASE USER METHOD [OPTIONS] host DATABASE USER ADDRESS METHOD [OPTIONS] hostssl DATABASE USER ADDRESS METHOD [OPTIONS] hostnossl DATABASE USER ADDRESS METHOD [OPTIONS] ``` During authentication, the system checks records in the **pg\_hba.conf** file in sequence for connection requests, so the record sequence is vital. > \[!NOTE]NOTE\ > Configure records in the **pg\_hba.conf** file from top to bottom based on communication and format requirements in the descending order of priorities. The IP addresses of the openGauss cluster and added hosts are of the highest priority and should be configured prior to those manually configured by users. If the IP addresses manually configured by users and those of added hosts are in the same network segment, delete the manually configured IP addresses before the scale-out and configure them after the scale-out. The suggestions on configuring authentication rules are as follows: * Records placed at the front have strict connection parameters but weak authentication methods. * Records placed at the end have weak connection parameters but strict authentication methods. > \[!NOTE]NOTE > > * If a user wants to connect to a specified database, the user must be authenticated by the rules in the **pg\_hba.conf** file and have the **CONNECT** permission for the database. If you want to restrict a user from connecting to certain databases, you can grant or revoke the user's **CONNECT** permission, which is easier than setting rules in the **pg\_hba.conf** file. > * The **trust** authentication mode is insecure for a connection between the openGauss and a client outside the cluster. In this case, set the authentication mode to **sha256**. ## Exception Handling There are many reasons for a user authentication failure. You can view an error message returned from a server to a client to determine the exact cause. [Table 1](#en-us_topic_0237121090_en-us_topic_0059778856_t451d737a3917467b9691ba1306766cdb) lists common error messages and solutions to these errors. **Table 1** Error messages ## Example ``` TYPE DATABASE USER ADDRESS METHOD "local" is for Unix domain socket connections only #Allow only the user specified by the -U parameter during installation to establish a connection from the local server. local all all trust IPv4 local connections: #User jack is allowed to connect to any database from the 10.10.0.50 host. The SHA-256 algorithm is used to encrypt the password. host all jack 10.10.0.50/32 sha256 #Any user is allowed to connect to any database from a host on the 10.10.0.0/24 network segment. The SHA-256 algorithm is used to encrypt the password and SSL transmission is used. hostssl all all 10.10.0.0/24 sha256 ``` --- --- url: >- /en/docs/latest-lite/database_administration_guide/configuring_file_permission_security_policies.md --- # Configuring File Permission Security Policies ## Background During its installation, the database sets permissions for its files, including files (such as log files) generated during the running process. File permissions are set as follows: * The permission of program directories in the database is set to **0750**. * The permission for data file directories in the database is set to **0700**. During database deployment, the directory specified by the **tmpMppdbPath** parameter in the XML configuration file is created for storing **.s.PGSQL.\*** files. If the parameter is not specified, the **/tmp/***$USER***\_mppdb** directory is created. The directory and file permission is set to **0700**. * The permissions of data files and audit logs of the database, as well as data files generated by other database programs, are set to **0600**. The permission of run logs is equal to or lower than **0640** by default. * Common OS users are not allowed to modify or delete database files and log files. ## Directory and File Permissions of Database Programs [Table 1](#en-us_topic_0283137309_en-us_topic_0237121115_en-us_topic_0059779254_t0da233846f2544f39362bcf53de94799) lists some of program directories and file permissions of the installed database. **Table 1** Program directories and file permissions ## Suggestion During the installation, the database automatically sets permissions for its files, including files (such as log files) generated during the running process. The specified permissions meet permission 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. --- --- url: >- /en/docs/latest/database_administration_guide/configuring_file_permission_security_policies.md --- # Configuring File Permission Security Policies ## Background During its installation, the database sets permissions for its files, including files (such as log files) generated during the running process. File permissions are set as follows: * The permission of program directories in the database is set to **0750**. * The permission for data file directories in the database is set to **0700**. During openGauss deployment, the directory specified by the **tmpMppdbPath** parameter in the XML configuration file is created for storing **.s.PGSQL.\*** files. If the parameter is not specified, the **/tmp/***$USER***\_mppdb** directory is created. The directory and file permission is set to **0700**. * The permissions of data files and audit logs of the database, as well as data files generated by other database programs, are set to **0600**. The permission of run logs is equal to or lower than **0640** by default. * Common OS users are not allowed to modify or delete database files and log files. ## Directory and File Permissions of Database Programs [Table 1](#en-us_topic_0237121115_en-us_topic_0059779254_t0da233846f2544f39362bcf53de94799) lists some of program directories and file permissions of the installed database. **Table 1** Program directories and file permissions ## Suggestion During the installation, the database automatically sets permissions for its files, including files (such as log files) generated during the running process. The specified permissions meet permission 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. --- --- url: /en/docs/latest/performance_tuning_guide/configuring_llvm.md --- # Configuring LLVM Low Level Virtual Machine (LLVM) dynamic compilation can be used to generate customized machine code for each query to replace original common functions. Query performance is improved by reducing redundant judgment conditions and virtual function calls, and by making local data more accurate during actual queries. LLVM needs to consume extra time to pre-generate intermediate representation (IR) and compile it into codes. Therefore, if the data volume is small or if a query itself consumes less time, the performance deteriorates. * **[LLVM Application Scenarios and Restrictions](llvm_application_scenarios_and_restrictions.md)** * **[Other Factors Affecting LLVM Performance](other_factors_affecting_llvm_performance.md)** * **[Recommended Suggestions for LLVM](recommended_suggestions_for_llvm.md)** --- --- url: /en/docs/latest-lite/performance_tuning_guide/configuring_smp.md --- # Configuring SMP This section describes the usage restrictions, application scenarios, and configuration guide of symmetric multiprocessing (SMP). * **[SMP Application Scenarios and Restrictions](smp_application_scenarios_and_restrictions.md)** * **[Resource Impact on SMP Performance](resource_impact_on_smp_performance.md)** * **[Other Factors Affecting SMP Performance](other_factors_affecting_smp_performance.md)** * **[Suggestions for Using SMP](suggestions_for_using_smp.md)** --- --- url: /en/docs/latest/performance_tuning_guide/configuring_smp.md --- # Configuring SMP This section describes the usage restrictions, application scenarios, and configuration guide of symmetric multiprocessing (SMP). * **[SMP Application Scenarios and Restrictions](smp_application_scenarios_and_restrictions.md)** * **[Resource Impact on SMP Performance](resource_impact_on_smp_performance.md)** * **[Other Factors Affecting SMP Performance](other_factors_affecting_smp_performance.md)** * **[Suggestions for Using SMP](suggestions_for_using_smp.md)** --- --- url: /en/docs/latest-lite/database_administration_guide/configuring_tde.md --- # Configuring TDE ## Overview Transparent data encryption (TDE) is used to encrypt data when the database writes the data to the storage medium and automatically decrypts the data when reading the data from the storage medium. This prevents attackers from reading data in the data file without database authentication, solving the static data leakage problem. This function is almost transparent to the application layer. You can determine whether to enable the transparent data encryption function as required. ## Prerequisites * Data encryption keys (DEKs) must be protected by KMS so that the database can access KMS. You can apply for KMS on the [Data Encryption Workshop (DEW)](https://www.huaweicloud.com/product/dew.html). * The GUC parameter **[enable\_tde](../database_reference/security-configuration.md#section17961238192110)** has been set to **on** to enable the TDE function of the database. In addition, you need to correctly set the **[tde\_cmk\_id](../database_reference/security-configuration.md#section4132027193410)** parameter which indicates the master key ID of the database instance. ## Background The current version interconnects with Huawei Cloud KMS to support table-level key storage and row-store table encryption. The specifications are as follows: * Encryption of a row-store table stored as a heap is supported. * Column-store encryption, materialized view encryption, and Ustore-based encryption are not supported. * Indexes, sequences, Xlogs, MOTs, and system catalogs cannot be encrypted. * You can specify an encryption algorithm when creating a table. Once specified, the encryption algorithm cannot be changed. If **enable\_tde** is set to **on** but the encryption algorithm **encrypt\_algo** is not specified when a table is created, the AES\_128\_CTR encryption algorithm is used by default. * If the encryption function is not enabled or the encryption algorithm is not specified when a table is created, the table cannot be switched to an encrypted table. * For a table that has been assigned an encryption key, switching between the encrypted and unencrypted states of the table does not change the key or encryption algorithm. * Data key rotation is supported only when the table encryption function is enabled. * Cross-region primary/standby synchronization of multiple copies for a single database instance is not supported. Cross-region scale-out of a single database instance is not supported. Cross-region backup and restoration, database instance DR, and data migration are not supported. * In hybrid cloud scenarios, if the Huawei Cloud KMS and management plane functions are used, TDE is supported. For other KMS services, TDE is not supported if no compatible API is available. * The query performance of encrypted tables is lower than that of non-encrypted tables. If high performance is required, exercise caution when enabling the encryption function. ## Key Management Mechanism In TDE, data encryption and decryption depend on a secure and reliable key management mechanism. This function uses a three-layer key structure to implement the key management mechanism, including the root key (RK), CMK, and data encryption key (DEK). CMKs are encrypted and protected by RKs, and DEKs are encrypted and protected by CMKs. DEKs are used to encrypt and decrypt user data. Each table corresponds to a DEK. RKs and CMKs are stored in KMS. You can apply to the KMS for creating DEKs. After the creation is successful, the key plaintext and ciphertext are returned. The DEK plaintext is cached in a hash table in the memory to reduce the KMS access frequency and improve performance. The key plaintext is stored only in the memory and is not flushed to the disk. In addition, the key plaintext that is not frequently used can be automatically deleted. Only the key plaintext used in the last one day is stored. The DEK ciphertext is stored in the database and flushed to the disk for persistence. When encrypting or decrypting user table data, if the corresponding key plaintext does not exist in the memory, apply to the KMS for decrypting the DEK before using it. ## Table-Level Encryption Solution When creating a table, you can specify whether to encrypt the table and the encryption algorithm to be used. The encryption algorithm can be AES\_128\_CTR or SM4\_CTR, which cannot be changed once specified. If an encrypted table is created, the database automatically applies for a DEK for the table and saves the encryption algorithm, key ciphertext, and corresponding CMK ID in the **reloptions** column of the pg\_class system catalog in keyword=value format. You can switch an encrypted table to a non-encrypted table or switch a non-encrypted table to an encrypted table. If the encryption function is not enabled when a table is created, the table cannot be switched to an encrypted table. For encrypted tables, DEK rotation is supported. After the key rotation, the data encrypted using the old key is decrypted using the old key, and the newly written data is encrypted using the new key. The encryption algorithm is not changed during key rotation. For a row-store table, the minimum data unit for each encryption and decryption is an 8 KB page. Each time the page is encrypted, an IV value is generated through the secure random number API, and the IV value, key ciphertext, and CMK ID are stored on the page and written to the storage medium. For an encrypted table, the encryption key information needs to be saved on the page. The occupied storage space increases by about 2.5% compared with that when the table is not encrypted. ## Creating an Encrypted Table Log in to the database, create the encrypted table **tde\_test1**, enable the encryption function, and set the encryption algorithm to **AES\_128\_CTR**. ``` openGauss=# CREATE TABLE tde_test (a int, b text) with (enable_tde = on, encrypt_algo = 'AES_128_CTR'); ``` Create the encrypted table **tde\_test2** and enable the encryption function. If the encryption algorithm is not specified, the default encryption algorithm is **AES\_128\_CTR**. ``` openGauss=# CREATE TABLE tde_test2 (a int, b text) with (enable_tde = on); ``` Create the encrypted table **tde\_test3**, disable the encryption function, and set the encryption algorithm to **SM4\_CTR**. ``` openGauss=# CREATE TABLE tde_test3 (a int, b text) with (enable_tde = off, encrypt_algo = 'SM4_CTR'); ``` ## Setting the Encryption Parameter of an Encrypted Table Log in to the database and set the encryption parameter of the **tde\_test1** table to **off**. ``` openGauss=# ALTER TABLE tde_test1 SET (enable_tde=off); ``` Set the encryption parameter of the **tde\_test1** table to **on**. ``` openGauss=# ALTER TABLE tde_test1 SET (enable_tde=on); ``` ## Rotating Keys of an Encrypted Table Log in to the database and rotate the keys of the encrypted table **tde\_test1**. ``` openGauss=# ALTER TABLE tde_test1 ENCRYPTION KEY ROTATION; ``` --- --- url: /en/docs/latest/database_administration_guide/configuring_tde.md --- # Configuring TDE ## Overview Transparent data encryption (TDE) is used to encrypt data when the database writes the data to the storage medium and automatically decrypts the data when reading the data from the storage medium. This prevents attackers from reading data in the data file without database authentication, solving the static data leakage problem. This function is almost transparent to the application layer. You can determine whether to enable the transparent data encryption function as required. ## Prerequisites * Data encryption keys (DEKs) must be protected by KMS so that the database can access KMS. You can apply for KMS on the [Data Encryption Workshop (DEW)](https://www.huaweicloud.com/product/dew.html). * The GUC parameter **[enable\_tde](../database_reference/security_configuration.md#section17961238192110)** has been set to **on** to enable the TDE function of the database. In addition, you need to correctly set the **[tde\_cmk\_id](../database_reference/security_configuration.md#section4132027193410)** parameter which indicates the master key ID of the database instance. ## Background The current version interconnects with Huawei Cloud KMS to support table-level key storage and row-store table encryption. The specifications are as follows: * Encryption of a row-store table stored as a heap is supported. * Column-store encryption, materialized view encryption, and Ustore-based encryption are not supported. * Indexes, sequences, Xlogs, MOTs, and system catalogs cannot be encrypted. * You can specify an encryption algorithm when creating a table. Once specified, the encryption algorithm cannot be changed. If **enable\_tde** is set to **on** but the encryption algorithm **encrypt\_algo** is not specified when a table is created, the AES\_128\_CTR encryption algorithm is used by default. * If the encryption function is not enabled or the encryption algorithm is not specified when a table is created, the table cannot be switched to an encrypted table. * For a table that has been assigned an encryption key, switching between the encrypted and unencrypted states of the table does not change the key or encryption algorithm. * Data key rotation is supported only when the table encryption function is enabled. * Cross-region primary/standby synchronization of multiple copies for a single database instance is not supported. Cross-region scale-out of a single database instance is not supported. Cross-region backup and restoration, database instance DR, and data migration are not supported. * In hybrid cloud scenarios, if the Huawei Cloud KMS and management plane functions are used, TDE is supported. For other KMS services, TDE is not supported if no compatible API is available. * The query performance of encrypted tables is lower than that of non-encrypted tables. If high performance is required, exercise caution when enabling the encryption function. ## Key Management Mechanism In TDE, data encryption and decryption depend on a secure and reliable key management mechanism. This function uses a three-layer key structure to implement the key management mechanism, including the root key (RK), CMK, and data encryption key (DEK). CMKs are encrypted and protected by RKs, and DEKs are encrypted and protected by CMKs. DEKs are used to encrypt and decrypt user data. Each table corresponds to a DEK. RKs and CMKs are stored in KMS. You can apply to the KMS for creating DEKs. After the creation is successful, the key plaintext and ciphertext are returned. The DEK plaintext is cached in a hash table in the memory to reduce the KMS access frequency and improve performance. The key plaintext is stored only in the memory and is not flushed to the disk. In addition, the key plaintext that is not frequently used can be automatically deleted. Only the key plaintext used in the last one day is stored. The DEK ciphertext is stored in the database and flushed to the disk for persistence. When encrypting or decrypting user table data, if the corresponding key plaintext does not exist in the memory, apply to the KMS for decrypting the DEK before using it. ## Table-Level Encryption Solution When creating a table, you can specify whether to encrypt the table and the encryption algorithm to be used. The encryption algorithm can be AES\_128\_CTR or SM4\_CTR, which cannot be changed once specified. If an encrypted table is created, the database automatically applies for a DEK for the table and saves the encryption algorithm, key ciphertext, and corresponding CMK ID in the **reloptions** column of the pg\_class system catalog in keyword=value format. You can switch an encrypted table to a non-encrypted table or switch a non-encrypted table to an encrypted table. If the encryption function is not enabled when a table is created, the table cannot be switched to an encrypted table. For encrypted tables, DEK rotation is supported. After the key rotation, the data encrypted using the old key is decrypted using the old key, and the newly written data is encrypted using the new key. The encryption algorithm is not changed during key rotation. For a row-store table, the minimum data unit for each encryption and decryption is an 8 KB page. Each time the page is encrypted, an IV value is generated through the secure random number API, and the IV value, key ciphertext, and CMK ID are stored on the page and written to the storage medium. For an encrypted table, the encryption key information needs to be saved on the page. The occupied storage space increases by about 2.5% compared with that when the table is not encrypted. ## Creating an Encrypted Table Log in to the database, create the encrypted table **tde\_test1**, enable the encryption function, and set the encryption algorithm to **AES\_128\_CTR**. ``` openGauss=# CREATE TABLE tde_test (a int, b text) with (enable_tde = on, encrypt_algo = 'AES_128_CTR'); ``` Create the encrypted table **tde\_test2** and enable the encryption function. If the encryption algorithm is not specified, the default encryption algorithm is **AES\_128\_CTR**. ``` openGauss=# CREATE TABLE tde_test2 (a int, b text) with (enable_tde = on); ``` Create the encrypted table **tde\_test3**, disable the encryption function, and set the encryption algorithm to **SM4\_CTR**. ``` openGauss=# CREATE TABLE tde_test3 (a int, b text) with (enable_tde = off, encrypt_algo = 'SM4_CTR'); ``` ## Setting the Encryption Parameter of an Encrypted Table Log in to the database and set the encryption parameter of the **tde\_test1** table to **off**. ``` openGauss=# ALTER TABLE tde_test1 SET (enable_tde=off); ``` Set the encryption parameter of the **tde\_test1** table to **on**. ``` openGauss=# ALTER TABLE tde_test1 SET (enable_tde=on); ``` ## Rotating Keys of an Encrypted Table Log in to the database and rotate the keys of the encrypted table **tde\_test1**. ``` openGauss=# ALTER TABLE tde_test1 ENCRYPTION KEY ROTATION; ``` --- --- url: /en/docs/latest/performance_tuning_guide/configuring_ustore.md --- # Configuring Ustore The Ustore storage engine, also called the in-place update storage engine, is a new storage mode added to the openGauss kernel. The row storage engine used by the earlier openGauss versions is in append update mode. Append update has good performance in service addition, deletion, and heap only tuple (HOT) update (that is, update on the same page). However, recycling is not efficient in cross-data-page non-HOT update scenarios. Therefore, Ustore comes into being. ## Design Principle Ustore stores valid data of the latest version and junk data of earlier versions separately. The valid data of the latest version is stored on the data page, and an independent UNDO space is created for managing the junk data of earlier versions in a unified manner. Therefore, the data space does not expand due to frequent updates, and the junk data is recycled more efficiently. Ustore adopts the NUMA-aware UNDO subsystem design, which enables the UNDO subsystem to be effectively expanded on the multi-core platform. In addition, Ustore adopts the multi-version index technology to clear indexes and improve the efficiency of reclaiming and reusing storage space. Ustore works with the UNDO space to implement more efficient and comprehensive flashback query and recycle bin mechanisms, quickly roll back misoperations, and provide abundant enterprise-level functions for openGauss. ## Core Advantages * **High performance**: For services with different loads, such as insertion, update, and deletion, the performance and resource usage are relatively balanced. The in-place update mode is recommended in frequent update scenarios, featuring higher and more stable performance. It is suitable for typical OLTP service scenarios that require **short** transactions, **frequent** updates, and **high** performance. * **Efficient storage**: Maximizes in-place update, greatly saving space. Rollback segments and data pages are stored separately, providing more efficient and stable I/O usage. The UNDO subsystem uses the NUMA-aware design and has better multi-core scalability. The UNDO space is allocated and reclaimed in a unified manner, improving the reuse efficiency and storage space usage. * **Fine-grained resource control**: The Ustore engine provides multi-dimensional transaction monitoring. It monitors transaction running based on the transaction running duration, size of the UNDO space used by a single transaction, and overall UNDO space limit to prevent abnormal and unexpected behaviors. This feature enables database administrators to regulate and restrict the use of database system resources. Ustore provides stable performance in scenarios where data is frequently updated, enabling service systems to run more stably and adapt to more service scenarios and workloads, especially core financial service scenarios that have higher requirements on performance and stability. ## Usage Guide Ustore coexists with the original append update storage engine (Astore). Ustore shields the implementation details of the storage layer. The SQL syntax is basically the same as that of the original Astore storage engine. The only difference lies in table creation and index creation. * **Table creation** Ustore contains undo logs. Before creating a table, you need to set **undo\_zone\_count** in the **postgresql.conf** file. This parameter indicates the number of undo logs. The recommended value is **16384**, that is, **undo\_zone\_count=16384**. After the configuration is complete, restart the database. \[postgresql.conf] ``` undo_zone_count=16384 ``` * **Method 1: Specify the storage engine type when creating a table.** ``` create table test(id int, name varchar(10)) with (storage_type=ustore); ``` * **Method 2: Specify Ustore by configuring a GUC parameter.** 1. Before starting a database, set **enable\_default\_ustore\_table** to **on** in **postgresql.conf** to specify that Ustore is used when a user creates a table by default. \[postgresql.conf] ``` enable_default_ustore_table=on ``` 2. Create a table. ``` create table test(id int, name varchar(10)); ``` * **Index creation** The index used by Ustore is UBtree. UBtree is developed for the Ustore storage engine and is the only index type supported by Ustore. Taking the following table **test** as an example, add an index **UBtree** to the **age** column of the **test** table. ``` openGauss=# \d+ test Table "public.test" Column | Type | Modifiers | Storage | Stats target | Description --------+-----------------------+-----------+----------+--------------+------------- id | integer | | plain | | age | integer | | plain | | name | character varying(10) | | extended | | ``` * **Method 1: If the index type is not specified, a UBtree index is created by default.** ``` openGauss=# create index ubt_idx on test(age); ``` ``` openGauss=# \d+ test Table "public.test" Column | Type | Modifiers | Storage | Stats target | Description --------+-----------------------+-----------+----------+--------------+------------- id | integer | | plain | | age | integer | | plain | | name | character varying(10) | | extended | | Indexes: "ubt_idx" ubtree (age) WITH (storage_type=USTORE) TBALESPACE pg_default Has OIDs: no Options: orientation=row, storage_type=ustore, compression=no ``` * **Method 2: When creating an index, use the using keyword to set the index type to ubtree.** ``` openGauss=# create index ubt_idx on test using ubtree(age); ``` ``` openGauss=# \d+ test Table "public.test" Column | Type | Modifiers | Storage | Stats target | Description --------+-----------------------+-----------+----------+--------------+------------- id | integer | | plain | | age | integer | | plain | | name | character varying(10) | | extended | | Indexes: "ubt_idx" ubtree (age) WITH (storage_type=USTORE) TBALESPACE pg_default Has OIDs: no Options: orientation=row, storage_type=ustore, compression=no ``` --- --- url: /en/docs/latest-lite/performance_tuning_guide/configuring_vectorization.md --- # Configuring Vectorization The openGauss database supports the row executor and vectorized executor for processing row-store tables and column-store tables, respectively. * More data is read in one batch at a time, saving I/O resources. * There are a large number of records in a batch, and the CPU cache hit rate increases. * In pipeline mode, the number of function calls is small. * A batch of data is processed at a time, which is efficient. Therefore, the openGauss database can achieve better query performance for complex analytical queries. However, column-store tables do not perform well in data insertion and update. Therefore, column-store tables cannot be used for services with frequent data insertion and update. To improve the query performance of row-store tables in complex analytical queries, the openGauss database provides the vectorized executor for processing row-store tables. You can set **[try\_vector\_engine\_strategy](https://docs.opengauss.org/en/docs/latest-lite/database_reference/optimizer_method_configuration.html#section145867222412)** to convert query statements containing row-store tables into vectorized execution plans for execution. This conversion is not applicable to all query scenarios. If a query statement contains operations such as expression calculation, multi-table join, and aggregation, the performance can be improved by converting the statement to a vectorized execution plan. Theoretically, converting a row-store table to a vectorized execution plan causes conversion overheads and performance deterioration. After the foregoing expression calculation, join operation, and aggregation operations are converted into vectorized execution plans, performance can be improved. The performance improvement must be higher than the overheads generated by the conversion. This determines whether the conversion is required. Take TPCH Q1 as an example. When the row executor is used, the execution time of the scan operator is 405210 ms, and the execution time of the aggregation operation is 2618964 ms. After the vectorized executor is used, the execution time of the scan operator (SeqScan and VectorAdapter) is 470840 ms, and the execution time of the aggregation operation is 212384 ms. So the query performance can be improved. Execution plan of the TPCH Q1 row executor: ``` QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------- Sort (cost=43539570.49..43539570.50 rows=6 width=260) (actual time=3024174.439..3024174.439 rows=4 loops=1) Sort Key: l_returnflag, l_linestatus Sort Method: quicksort Memory: 25kB -> HashAggregate (cost=43539570.30..43539570.41 rows=6 width=260) (actual time=3024174.396..3024174.403 rows=4 loops=1) Group By Key: l_returnflag, l_linestatus -> Seq Scan on lineitem (cost=0.00..19904554.46 rows=590875396 width=28) (actual time=0.016..405210.038 rows=596140342 loops=1) Filter: (l_shipdate <= '1998-10-01 00:00:00'::timestamp without time zone) Rows Removed by Filter: 3897560 Total runtime: 3024174.578 ms (9 rows) ``` Execution plan of the TPCH Q1 vectorized executor: ``` QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------------------------------- Row Adapter (cost=43825808.18..43825808.18 rows=6 width=298) (actual time=683224.925..683224.927 rows=4 loops=1) -> Vector Sort (cost=43825808.16..43825808.18 rows=6 width=298) (actual time=683224.919..683224.919 rows=4 loops=1) Sort Key: l_returnflag, l_linestatus Sort Method: quicksort Memory: 3kB -> Vector Sonic Hash Aggregate (cost=43825807.98..43825808.08 rows=6 width=298) (actual time=683224.837..683224.837 rows=4 loops=1) Group By Key: l_returnflag, l_linestatus -> Vector Adapter(type: BATCH MODE) (cost=19966853.54..19966853.54 rows=596473861 width=66) (actual time=0.982..470840.274 rows=596140342 loops=1) Filter: (l_shipdate <= '1998-10-01 00:00:00'::timestamp without time zone) Rows Removed by Filter: 3897560 -> Seq Scan on lineitem (cost=0.00..19966853.54 rows=596473861 width=66) (actual time=0.364..199301.737 rows=600037902 loops=1) Total runtime: 683225.564 ms (11 rows) ``` --- --- url: /en/docs/latest/performance_tuning_guide/configuring_vectorization.md --- # Configuring Vectorization The openGauss database supports the row executor and vectorized executor for processing row-store tables and column-store tables, respectively. * More data is read in one batch at a time, saving I/O resources. * There are a large number of records in a batch, and the CPU cache hit rate increases. * In pipeline mode, the number of function calls is small. * A batch of data is processed at a time, which is efficient. Therefore, the openGauss database can achieve better query performance for complex analytical queries. However, column-store tables do not perform well in data insertion and update. Therefore, column-store tables cannot be used for services with frequent data insertion and update. To improve the query performance of row-store tables in complex analytical queries, the openGauss database provides the vectorized executor for processing row-store tables. You can set **[try\_vector\_engine\_strategy](https://docs.opengauss.org/en/docs/latest/database_reference/optimizer_method_configuration.html#section145867222412)** to convert query statements containing row-store tables into vectorized execution plans for execution. This conversion is not applicable to all query scenarios. If a query statement contains operations such as expression calculation, multi-table join, and aggregation, the performance can be improved by converting the statement to a vectorized execution plan. Theoretically, converting a row-store table to a vectorized execution plan causes conversion overheads and performance deterioration. After the foregoing expression calculation, join operation, and aggregation operations are converted into vectorized execution plans, performance can be improved. The performance improvement must be higher than the overheads generated by the conversion. This determines whether the conversion is required. Take TPCH Q1 as an example. When the row executor is used, the execution time of the scan operator is 405210 ms, and the execution time of the aggregation operation is 2618964 ms. After the vectorized executor is used, the execution time of the scan operator (SeqScan and VectorAdapter) is 470840 ms, and the execution time of the aggregation operation is 212384 ms. So the query performance can be improved. Execution plan of the TPCH Q1 row executor: ``` QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------- Sort (cost=43539570.49..43539570.50 rows=6 width=260) (actual time=3024174.439..3024174.439 rows=4 loops=1) Sort Key: l_returnflag, l_linestatus Sort Method: quicksort Memory: 25kB -> HashAggregate (cost=43539570.30..43539570.41 rows=6 width=260) (actual time=3024174.396..3024174.403 rows=4 loops=1) Group By Key: l_returnflag, l_linestatus -> Seq Scan on lineitem (cost=0.00..19904554.46 rows=590875396 width=28) (actual time=0.016..405210.038 rows=596140342 loops=1) Filter: (l_shipdate <= '1998-10-01 00:00:00'::timestamp without time zone) Rows Removed by Filter: 3897560 Total runtime: 3024174.578 ms (9 rows) ``` Execution plan of the TPCH Q1 vectorized executor: ``` QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------------------------------- Row Adapter (cost=43825808.18..43825808.18 rows=6 width=298) (actual time=683224.925..683224.927 rows=4 loops=1) -> Vector Sort (cost=43825808.16..43825808.18 rows=6 width=298) (actual time=683224.919..683224.919 rows=4 loops=1) Sort Key: l_returnflag, l_linestatus Sort Method: quicksort Memory: 3kB -> Vector Sonic Hash Aggregate (cost=43825807.98..43825808.08 rows=6 width=298) (actual time=683224.837..683224.837 rows=4 loops=1) Group By Key: l_returnflag, l_linestatus -> Vector Adapter(type: BATCH MODE) (cost=19966853.54..19966853.54 rows=596473861 width=66) (actual time=0.982..470840.274 rows=596140342 loops=1) Filter: (l_shipdate <= '1998-10-01 00:00:00'::timestamp without time zone) Rows Removed by Filter: 3897560 -> Seq Scan on lineitem (cost=0.00..19966853.54 rows=596473861 width=66) (actual time=0.364..199301.737 rows=600037902 loops=1) Total runtime: 683225.564 ms (11 rows) ``` --- --- url: /en/docs/latest/getting_started/confirming_connection_information.md --- # Confirming Connection Information You can use a client tool to connect to a database through a the primary node of the database in the database. Before the connection, obtain the IP address and the primary node of the database port number of the server where the primary node of the database is deployed. ## Procedure 1. Log in as the OS user **omm** to the primary node of the database. 2. Run the **gs\_ctl query -D /home/dbuser/env\_test/data** command to query openGauss instances. ``` gs_ctl query -D /home/dbuser/env_test/data ``` ``` [2022-01-08 17:21:26.569][15657][][gs_ctl]: gs_ctl query ,datadir is /home/dbuser/env_test/data HA state: local_role : Primary static_connections : 1 db_state : Normal detail_information : Normal Senders info: sender_pid : 15464 local_role : Primary peer_role : Standby peer_state : Normal state : Streaming sender_sent_location : 0/4000148 sender_write_location : 0/4000148 sender_flush_location : 0/4000148 sender_replay_location : 0/4000148 receiver_received_location : 0/4000148 receiver_write_location : 0/4000148 receiver_flush_location : 0/4000148 receiver_replay_location : 0/4000148 sync_percent : 100% sync_state : Sync sync_priority : 1 sync_most_available : Off channel : 10.244.42.115:65301-->10.244.181.97:35446 Receiver info: No information ``` In the preceding information, the IP address of the server where the primary database node instance is deployed is **10.244.42.115**. The data path of the primary node of the database is **/home/dbuser/env\_test/data**. **Primary** indicates the primary database node. **Normal** indicates that openGauss is available, the data has redundancy backup, all processes are running, and the primary/standby relationship is normal. 3. Confirm the port number of the primary node of the database. View the port number in the **postgresql.conf** file of the primary node of the database path, which is queried in [2](#en-us_topic_0283137330_en-us_topic_0237120290_en-us_topic_0062129725_li736435692628). The command is as follows: ``` cat /srv/BigData/gaussdb/data1/dbnode/postgresql.conf | grep port ``` ``` port = 8000 # (change requires restart) #comm_sctp_port = 1024 # Assigned by installation (change requires restart) #comm_control_port = 10001 # Assigned by installation (change requires restart) # supported by the operating system: # e.g. 'localhost=10.145.130.2 localport=12211 remotehost=10.145.130.3 remoteport=12212, localhost=10.145.133.2 localport=12213 remotehost=10.145.133.3 remoteport=12214' # e.g. 'localhost=10.145.130.2 localport=12311 remotehost=10.145.130.4 remoteport=12312, localhost=10.145.133.2 localport=12313 remotehost=10.145.133.4 remoteport=12314' # %r = remote host and port alarm_report_interval = 10 support_extended_features=true ``` **8000** is the port number of the primary node of the database. --- --- url: /en/docs/latest-lite/database_om_guide/conflicts.md --- # Conflicts Logical replication behaves similarly to common DML operations. Even if the data is modified locally on the subscriber node, logical replication updates the data based on the received changes. If the incoming data violates any constraints, the replication will stop. This situation is called a conflict. When UPDATE or DELETE operations are replicated, the missing data will not cause conflicts and such operations will be simply skipped. A conflict will cause errors and stop the replication, which must be resolved manually by the user. Details about the conflict can be found in the subscriber's server log. The conflict can be resolved either by changing the data on the subscriber (so that the data does not conflict with incoming data) or by skipping the transaction that conflicts with the existing data. The transaction can be skipped by calling the **pg\_replication\_origin\_advance()** function with **node\_name** corresponding to the subscription name and a position. The current position of the replication source can be seen in the **pg\_replication\_origin\_status system** view. --- --- url: /en/docs/latest/database_om_guide/conflicts.md --- # Conflicts Logical replication behaves similarly to common DML operations. Even if the data is modified locally on the subscriber node, logical replication updates the data based on the received changes. If the incoming data violates any constraints, the replication will stop. This situation is called a conflict. When UPDATE or DELETE operations are replicated, the missing data will not cause conflicts and such operations will be simply skipped. A conflict will cause errors and stop the replication, which must be resolved manually by the user. Details about the conflict can be found in the subscriber's server log. The conflict can be resolved either by changing the data on the subscriber (so that the data does not conflict with incoming data) or by skipping the transaction that conflicts with the existing data. The transaction can be skipped by calling the **pg\_replication\_origin\_advance()** function with **node\_name** corresponding to the subscription name, and an Xlog LSN. The current position of the replication source can be seen in the **pg\_replication\_origin\_status system** view. --- --- url: /en/docs/latest-lite/developer_guide/connecting_to_a_database_jdbc.md --- # Connecting to a Database After a database is connected, you can use JDBC to run SQL statements to operate data. ## Function Prototype JDBC provides the following three database connection methods: * DriverManager.getConnection(String url); * DriverManager.getConnection(String url, Properties info); * DriverManager.getConnection(String url, String user, String password); ## Parameters **Table 1** Database connection parameters ## Examples ``` // The following code encapsulates database connection operations into an API. The database can then be connected using an authorized username and a password. public static Connection getConnect(String username, String passwd) { // Driver class. String driver = "org.postgresql.Driver"; // Database connection descriptor. String sourceURL = "jdbc:postgresql://10.10.0.13:8000/postgres"; Connection conn = null; try { // Load the driver. Class.forName(driver); } catch( Exception e ) { e.printStackTrace(); return null; } try { // Create a connection. conn = DriverManager.getConnection(sourceURL, username, passwd); System.out.println("Connection succeed!"); } catch(Exception e) { e.printStackTrace(); return null; } return conn; }; // The following code uses the Properties object as a parameter to establish a connection. public static Connection getConnectUseProp(String username, String passwd) { // Driver class. String driver = "org.postgresql.Driver"; // Database connection descriptor. String sourceURL = "jdbc:postgresql://10.10.0.13:8000/postgres?"; Connection conn = null; Properties info = new Properties(); try { // Load the driver. Class.forName(driver); } catch( Exception e ) { e.printStackTrace(); return null; } try { info.setProperty("user", username); info.setProperty("password", passwd); // Create a connection. conn = DriverManager.getConnection(sourceURL, info); System.out.println("Connection succeed!"); } catch(Exception e) { e.printStackTrace(); return null; } return conn; }; ``` --- --- url: /en/docs/latest/developer_guide/connecting_to_a_database_psycopg.md --- # Connecting to a Database 1. Use the **psycopg2.connect** function to obtain the connection object. 2. Use the connection object to create a cursor object. --- --- url: /en/docs/latest/developer_guide/connecting_to_a_database_jdbc.md --- # Connecting to a Database After a database is connected, you can use JDBC to run SQL statements to operate data. ## Function Prototype JDBC provides the following three database connection methods: * DriverManager.getConnection(String url); * DriverManager.getConnection(String url, Properties info); * DriverManager.getConnection(String url, String user, String password); ## Parameters **Table 1** Database connection parameters > \[!NOTE]NOTE > After the **uppercaseAttributeName** parameter is enabled, if the database contains metadata with a mixture of uppercase and lowercase letters, only the metadata in lowercase letters can be queried and output in uppercase letters. Before using the metadata, ensure that the metadata is stored in lowercase letters to prevent data errors. ## Examples ``` // The following code encapsulates database connection operations into an API. The database can then be connected using an authorized username and a password. public static Connection getConnect(String username, String passwd) { // Driver class. String driver = "org.opengauss.Driver"; // Database connection descriptor. String sourceURL = "jdbc:opengauss://10.10.0.13:8000/postgres"; Connection conn = null; try { // Load the driver. Class.forName(driver); } catch( Exception e ) { e.printStackTrace(); return null; } try { // Create a connection. conn = DriverManager.getConnection(sourceURL, username, passwd); System.out.println("Connection succeed!"); } catch(Exception e) { e.printStackTrace(); return null; } return conn; }; // The following code uses the Properties object as a parameter to establish a connection. public static Connection getConnectUseProp(String username, String passwd) { // Driver class. String driver = "org.opengauss.Driver"; // Database connection descriptor. String sourceURL = "jdbc:opengauss://10.10.0.13:8000/postgres?"; Connection conn = null; Properties info = new Properties(); try { // Load the driver. Class.forName(driver); } catch( Exception e ) { e.printStackTrace(); return null; } try { info.setProperty("user", username); info.setProperty("password", passwd); // Create a connection. conn = DriverManager.getConnection(sourceURL, info); System.out.println("Connection succeed!"); } catch(Exception e) { e.printStackTrace(); return null; } return conn; }; ``` --- --- url: /en/docs/latest/developer_guide/connecting_to_a_database_using_ssl_jdbc.md --- # Connecting to a Database (Using SSL) When establishing connections to the openGauss server using JDBC, you can enable SSL connections to encrypt client and server communications for security of sensitive data transmission on the Internet. This section describes how applications establish an SSL connection to openGauss using JDBC. To start the SSL mode, you must have the server certificate, client certificate, and private key files. For details how to obtain these files, see related documents and commands of OpenSSL. ## Configuring the Server The SSL mode requires a root certificate, a server certificate, and a private key. Perform the following operations (assuming that the license files are saved in the data directory **/gaussdb/data/datanode** and the default file names are used): 1. Log in as the OS user omm to the primary node of the database. 2. Generate and import a certificate. Generate an SSL certificate. For details, see [Generating Certificates](../database_administration_guide/ssl_certificate_management.md). Copy the generated **server.crt**, **server.key**, and **cacert.pem** files to the data directory on the server. Run the following command to query the data directory of the database node. The instance column indicates the data directory. ``` gs_om -t status --detail ``` In the Unix OS, **server.crt** and **server.key** must deny the access from the external or any group. Run the following command to set this permission: ``` chmod 0600 server.key ``` 3. Enable the SSL authentication mode. ``` gs_guc set -D /gaussdb/data/datanode -c "ssl=on" ``` 4. Set client access authentication parameters. The IP address is the IP address of the host to be connected. ``` gs_guc reload -D /gaussdb/data/datanode -h "hostssl all all 127.0.0.1/32 cert" gs_guc reload -D /gaussdb/data/datanode -h "hostssl all all IP/32 cert" ``` Clients on the **127.0.0.1/32** network segment can connect to openGauss servers in SSL mode. > \[!TIP]NOTICE > > * If **METHOD** is set to **cert** in the **pg\_hba.conf** file of the server, the client must use the username (common name) configured in the certificate file (**client.crt**) for the database connection. If **METHOD** is set to **md5**, **sm3**, or **sha256**, there is no such a restriction. > * The MD5 encryption algorithm has lower security and poses security risks. Therefore, you are advised to use a more secure encryption algorithm. 5. Configure the digital certificate parameters related to SSL authentication. The information following each command indicates operation success. ``` gs_guc set -D /gaussdb/data/datanode -c "ssl_cert_file='server.crt'" gs_guc set: ssl_cert_file='server.crt' ``` ``` gs_guc set -D /gaussdb/data/datanode -c "ssl_key_file='server.key'" gs_guc set: ssl_key_file='server.key' ``` ``` gs_guc set -D /gaussdb/data/datanode -c "ssl_ca_file='cacert.pem'" gs_guc set: ssl_ca_file='cacert.pem' ``` 6. Restart the database. ``` gs_om -t stop && gs_om -t start ``` ## Configuring the Client To configure the client, perform the following steps: Upload the certificate files **client.key.pk8**, **client.crt**, and **cacert.pem** generated in [Configuring the Server](#en-us_topic_0283137170_en-us_topic_0237120382_en-us_topic_0213179127_en-us_topic_0189251215_en-us_topic_0059777633_s513e457bfaa24ce4b1a20a1f2322f9ae) to the client. ## Examples Note: Select either example 1 or example 2. ``` public class SSL{ public static void main(String[] args) { Properties urlProps = new Properties(); String urls = "jdbc:opengauss://10.29.37.136:8000/postgres"; /** * ================== Example 1: Use the NonValidatingFactory channel. */ urlProps.setProperty("sslfactory","org.opengauss.ssl.NonValidatingFactory"); urlProps.setProperty("user", "world"); urlProps.setProperty("password", "xxxxxx"); urlProps.setProperty("ssl", "true"); /** * ================== Examples 2: Use a certificate. */ urlProps.setProperty("sslcert", "client.crt"); urlProps.setProperty("sslkey", "client.key.pk8"); urlProps.setProperty("sslrootcert", "cacert.pem"); urlProps.setProperty("user", "world"); urlProps.setProperty("ssl", "true"); /* sslmode can be set to require, verify-ca, or verify-full. Select one from the following three examples.*/ /* ================== Example 2.1: Set sslmode to require to use the certificate for authentication. */ urlProps.setProperty("sslmode", "require"); /* ================== Example 2.2: Set sslmode to verify-ca to use the certificate for authentication. */ urlProps.setProperty("sslmode", "verify-ca"); /* ================== Example 2.3: Set sslmode to verify-full to use the certificate (in the Linux OS) for authentication. */ urls = "jdbc:opengauss://world:8000/postgres"; urlProps.setProperty("sslmode", "verify-full"); try { Class.forName("org.opengauss.Driver").newInstance(); } catch (Exception e) { e.printStackTrace(); } try { Connection conn; conn = DriverManager.getConnection(urls,urlProps); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * Note: Convert the client key to the DER format. * openssl pkcs8 -topk8 -outform DER -in client.key -out client.key.pk8 -nocrypt * openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out client.key.der -v1 PBE-MD5-DES * openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out client.key.der -v1 PBE-SHA1-3DES * The preceding algorithms are not recommended due to their low security. * If the customer needs to use a higher-level private key encryption algorithm, the following private key encryption algorithms can be used after the BouncyCastle or a third-party private key is used to decrypt the password package: * openssl pkcs8 -in client.key -topk8 -outform DER -out client.key.der -v2 AES128 * openssl pkcs8 -in client.key -topk8 -outform DER -out client.key.der -v2 aes-256-cbc -iter 1000000 * openssl pkcs8 -in client.key -topk8 -out client.key.der -outform Der -v2 aes-256-cbc -v2prf hmacWithSHA512 * Enable BouncyCastle: Introduce the bcpkix-jdk15on.jar package for projects that use JDBC. The recommended version is 1.65 or later. */ ``` --- --- url: /en/docs/latest-lite/developer_guide/connecting_to_a_database_using_uds.md --- # Connecting to a Database (Using UDS) The Unix domain socket is used for data exchange between different processes on the same host. You can add **junixsocket** to obtain the socket factory. The **junixsocket-core-***XXX***.jar**, **junixsocket-common-***XXX***.jar**, and **junixsocket-native-common-***XXX***.jar** JAR packages need to be referenced. In addition, you need to add **socketFactory=org.newsclub.net.unix.AFUNIXSocketFactory$FactoryArg\&socketFactoryArg=***\[path-to-the-unix-socket]* to the URL connection string. Example: ``` import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.Properties; public class Test { public static void main(String[] args) { String driver = "org.postgresql.Driver"; Connection conn; try { Class.forName(driver).newInstance(); Properties properties = new Properties(); properties.setProperty("user", "username"); properties.setProperty("password", "password"); conn = DriverManager.getConnection("jdbc:postgresql://localhost:8000/postgres?socketFactory=org.newsclub" + ".net.unix" + ".AFUNIXSocketFactory$FactoryArg&socketFactoryArg=/data/tmp/.s.PGSQL.8000", properties); System.out.println("Connection Successful!"); Statement statement = conn.createStatement(); statement.executeQuery("select 1"); } catch (Exception e) { e.printStackTrace(); } } } ``` > \[!TIP]NOTICE > > * Set the **socketFactoryArg** parameter based on the actual path. The value must be the same as that of the GUC parameter **unix\_socket\_directory**. > * The connection host name must be set to **localhost**. --- --- url: /en/docs/latest/developer_guide/connecting_to_a_database_using_uds.md --- # Connecting to a Database (Using UDS) The Unix domain socket is used for data exchange between different processes on the same host. You can add **junixsocket** to obtain the socket factory. The **junixsocket-core-***XXX***.jar**, **junixsocket-common-***XXX***.jar**, and **junixsocket-native-common-***XXX***.jar** JAR packages need to be referenced. In addition, you need to add **socketFactory=org.newsclub.net.unix.AFUNIXSocketFactory$FactoryArg\&socketFactoryArg=***\[path-to-the-unix-socket]* to the URL connection string. Example: ``` import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.Properties; public class Test { public static void main(String[] args) { String driver = "org.postgresql.Driver"; Connection conn; try { Class.forName(driver).newInstance(); Properties properties = new Properties(); properties.setProperty("user", "username"); properties.setProperty("password", "password"); conn = DriverManager.getConnection("jdbc:postgresql://localhost:8000/postgres?socketFactory=org.newsclub" + ".net.unix" + ".AFUNIXSocketFactory$FactoryArg&socketFactoryArg=/data/tmp/.s.PGSQL.8000", properties); System.out.println("Connection Successful!"); Statement statement = conn.createStatement(); statement.executeQuery("select 1"); } catch (Exception e) { e.printStackTrace(); } } } ``` > \[!TIP]NOTICE > > * Set the **socketFactoryArg** parameter based on the actual path. The value must be the same as that of the GUC parameter **unix\_socket\_directory**. > * The connection host name must be set to **localhost**. --- --- url: /en/docs/latest-lite/getting_started/connecting_to_opengauss.md --- # Connecting to openGauss * **[gsql Connection and Usage](gsql_connection_and_usage.md)** * **[Connecting to a Database](odbc.md)** --- --- url: /en/docs/latest/getting_started/connecting_to_opengauss.md --- # Connecting to openGauss * **[gsql Connection and Usage](gsql_connection_and_usage.md)** * **[Connecting to a Database](odbc.md)** --- --- url: /en/docs/latest-lite/developer_guide/connecting_to_a_database_psycopg.md --- # Connecting to the Database 1. Use the **psycopg2.connect** function to obtain the connection object. 2. Use the connection object to create a cursor object. --- --- url: >- /en/docs/latest-lite/developer_guide/connecting_to_a_database_using_ssl_jdbc.md --- # Connecting to the Database (Using SSL) When establishing connections to the openGauss server using JDBC, you can enable SSL connections to encrypt client and server communications for security of sensitive data transmission on the Internet. This section describes how applications establish an SSL connection to openGauss using JDBC. To start the SSL mode, you must have the server certificate, client certificate, and private key files. For details how to obtain these files, see related documents and commands of OpenSSL. ## Configuring the Server The SSL mode requires a root certificate, a server certificate, and a private key. Perform the following operations (assuming that the license files are saved in the data directory **/gaussdb/data/datanode** and the default file names are used): 1. Log in as the OS user **omm** to the primary node of the database. 2. Generate and configure a certificate. Generate an SSL certificate. For details, see [Generating Certificates](../database_administration_guide/ssl_certificate_management.md). Copy the generated **server.crt**, **server.key**, and **cacert.pem** files to the data directory on the server. In the Unix OS, **server.crt** and **server.key** must deny the access from the external or any group. Run the following command to set this permission: ``` chmod 0600 server.key ``` 3. Enable the SSL authentication mode. ``` gs_guc set -D /gaussdb/data/datanode -c "ssl=on" ``` 4. Set client access authentication parameters. The IP address is the IP address of the host to be connected. ``` gs_guc reload -D /gaussdb/data/datanode -h "hostssl all all 127.0.0.1/32 cert" gs_guc reload -D /gaussdb/data/datanode -h "hostssl all all IP/32 cert" ``` Clients on the **127.0.0.1/32** network segment can connect to openGauss servers in SSL mode. > \[!TIP]NOTICE > > * If **METHOD** is set to **cert** in the **pg\_hba.conf** file of the server, the client must use the username (common name) configured in the certificate file (**client.crt**) for the database connection. If **METHOD** is set to **md5**, **sm3**, or **sha256**, there is no such a restriction. > * The MD5 encryption algorithm has lower security and poses security risks. Therefore, you are advised to use a more secure encryption algorithm. 5. Configure the digital certificate parameters related to SSL authentication. The information following each command indicates operation success. ``` gs_guc set -D /gaussdb/data/datanode -c "ssl_cert_file='server.crt'" gs_guc set: ssl_cert_file='server.crt' ``` ``` gs_guc set -D /gaussdb/data/datanode -c "ssl_key_file='server.key'" gs_guc set: ssl_key_file='server.key' ``` ``` gs_guc set -D /gaussdb/data/datanode -c "ssl_ca_file='cacert.pem'" gs_guc set: ssl_ca_file='cacert.pem' ``` 6. Restart the database. ``` gs_ctl restart -D /gaussdb/data/datanode ``` ## Configuring the Client To configure the client, perform the following steps: Upload the certificate files **client.key.pk8**, **client.crt**, and **cacert.pem** generated in [Configuring the Server](#en-us_topic_0283137170_en-us_topic_0237120382_en-us_topic_0213179127_en-us_topic_0189251215_en-us_topic_0059777633_s513e457bfaa24ce4b1a20a1f2322f9ae) to the client. ## Examples Note: Select either example 1 or example 2. ``` public class SSL{ public static void main(String[] args) { Properties urlProps = new Properties(); String urls = "jdbc:postgresql://10.29.37.136:8000/postgres"; /** * ================== Example 1: Use the NonValidatingFactory channel. */ urlProps.setProperty("sslfactory","org.postgresql.ssl.NonValidatingFactory"); urlProps.setProperty("user", "world"); urlProps.setProperty("password", "xxxxxx"); urlProps.setProperty("ssl", "true"); /** * ================== Examples 2: Use a certificate. */ urlProps.setProperty("sslcert", "client.crt"); urlProps.setProperty("sslkey", "client.key.pk8"); urlProps.setProperty("sslrootcert", "cacert.pem"); urlProps.setProperty("user", "world"); urlProps.setProperty("ssl", "true"); /* sslmode can be set to require, verify-ca, or verify-full. Select one from the following three examples.*/ /* ================== Example 2.1: Set sslmode to require to use the certificate for authentication. */ urlProps.setProperty("sslmode", "require"); /* ================== Example 2.2: Set sslmode to verify-ca to use the certificate for authentication. */ urlProps.setProperty("sslmode", "verify-ca"); /* ================== Example 2.3: Set sslmode to verify-full to use the certificate (in the Linux OS) for authentication. */ urls = "jdbc:postgresql://world:8000/postgres"; urlProps.setProperty("sslmode", "verify-full"); try { Class.forName("org.postgresql.Driver").newInstance(); } catch (Exception e) { e.printStackTrace(); } try { Connection conn; conn = DriverManager.getConnection(urls,urlProps); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * Note: Convert the client key to the DER format. * openssl pkcs8 -topk8 -outform DER -in client.key -out client.key.pk8 -nocrypt * openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out client.key.der -v1 PBE-MD5-DES * openssl pkcs8 -topk8 -inform PEM -in client.key -outform DER -out client.key.der -v1 PBE-SHA1-3DES * The preceding algorithms are not recommended due to their low security. * If the customer needs to use a higher-level private key encryption algorithm, the following private key encryption algorithms can be used after the BouncyCastle or a third-party private key is used to decrypt the password package: * openssl pkcs8 -in client.key -topk8 -outform DER -out client.key.der -v2 AES128 * openssl pkcs8 -in client.key -topk8 -outform DER -out client.key.der -v2 aes-256-cbc -iter 1000000 * openssl pkcs8 -in client.key -topk8 -out client.key.der -outform Der -v2 aes-256-cbc -v2prf hmacWithSHA512 * Enable BouncyCastle: Introduce the bcpkix-jdk15on.jar package for projects that use JDBC. The recommended version is 1.65 or later. */ ``` --- --- url: >- /en/docs/latest-lite/developer_guide/connecting_to_the_database_using_ssl_psycopg.md --- # Connecting to the Database (Using SSL) When you use psycopy2 to connect to the GaussDB Kernel server, you can enable SSL to encrypt the communication between the client and server. To enable SSL, you must have the server certificate, client certificate, and private key files. For details on how to obtain these files, see related documents and commands of OpenSSL. 1. Use the .ini file (the **configparser**package of Python can parse this type of configuration file) to save the configuration information about the database connection. 2. Add SSL connection parameters **sslmode**, **sslcert**, **sslkey**, and **sslrootcert**to the connection options. 1. **sslmode**: [Table 1](#table167989176183) 2. **sslcert**: client certificate path 3. **sslkey**: client key path 4. **sslrootcert**: root certificate path 3. Use the **psycopg2.connect** function to obtain the connection object. 4. Use the connection object to create a cursor object. **Table 1** sslmode options --- --- url: >- /en/docs/latest/developer_guide/connecting_to_the_database_using_ssl_psycopg.md --- # Connecting to the Database (Using SSL) When you use psycopy2 to connect to the GaussDB Kernel server, you can enable SSL to encrypt the communication between the client and server. To enable SSL, you must have the server certificate, client certificate, and private key files. For details on how to obtain these files, see related documents and commands of OpenSSL. 1. Use the .ini file (the **configparser**package of Python can parse this type of configuration file) to save the configuration information about the database connection. 2. Add SSL connection parameters **sslmode**, **sslcert**, **sslkey**, and **sslrootcert**to the connection options. 1. **sslmode**: [Table 1](#table167989176183) 2. **sslcert**: client certificate path 3. **sslkey**: client key path 4. **sslrootcert**: root certificate path 3. Use the **psycopg2.connect** function to obtain the connection object. 4. Use the connection object to create a cursor object. **Table 1** sslmode options --- --- url: /en/docs/latest-lite/database_reference/connection_pool_parameters.md --- # Connection Pool Parameters When a connection pool is used to access the database, database connections are established and then stored in the memory as objects during system running. When you need to access the database, no new connection is established. Instead, an existing idle connection is selected from the connection pool. After you finish accessing the database, the database does not disable the connection but puts it back into the connection pool. The connection can be used for the next access request. ## pooler\_maximum\_idle\_time **Parameter description**: Specifies the maximum amount of time that the connections can remain idle in a pool before being removed. After that, the automatic connection clearing mechanism is triggered to reduce the number of connections on each node to the value of **minimum\_pool\_size**. > \[!NOTE]NOTE > This parameter does not take effect in this version. This parameter is a **USERSET** parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to *INT\_MAX*. The smallest unit is m. **Default value**: **1h** (60 minutes) ## minimum\_pool\_size **Parameter description**: Specifies the minimum number of remaining connections in the pool on each node after the automatic connection clearing is triggered. If this parameter is set to **0**, the automatic connection clearing is disabled. > \[!NOTE]NOTE > This parameter does not take effect in this version. This parameter is a **USERSET** parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 1 to 65535 **Default value**: **200** ## cache\_connection **Parameter description**: Specifies whether to reclaim the connections of a connection pool. This parameter is a **SIGHUP** parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that the connections of a connection pool will be reclaimed. * **off** indicates that the connections of a connection pool will not be reclaimed. **Default value**: **on** --- --- url: /en/docs/latest/database_reference/connection_pool_parameters.md --- # Connection Pool Parameters When a connection pool is used to access the database, database connections are established and then stored in the memory as objects during system running. When you need to access the database, no new connection is established. Instead, an existing idle connection is selected from the connection pool. After you finish accessing the database, the database does not disable the connection but puts it back into the connection pool. The connection can be used for the next access request. ## pooler\_maximum\_idle\_time **Parameter description**: Specifies the maximum amount of time that the connections can remain idle in a pool before being removed. After that, the automatic connection clearing mechanism is triggered to reduce the number of connections on each node to the value of **minimum\_pool\_size**. > \[!NOTE]NOTE > This parameter does not take effect in this version. This parameter is a **USERSET** parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 0 to *INT\_MAX*. The smallest unit is m. **Default value**: **1h** (60 minutes) ## minimum\_pool\_size **Parameter description**: Specifies the minimum number of remaining connections in the pool on each node after the automatic connection clearing is triggered. If this parameter is set to **0**, the automatic connection clearing is disabled. > \[!NOTE]NOTE > This parameter does not take effect in this version. This parameter is a **USERSET** parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: an integer ranging from 1 to 65535 **Default value**: **200** ## cache\_connection **Parameter description**: Specifies whether to reclaim the connections of a connection pool. This parameter is a **SIGHUP** parameter. Set it based on instructions provided in [Table 2](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t290c8f15953843db8d8e53d867cd893d). **Value range**: Boolean * **on** indicates that the connections of a connection pool will be reclaimed. * **off** indicates that the connections of a connection pool will not be reclaimed. **Default value**: **on** --- --- url: /en/docs/latest-lite/database_reference/connection_settings.md --- # Connection Settings This section describes parameters related to client-server connection modes. ## listen\_addresses **Parameter description**: Specifies the TCP/IP address of the client for a server to listen on. This parameter specifies the IP address used by the openGauss server for listening, for example, IPv4 or IPv6 (if supported). Multiple NICs may exist on the host and each NIC can be bound to multiple IP addresses. This parameter specifies the IP addresses to which openGauss is bound. The client can use the IP address specified by this parameter to connect to or send requests to openGauss. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: * Host name or IP address. Multiple values are separated with commas (,). * Asterisk (\*) or **0.0.0.0**, indicating that all IP addresses will be listened to, which is not recommended due to potential security risks. This parameter must be used together with valid addresses (for example, the local IP address). Otherwise, the build may fail. In primary/standby mode, if the value is set to **\\\*** or **0.0.0.0**, the value of **localport** in the **postgresql.conf** file of the database on the primary node cannot be the value of **dataPortBase + 1**. Otherwise, the database cannot be started. * If the parameter is not specified, the server does not listen on any IP address. In this case, only Unix domain sockets can be used for database connections. **Default value**: After the database instance is installed, the default value is configured according to the IP address of different instances in the XML configuration file. The default value for the DN instance is **'x.x.x.x'**. ## local\_bind\_address **Parameter description**: Specifies the host IP address bound to the current node for connecting to other nodes in openGauss. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Default value**: After the database instance is installed, the default value is configured according to the IP address of different instances in the XML configuration file. The default value for the DN instance is **'x.x.x.x'**. ## port **Parameter description**: Specifies the TCP port listened on by the openGauss. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!NOTE]NOTE > This parameter is specified in the configuration file during installation. Do not modify this parameter unless absolutely necessary. Otherwise, database communication will be affected. **Value range**: an integer ranging from 1 to 65535 > \[!NOTE]NOTE > > * When setting the port number, ensure that the port number is not in use. When setting the port numbers of multiple instances, ensure that the port numbers do not conflict. > * Ports 1 to 1023 are reserved for the operating system. Do not use them. > * When the database instance is installed using the configuration file, pay attention to the ports reserved in the communication matrix in the configuration file. For example, *dataPortBase* + 1 needs to be reserved as the port used by internal tools, and *dataPortBase* + 6 needs to be reserved as the communication port of the flow engine message queue. Therefore, during database instance installation, the maximum port number is **65529** for DNs. Ensure that the port number does not conflict with each other. **Default value**: **5432** (The actual value is specified in the configuration file during installation.) ## max\_connections **Parameter description**: Specifies the maximum number of concurrent connections to the database. This parameter influences the concurrent processing capability of openGauss. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer. The minimum value is **10** (greater than the value of *max\*wal\_senders\_). The theoretical maximum value is **262143**. The actual maximum value is a dynamic value, which is calculated using the formula 262143 – value of*job\*queue\_processes\_ – value of *autovacuum\*max\_workers\_– value of*AUXILIARY\*BACKENDS\_ – value of \*AV\*LAUNCHER\_PROCS\_. The values of [\*job\*queue\_processes\_](scheduled_task.md#en-us_topic_0283137574_en-us_topic_0237124754_en-us_topic_0059778487_section10342177134137), *[autovacuum\*max\_workers](automatic_vacuuming.md#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s76932f79410248ba8923017d19982673)*, and *[max\*inner\_tool\_connections](#en-us_topic_0283136886_section132711513143211)* depend on the settings of the corresponding GUC parameters.\*AUXILIARY\*BACKENDS\_ indicates the number of reserved auxiliary threads, which is fixed at 20. \*AV\*LAUNCHER\_PROCS\_ indicates the number of reserved launcher threads for autovacuum, which is fixed at 2. **Default value**: * **200**: Applicable when the database is installed in build or simplified mode. * **5000**: Applicable when the database is installed using the OM tool. **Setting suggestions**: Retain the default value of this parameter on the primary node of the databases. **Impact of incorrect configuration:** * If the value of \*max\*connections\_ is too large and exceeds the dynamic maximum value described in the formula, the node fails to be started and the error message " invalid value for parameter "max\_connections"" is displayed. * If only the value of \*max\*connections\_ is increased while the memory parameter is not adjusted in proportion according to the external egress specifications, when the service load is heavy, the memory may be insufficient, and the error message "memory is temporarily unavailable" is displayed. > \[!NOTE]NOTE > > * If the number of connections of the administrator exceeds the value of *max\*connections\_, the administrator can still connect to the database after the connections are used up by common users. If the number of connections exceeds the value of*sysadmin\*reserved\_connections\_, an error is reported. That is, the maximum number of connections of the administrator is equal to the value of \*max\*connections\_+\*sysadmin\*reserved\_connections\_. > * For common users, internal jobs use some connections. Therefore, the value of this parameter is slightly less than that of \*max\*connections\_. The value depends on the number of internal connections. ## max\_inner\_tool\_connections **Parameter description**: Specifies the maximum number of concurrent connections of a tool which is allowed to connect to the database. This parameter influences the concurrent connection capability of the openGauss tool. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to *MIN* (which takes the smaller value between **262143** and *max\*connections\_). For details about how to calculate the value of*max\*connections\_, see the preceding description. **Default value**: **10** for each database node. If the default value is greater than the maximum value supported by the kernel (determined when the **gs\_initdb** command is executed), an error message is displayed. **Setting suggestions**: Retain the default value of this parameter on the primary node of the databases. If this parameter is set to a large value, openGauss requires more System V shared memories or semaphores, which may exceed the default maximum configuration of the OS. In this case, modify the value as needed. ## sysadmin\_reserved\_connections **Parameter description**: Specifies the minimum number of connections reserved for administrators. You are advised not to set this parameter to a large value. This parameter is used together with the \*max\*connections\_parameter. The maximum number of connections of the administrator is equal to the value of\*max\*connections\_ + \*sysadmin\*reserved\_connections\_. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to *MIN* (which takes the smaller value between **262143** and *max\*connections\_). For details about how to calculate the value of*max\*connections\_, see the preceding description. **Default value**: **3** Note: When the thread pool function is enabled, if the thread pool is fully occupied, a processing bottleneck occurs. As a result, connections reserved by the administrator cannot be established. In this case, you can use gsql to establish connections through the primary port number + 1 to clear useless sessions. ## unix\_socket\_directory **Parameter description**: Specifies the Unix domain socket directory for the openGauss server to listen to connections from the client. This parameter is a **POSTMASTER** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). The parameter length limit varies by OS. If the length is exceeded, the error "Unix-domain socket path xxx is too long" will be reported. **Value range**: a string **Default value**: empty. The actual value is specified by the configuration file during installation. ## unix\_socket\_group **Parameter description**: Specifies the group of the Unix domain socket (the user of a socket is the user that starts the server). This parameter can work with **[unix\_socket\_permissions](#en-us_topic_0283136886_en-us_topic_0237124695_en-us_topic_0059777636_s09d0cf55124b4f1aa3d401d18b9b4151)** to control socket access. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string. If this parameter is set to an empty string, the default group of the current user is used. **Default value**: empty ## unix\_socket\_permissions **Parameter description**: Specifies access permissions for the Unix domain socket. The Unix domain socket uses the usual permission set of the Unix file system. The value of this parameter should be a number (acceptable for the **chmod** and **umask** commands). If a user-defined octal format is used, the number must start with 0. You are advised to set it to **0770** (only allowing access from users connecting to the database and users in the same group as them) or **0700** (only allowing access from users connecting to the database). This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: 0000 to 0777 **Default value**: **0700** > \[!NOTE]NOTE > In the Linux OS, a document has one document attribute and nine permission attributes, which consists of the read (r), write (w), and execute (x) permissions of the Owner, Group, and Others groups. > The r, w, and x permissions are represented by the following numbers: > r: 4 > w: 2 > x: 1 > -: 0 > The three attributes in a group are accumulative. > For example, **-rwxrwx---** indicates the following permissions: > owner = rwx = 4+2+1 = 7 > group = rwx = 4+2+1 = 7 > others = --- = 0+0+0 = 0 > The permission of the file is 0770. ## application\_name **Parameter description**: Specifies the client name used in the current connection request. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). When a standby node requests to replicate logs on the primary node, if this parameter is not an empty string, it is used as the name of the streaming replication slot of the standby node on the primary node. In this case, if the length of this parameter exceeds 61 bytes, only the first 61 bytes are used as the streaming replication slot name. **Value range:** a string **Default value**: empty (The actual value is the name of the application connected to the backend.) ## connection\_info **Parameter description**: Specifies the database connection information, including the driver type, driver version, driver deployment path, and process owner. This parameter is a USERSET parameter used for O\&M. You are advised not to change the parameter value. **Value range:** a string **Default value**: empty > \[!NOTE]NOTE > > * An empty string indicates that the driver connected to the database does not support automatic setting of the **connection\_info** parameter or the parameter is not set by users in applications. > * The following is an example of the concatenated value of **connection\_info**: > > ``` > {"driver_name":"ODBC","driver_version": "(openGauss X.X.X build 13b34b53) compiled at 2020-05-08 02:59:43 commit 2143 last mr 131 release","driver_path":"/usr/local/lib/psqlodbcw.so","os_user":"omm"} > ``` > > **driver\_name** and **driver\_version** are displayed by default. Whether **driver\_path** and **os\_user** are displayed is determined by users. For details, see [Connecting to a Database](../getting_started/odbc.md). ## enable\_dolphin\_proto **Parameter descriptio**: Whether enable dolphin database protocol or not This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a bool **Default value**: off ## dolphin\_server\_port **Parameter description**: Specifies the TCP port listened on by the dolphin plugin server. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 65535 **Default value**: **3308** --- --- url: /en/docs/latest/database_reference/connection_settings.md --- # Connection Settings This section describes parameters related to client-server connection modes. ## listen\_addresses **Parameter description**: Specifies the TCP/IP address of the client for a server to listen on. This parameter specifies the IP address used by the openGauss server for listening, for example, IPv4 or IPv6 (if supported). Multiple NICs may exist on the host and each NIC can be bound to multiple IP addresses. This parameter specifies the IP addresses to which openGauss is bound. The client can use the IP address specified by this parameter to connect to or send requests to openGauss. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: * Host name or IP address. Multiple values are separated with commas (,). * Asterisk (\*) or **0.0.0.0**, indicating that all IP addresses will be listened to, which is not recommended due to potential security risks. This parameter must be used together with valid addresses (for example, the local IP address). Otherwise, the build may fail. In primary/standby mode, if the value is set to **\\\*** or **0.0.0.0**, the value of **localport** in the **postgresql.conf** file of the database on the primary node cannot be the value of **dataPortBase + 1**. Otherwise, the database cannot be started. * If the parameter is not specified, the server does not listen on any IP address. In this case, only Unix domain sockets can be used for database connections. **Default value**: After the database instance is installed, the default value is configured according to the IP address of different instances in the XML configuration file. The default value for the DN instance is **'x.x.x.x'**. ## local\_bind\_address **Parameter description**: Specifies the host IP address bound to the current node for connecting to other nodes in openGauss. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Default value**: After the database instance is installed, the default value is configured according to the IP address of different instances in the XML configuration file. The default value for the DN instance is **'x.x.x.x'**. ## port **Parameter description**: Specifies the TCP port listened on by the openGauss. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). > \[!NOTE]NOTE > This parameter is specified in the configuration file during installation. Do not modify this parameter unless absolutely necessary. Otherwise, database communication will be affected. **Value range**: an integer ranging from 1 to 65535 > \[!NOTE]NOTE > > * When setting the port number, ensure that the port number is not in use. When setting the port numbers of multiple instances, ensure that the port numbers do not conflict. > * Ports 1 to 1023 are reserved for the operating system. Do not use them. > * When the database instance is installed using the configuration file, pay attention to the ports reserved in the communication matrix in the configuration file. For example, *dataPortBase* + 1 needs to be reserved as the port used by internal tools. > * After changing the port number by using gs\_guc set, you need to manually modify the port information in the static configuration file **static\_config\_files** for the change to take effect. **Default value**: **5432** (The actual value is specified in the configuration file during installation.) ## max\_connections **Parameter description**: Specifies the maximum number of concurrent connections to the database. This parameter influences the concurrent processing capability of openGauss. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer. The minimum value is **10** (greater than the value of *max\*wal\_senders\_). The theoretical maximum value is **262143**. The actual maximum value is a dynamic value, which is calculated using the formula 262143 – value of*job\*queue\_processes\_ – value of *autovacuum\*max\_workers\_– value of*AUXILIARY\*BACKENDS\_ – value of *AV\*LAUNCHER\_PROCS\_. The values of*job\*queue\_processes *[autovacuum\*max\_workers](../database_reference/automatic_vacuuming.md#en-us_topic_0283137694_en-us_topic_0237124730_en-us_topic_0059778244_s76932f79410248ba8923017d19982673)*, and *[max\*inner\_tool\_connections](#en-us_topic_0283136886_section132711513143211)* depend on the settings of the corresponding GUC parameters. \*AUXILIARY\*BACKENDS\_ indicates the number of reserved auxiliary threads, which is fixed at 20.\*AV\*LAUNCHER\_PROCS\_ indicates the number of reserved launcher threads for autovacuum, which is fixed at 2. **Default value**: * **200**: Applicable when the database is installed in build or simplified mode. * **5000**: Applicable when the database is installed using the OM tool. **Setting suggestions**: Retain the default value of this parameter on the primary node of the databases. **Impact of incorrect configuration:** * If the value of \*max\*connections\_ is too large and exceeds the dynamic maximum value described in the formula, the node fails to be started and the error message " invalid value for parameter "max\_connections"" is displayed. * If only the value of \*max\*connections\_ is increased while the memory parameter is not adjusted in proportion according to the external egress specifications, when the service load is heavy, the memory may be insufficient, and the error message "memory is temporarily unavailable" is displayed. > \[!NOTE]NOTE > > * If the number of connections of the administrator exceeds the value of *max\*connections\_, the administrator can still connect to the database after the connections are used up by common users. If the number of connections exceeds the value of*sysadmin\*reserved\_connections\_, an error is reported. That is, the maximum number of connections of the administrator is equal to the value of \*max\*connections\_+\*sysadmin\*reserved\_connections\_. > * For common users, internal jobs use some connections. Therefore, the value of this parameter is slightly less than that of \*max\*connections\_. The value depends on the number of internal connections. ## max\_inner\_tool\_connections **Parameter description**: Specifies the maximum number of concurrent connections of a tool which is allowed to connect to the database. This parameter influences the concurrent connection capability of the openGauss tool. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to *MIN* (which takes the smaller value between **262143** and *max\*connections\_). For details about how to calculate the value of*max\*connections\_, see the preceding description. **Default value**: **50** for each database node. If the default value is greater than the maximum value supported by the kernel (determined when the **gs\_initdb** command is executed), an error message is displayed. **Setting suggestions**: Retain the default value of this parameter on the primary node of the databases. If this parameter is set to a large value, openGauss requires more System V shared memories or semaphores, which may exceed the default maximum configuration of the OS. In this case, modify the value as needed. ## sysadmin\_reserved\_connections **Parameter description**: Specifies the minimum number of connections reserved for administrators. You are advised not to set this parameter to a large value. This parameter is used together with the max\_connections parameter. The maximum number of connections of the administrator is equal to the value of max\_connections + sysadmin\_reserved\_connections. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to *MIN* (which takes the smaller value between **262143** and *max\*connections\_). For details about how to calculate the value of*max\*connections\_, see the preceding description. **Default value**: **3** Note: When the thread pool function is enabled, if the thread pool is fully occupied, a processing bottleneck occurs. As a result, connections reserved by the administrator cannot be established. In this case, you can use gsql to establish connections through the primary port number + 1 to clear useless sessions. ## unix\_socket\_directory **Parameter description**: Specifies the Unix domain socket directory for the openGauss server to listen to connections from the client. This parameter is a **POSTMASTER** parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). The parameter length limit varies by OS. If the length is exceeded, the error "Unix-domain socket path xxx is too long" will be reported. **Value range**: a string **Default value**: empty. The actual value is specified by the configuration file during installation. ## unix\_socket\_group **Parameter description**: Specifies the group of the Unix domain socket (the user of a socket is the user that starts the server). This parameter can work with **[unix\_socket\_permissions](#en-us_topic_0283136886_en-us_topic_0237124695_en-us_topic_0059777636_s09d0cf55124b4f1aa3d401d18b9b4151)** to control socket access. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a string. If this parameter is set to an empty string, the default group of the current user is used. **Default value**: empty ## unix\_socket\_permissions **Parameter description**: Specifies access permissions for the Unix domain socket. The Unix domain socket uses the usual permission set of the Unix file system. The value of this parameter should be a number (acceptable for the **chmod** and **umask** commands). If a user-defined octal format is used, the number must start with 0. You are advised to set it to **0770** (only allowing access from users connecting to the database and users in the same group as them) or **0700** (only allowing access from users connecting to the database). This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: 0000 to 0777 **Default value**: **0700** > \[!NOTE]NOTE > In the Linux OS, a document has one document attribute and nine permission attributes, which consists of the read (r), write (w), and execute (x) permissions of the Owner, Group, and Others groups. > The r, w, and x permissions are represented by the following numbers: > r: 4 > w: 2 > x: 1 > -: 0 > The three attributes in a group are accumulative. > For example, **-rwxrwx---** indicates the following permissions: > owner = rwx = 4+2+1 = 7 > group = rwx = 4+2+1 = 7 > others = --- = 0+0+0 = 0 > The permission of the file is 0770. ## application\_name **Parameter description**: Specifies the client name used in the current connection request. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). When a standby node requests to replicate logs on the primary node, if this parameter is not an empty string, it is used as the name of the streaming replication slot of the standby node on the primary node. In this case, if the length of this parameter exceeds 61 bytes, only the first 61 bytes are used as the streaming replication slot name. **Value range:** a string **Default value**: empty (The actual value is the name of the application connected to the backend.) ## connection\_info **Parameter description**: Specifies the database connection information, including the driver type, driver version, driver deployment path, and process owner. This parameter is a USERSET parameter used for O\&M. You are advised not to change the parameter value. **Value range:** a string **Default value**: empty > \[!NOTE]NOTE > > * An empty string indicates that the driver connected to the database does not support automatic setting of the **connection\_info** parameter or the parameter is not set by users in applications. > * The following is an example of the concatenated value of **connection\_info**: > > ``` > {"driver_name":"ODBC","driver_version": "(openGauss X.X.X build 13b34b53) compiled at 2020-05-08 02:59:43 commit 2143 last mr 131 release","driver_path":"/usr/local/lib/psqlodbcw.so","os_user":"omm"} > ``` > > **driver\_name** and **driver\_version** are displayed by default. Whether **driver\_path** and **os\_user** are displayed is determined by users. For details, see [Connecting to a Database](../getting_started/odbc.md) and [Configuring a Data Source in the Linux OS](../developer_guide/configuring_a_data_source_in_the_linux_os.md). ## enable\_dolphin\_proto **Parameter descriptio**: Whether enable dolphin database protocol or not This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: a bool **Default value**: off ## dolphin\_server\_port **Parameter description**: Specifies the TCP port listened on by the dolphin plugin server. This parameter is a POSTMASTER parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1024 to 65535 **Default value**: **3308** --- --- url: /en/docs/latest-lite/developer_guide/connection_close.md --- # connection.close() ## Function This method closes the database connection. > \[!WARNING]CAUTION > This method closes the database connection and does not automatically call **commit()**. If you just close the database connection without calling **commit()** first, changes will be lost. ## Prototype ``` connection.close() ``` ## Parameter None ## Return Value None ## Examples For details, see [Example: Common Operations](example_common_operations_psycopg.md). --- --- url: /en/docs/latest/developer_guide/connection_close.md --- # connection.close() ## Function This method closes the database connection. > \[!WARNING]CAUTION > This method closes the database connection and does not automatically call **commit()**. If you just close the database connection without calling **commit()** first, changes will be lost. ## Prototype ``` connection.close() ``` ## Parameter None ## Return Value None ## Examples For details, see [Example: Common Operations](example_common_operations_psycopg.md). --- --- url: /zh/docs/latest-lite/developer_guide/connection_close.md --- # connection.close() ## 功能描述 此方法关闭数据库连接。 > \[!WARNING]注意 > 此方法关闭数据库连接,并不自动调用commit()。如果只是关闭数据库连接而不调用commit()方法,那么所有更改将会丢失。 ## 原型 ``` connection.close() ``` ## 参数 无。 ## 返回值 无。 ## 示例 请参见[示例:常用操作](example_common_operations_psycopg.md)。 --- --- url: /zh/docs/latest/developer_guide/connection_close.md --- # connection.close() ## 功能描述 此方法关闭数据库连接。 > \[!WARNING]注意 > 此方法关闭数据库连接,并不自动调用commit()。如果只是关闭数据库连接而不调用commit()方法,那么所有更改将会丢失。 ## 原型 ``` connection.close() ``` ## 参数 无。 ## 返回值 无。 ## 示例 请参见[示例:常用操作](example_common_operations_psycopg.md)。 --- --- url: /en/docs/latest-lite/developer_guide/connection_commit.md --- # connection.commit() ## Function This method commits the currently pending transaction to the database. > \[!WARNING]CAUTION > By default, Psycopg opens a transaction before executing the first command. If **commit()** is not called, the effect of any data operation will be lost. ## Prototype ``` connection.commit() ``` ## Parameter None ## Return Value None ## Examples For details, see [Example: Common Operations](example_common_operations_psycopg.md). --- --- url: /en/docs/latest/developer_guide/connection_commit.md --- # connection.commit() ## Function This method commits the currently pending transaction to the database. > \[!WARNING]CAUTION > By default, Psycopg opens a transaction before executing the first command. If **commit()** is not called, the effect of any data operation will be lost. ## Prototype ``` connection.commit() ``` ## Parameter None ## Return Value None ## Examples For details, see [Example: Common Operations](example_common_operations_psycopg.md). --- --- url: /zh/docs/latest-lite/developer_guide/connection_commit.md --- # connection.commit() ## 功能描述 此方法将当前挂起的事务提交到数据库。 > \[!WARNING]注意 > 默认情况下,Psycopg在执行第一个命令之前打开一个事务:如果不调用commit(),任何数据操作的效果都将丢失。 ## 原型 ``` connection.commit() ``` ## 参数 无。 ## 返回值 无。 ## 示例 请参见[示例:常用操作](example_common_operations_psycopg.md)。 --- --- url: /zh/docs/latest/developer_guide/connection_commit.md --- # connection.commit() ## 功能描述 此方法将当前挂起的事务提交到数据库。 > \[!WARNING]注意 > 默认情况下,Psycopg在执行第一个命令之前打开一个事务:如果不调用commit(),任何数据操作的效果都将丢失。 ## 原型 ``` connection.commit() ``` ## 参数 无。 ## 返回值 无。 ## 示例 请参见[示例:常用操作](example_common_operations_psycopg.md)。 --- --- url: /en/docs/latest-lite/developer_guide/connection_cursor.md --- # connection.cursor() ## Function This method returns a new cursor object. ## Prototype ``` cursor(name=None, cursor_factory=None, scrollable=None, withhold=False) ``` ## Parameter **Table 1** connection.cursor parameters ## Return Value Cursor object (used for cusors that are programmed using Python in the entire database) ## Examples For details, see [Example: Common Operations](example_common_operations_psycopg.md). --- --- url: /en/docs/latest/developer_guide/connection_cursor.md --- # connection.cursor() ## Function This method returns a new cursor object. ## Prototype ``` cursor(name=None, cursor_factory=None, scrollable=None, withhold=False) ``` ## Parameter **Table 1** connection.cursor parameters ## Return Value Cursor object (used for cusors that are programmed using Python in the entire database) ## Examples For details, see [Example: Common Operations](example_common_operations_psycopg.md). --- --- url: /zh/docs/latest-lite/developer_guide/connection_cursor.md --- # connection.cursor() ## 功能描述 此方法用于返回新的cursor对象。 ## 原型 ``` cursor(name=None, cursor_factory=None, scrollable=None, withhold=False) ``` ## 参数 **表 1** connection.cursor参数 ## 返回值 cursor对象(用于整个数据库使用Python编程的cursor)。 ## 示例 请参见[示例:常用操作](example_common_operations_psycopg.md)。 --- --- url: /zh/docs/latest/developer_guide/connection_cursor.md --- # connection.cursor() ## 功能描述 此方法用于返回新的cursor对象。 ## 原型 ``` cursor(name=None, cursor_factory=None, scrollable=None, withhold=False) ``` ## 参数 **表 1** connection.cursor参数 ## 返回值 cursor对象(用于整个数据库使用Python编程的cursor)。 ## 示例 请参见[示例:常用操作](example_common_operations_psycopg.md)。 --- --- url: /en/docs/latest-lite/developer_guide/connection_rollback.md --- # connection.rollback() ## Function This method rolls back the current pending transaction. > \[!WARNING]CAUTION > If you close the connection using **close()** but do not commit the change using **commit()**, an implicit rollback will be performed. ## Prototype ``` connection.rollback() ``` ## Parameter None ## Return Value None ## Examples For details, see [Example: Common Operations](example_common_operations_psycopg.md). --- --- url: /en/docs/latest/developer_guide/connection_rollback.md --- # connection.rollback() ## Function This method rolls back the current pending transaction. > \[!WARNING]CAUTION > If you close the connection using **close()** but do not commit the change using **commit()**, an implicit rollback will be performed. ## Prototype ``` connection.rollback() ``` ## Parameter None ## Return Value None ## Examples For details, see [Example: Common Operations](example_common_operations_psycopg.md). --- --- url: /zh/docs/latest-lite/developer_guide/connection_rollback.md --- # connection.rollback() ## 功能描述 此方法回滚当前挂起事务。 > \[!WARNING]注意 > 执行关闭连接“close()”而不先提交更改“commit()”将导致执行隐式回滚。 ## 原型 ``` connection.rollback() ``` ## 参数 无。 ## 返回值 无。 ## 示例 请参见[示例:常用操作](example_common_operations_psycopg.md)。 --- --- url: /zh/docs/latest/developer_guide/connection_rollback.md --- # connection.rollback() ## 功能描述 此方法回滚当前挂起事务。 > \[!WARNING]注意 > 执行关闭连接“close()”而不先提交更改“commit()”将导致执行隐式回滚。 ## 原型 ``` connection.rollback() ``` ## 参数 无。 ## 返回值 无。 ## 示例 请参见[示例:常用操作](example_common_operations_psycopg.md)。 --- --- url: /en/docs/latest-lite/sql_reference/constant_and_macro.md --- # Constant and Macro [Table 1](#en-us_topic_0283136888_en-us_topic_0237121963_en-us_topic_0059778360_en-us_topic_0058965862_table49126904) lists the constants and macros that can be used in openGauss. **Table 1** Constant and macro --- --- url: /en/docs/latest/sql_reference/constant_and_macro.md --- # Constant and Macro [Table 1](#en-us_topic_0283136888_en-us_topic_0237121963_en-us_topic_0059778360_en-us_topic_0058965862_table49126904) lists the constants and macros that can be used in openGauss. **Table 1** Constant and macro --- --- url: /en/docs/latest-lite/developer_guide/constraint_design.md --- # Constraint Design ## DEFAULT and NULL Constraints * \[Proposal] If all the column values can be obtained from services, you are not advised to use the **DEFAULT** constraint. Otherwise, unexpected results will be generated during data loading. * \[Proposal] Add **NOT NULL** constraints to columns that never have NULL values. The optimizer automatically optimizes the columns in certain scenarios. * \[Proposal] Explicitly name all constraints excluding **NOT NULL** and **DEFAULT**. ## Partial Cluster Keys A partial cluster key (PCK) is a local clustering technology used for column-store tables. After creating a PCK, you can quickly filter and scan fact tables using min or max sparse indexes in openGauss. Comply with the following rules to create a PCK: * \[Notice] Only one PCK can be created in a table. A PCK can contain multiple columns, preferably no more than two columns. * \[Proposal] Create a PCK on simple expression filter conditions in a query. Such filter conditions are usually in the form of **col op const**, where **col** specifies a column name, **op** specifies an operator (such as =, >, >=, <=, and <), and **const** specifies a constant. * \[Proposal] If the preceding conditions are met, create a PCK on the column having the most distinct values. ## Unique Constraints * \[Notice] Both row-store and column-store tables support unique constraints. * \[Proposal] The constraint name should indicate that it is a unique constraint, for example, **UNI***Included columns*. ## Primary Key Constraints * \[Notice] Both row-store and column-store tables support primary key constraints. * \[Proposal] The constraint name should indicate that it is a primary key constraint, for example, **PK***Included columns*. ## Check Constraints * \[Notice] Check constraints can be used in row-store tables but not in column-store tables. * \[Proposal] The constraint name should indicate that it is a check constraint, for example, **CK***Included columns*. --- --- url: /en/docs/latest/developer_guide/constraint_design.md --- # Constraint Design ## DEFAULT and NULL Constraints * \[Proposal] If all the column values can be obtained from services, you are not advised to use the **DEFAULT** constraint. Otherwise, unexpected results will be generated during data loading. * \[Proposal] Add **NOT NULL** constraints to columns that never have NULL values. The optimizer automatically optimizes the columns in certain scenarios. * \[Proposal] Explicitly name all constraints excluding **NOT NULL** and **DEFAULT**. ## Partial Cluster Keys A partial cluster key (PCK) is a local clustering technology used for column-store tables. After creating a PCK, you can quickly filter and scan fact tables using min or max sparse indexes in openGauss. Comply with the following rules to create a PCK: * \[Notice] Only one PCK can be created in a table. A PCK can contain multiple columns, preferably no more than two columns. * \[Proposal] Create a PCK on simple expression filter conditions in a query. Such filter conditions are usually in the form of **col op const**, where **col** specifies a column name, **op** specifies an operator (such as =, >, >=, <=, and <), and **const** specifies a constant. * \[Proposal] If the preceding conditions are met, create a PCK on the column having the most distinct values. ## Unique Constraints * \[Notice] Unique constraints can be used in row-store tables and column-store tables. * \[Proposal] The constraint name should indicate that it is a unique constraint, for example, **UNI***Included columns*. ## Primary Key Constraints * \[Notice] Primary key constraints can be used in row-store tables and column-store tables. * \[Proposal] The constraint name should indicate that it is a primary key constraint, for example, **PK***Included columns*. ## Check Constraints * \[Notice] Check constraints can be used in row-store tables but not in column-store tables. * \[Proposal] The constraint name should indicate that it is a check constraint, for example, **CK***Included columns*. --- --- url: /en/docs/latest-lite/brief_tutorial/constraints.md --- # Constraints Constraint clauses specify constraints that new or updated rows must satisfy for an INSERT or UPDATE operation to succeed. If there is any data behavior that violates the constraints, the behavior is terminated by the constraints. Constraints can be specified when a table is created (by executing the CREATE TABLE statement) or after a table is created (by executing the ALTER TABLE statement). Constraints can be column-level or table-level. Column-level constraints apply only to columns, and table-level constraints apply to the entire table. The common constraints of openGauss are as follows: * NOT NULL: specifies that a column cannot store **NULL** values. * UNIQUE: ensures that the value of a column is unique. * PRIMARY KEY: functions as the combination of NOT NULL and UNIQUE and ensures that a column (or the combination of two or more columns) has a unique identifier to help quickly locate a specific record in a table. * FOREIGN KEY: ensures the referential integrity for data in one table to match values in another table. * CHECK: ensures that values in a column meet specified conditions. ## NOT NULL If no constraint is specified during table creation, the default value is **NULL**, indicating that **NULL** values can be inserted into columns. If you do not want a column to be set to **NULL**, you need to define the NOT NULL constraint on the column to specify that **NULL** values are not allowed in the column. When you insert data, if the column contains **NULL**, an error is reported and the data fails to be inserted. **NULL** does not mean that there is no data. It indicates unknown data. For example, create the **staff** table that contains five columns. The **NAME** and **ID** columns cannot be set to **NULL**. ``` openGauss=# CREATE TABLE staff( ID INT NOT NULL, NAME char(8) NOT NULL, AGE INT , ADDRESS CHAR(50), SALARY REAL ); ``` Insert data into the **staff** table. When a **NULL** value is inserted into the **ID** column, the database returns an error. ``` openGauss=# INSERT INTO staff VALUES (1,'lily',28); INSERT 0 1 openGauss=# INSERT INTO staff (NAME,AGE) VALUES ('JUCE',28); ERROR: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, JUCE , 28, null, null). ``` ## UNIQUE The UNIQUE constraint specifies that a group of one or more columns of a table can contain only unique values. For the UNIQUE constraint, **NULL** is not considered equal. For example, create the **staff1** table that contains five columns, where **AGE** is set to **UNIQUE**. Therefore, you cannot add two records with the same age. ``` openGauss=# CREATE TABLE staff1( ID INT NOT NULL, NAME char(8) NOT NULL, AGE INT NOT NULL UNIQUE , ADDRESS CHAR(50), SALARY REAL ); ``` Insert data into the **staff1** table. When two identical data records are inserted into the **AGE** column, the database returns an error. ``` openGauss=# INSERT INTO staff1 VALUES (1,'lily',28); INSERT 0 1 openGauss=# INSERT INTO staff1 VALUES (2, 'JUCE',28); ERROR: duplicate key value violates unique constraint "staff1_age_key" DETAIL: Key (age)=(28) already exists. ``` ## PRIMARY KEY PRIMARY KEY is the unique identifier of each record in a data table. It specifies that a column or multiple columns in a table can contain only unique (non-duplicate) and non-**NULL** values. PRIMARY KEY is the combination of NOT NULL and UNIQUE. Only one primary key can be specified for a table. For example, create the **staff2** table where **ID** indicates the primary key. ``` openGauss=# CREATE TABLE staff2( ID INT PRIMARY KEY , NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "staff2_pkey" for table "staff2" CREATE TABLE ``` ## FOREIGN KEY The FOREIGN KEY constraint specifies that the value of a column (or a group of columns) must match the value in a row of another table. Generally, the FOREIGN KEY constraint in one table points to the UNIQUE KEY constraint in another table. That is, the referential integrity between two related tables is maintained. For example, create the **staff3** table that contains five columns. ``` openGauss=# CREATE TABLE staff3( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); ``` Create the **DEPARTMENT** table and add three columns. The **EMP\_ID** column indicates the foreign key and it is similar to the **ID** column of the **staff3** table. ``` openGauss=# CREATE TABLE DEPARTMENT( ID INT PRIMARY KEY NOT NULL, DEPT CHAR(50) NOT NULL, EMP_ID INT references staff3(ID) ); ``` ## CHECK The CHECK constraint specifies an expression producing a Boolean result where the INSERT or UPDATE operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A CHECK constraint specified as a column constraint should reference only the column's value, while an expression in a table constraint can reference multiple columns. **<>NULL** and **!=NULL** are invalid in an expression. Change them to **IS NOT NULL**. For example, create the **staff4** table and add a CHECK constraint to the **SALARY** column to ensure that the inserted value is greater than **0**. ``` openGauss=# CREATE TABLE staff4( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL CHECK(SALARY > 0) ); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "staff4_pkey" for table "staff4" CREATE TABLE ``` Insert data into the **staff4** table. When the inserted value of the **SALARY** column is not greater than **0**, the database reports an error. ``` openGauss=# INSERT INTO staff4(ID,NAME,AGE,SALARY) VALUES (2, 'JUCE',16,0); ERROR: new row for relation "staff4" violates check constraint "staff4_salary_check" DETAIL: N/A ``` --- --- url: /en/docs/latest-lite/sql_reference/constraints.md --- # Constraints Constraint clauses specify constraints that new or updated rows must satisfy for an INSERT or UPDATE operation to succeed. If there is any data behavior that violates the constraints, the behavior is terminated by the constraints. Constraints can be specified when a table is created (by executing the CREATE TABLE statement) or after a table is created (by executing the ALTER TABLE statement). Constraints can be column-level or table-level. Column-level constraints apply only to columns, and table-level constraints apply to the entire table. The common constraints of openGauss are as follows: * NOT NULL: specifies that a column cannot store **NULL** values. * UNIQUE: ensures that the value of a column is unique. * PRIMARY KEY: functions as the combination of NOT NULL and UNIQUE and ensures that a column (or the combination of two or more columns) has a unique identifier to help quickly locate a specific record in a table. * FOREIGN KEY: ensures the referential integrity for data in one table to match values in another table. * CHECK: ensures that values in a column meet specified conditions. ## NOT NULL If no constraint is specified during table creation, the default value is **NULL**, indicating that **NULL** values can be inserted into columns. If you do not want a column to be set to **NULL**, you need to define the NOT NULL constraint on the column to specify that **NULL** values are not allowed in the column. When you insert data, if the column contains **NULL**, an error is reported and the data fails to be inserted. **NULL** does not mean that there is no data. It indicates unknown data. For example, create the **staff** table that contains five columns. The **NAME** and **ID** columns cannot be set to **NULL**. ``` openGauss=# CREATE TABLE staff( ID INT NOT NULL, NAME char(8) NOT NULL, AGE INT , ADDRESS CHAR(50), SALARY REAL ); ``` Insert data into the **staff** table. When a **NULL** value is inserted into the **ID** column, the database returns an error. ``` openGauss=# INSERT INTO staff VALUES (1,'lily',28); INSERT 0 1 openGauss=# INSERT INTO staff (NAME,AGE) VALUES ('JUCE',28); ERROR: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, JUCE , 28, null, null). ``` ## UNIQUE The UNIQUE constraint specifies that a group of one or more columns of a table can contain only unique values. For the UNIQUE constraint, **NULL** is not considered equal. For example, create the **staff1** table that contains five columns, where **AGE** is set to **UNIQUE**. Therefore, you cannot add two records with the same age. ``` openGauss=# CREATE TABLE staff1( ID INT NOT NULL, NAME char(8) NOT NULL, AGE INT NOT NULL UNIQUE , ADDRESS CHAR(50), SALARY REAL ); ``` Insert data into the **staff1** table. When two identical data records are inserted into the **AGE** column, the database returns an error. ``` openGauss=# INSERT INTO staff1 VALUES (1,'lily',28); INSERT 0 1 openGauss=# INSERT INTO staff1 VALUES (2, 'JUCE',28); ERROR: duplicate key value violates unique constraint "staff1_age_key" DETAIL: Key (age)=(28) already exists. ``` ## PRIMARY KEY PRIMARY KEY is the unique identifier of each record in a data table. It specifies that a column or multiple columns in a table can contain only unique (non-duplicate) and non-**NULL** values. PRIMARY KEY is the combination of NOT NULL and UNIQUE. Only one primary key can be specified for a table. For example, create the **staff2** table where **ID** indicates the primary key. ``` openGauss=# CREATE TABLE staff2( ID INT PRIMARY KEY , NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "staff2_pkey" for table "staff2" CREATE TABLE ``` ## FOREIGN KEY The FOREIGN KEY constraint specifies that the value of a column (or a group of columns) must match the value in a row of another table. Generally, the FOREIGN KEY constraint in one table points to the UNIQUE KEY constraint in another table. That is, the referential integrity between two related tables is maintained. For example, create the **staff3** table that contains five columns. ``` openGauss=# CREATE TABLE staff3( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); ``` Create the **DEPARTMENT** table and add three columns. The **EMP\_ID** column indicates the foreign key and it is similar to the **ID** column of the **staff3** table. ``` openGauss=# CREATE TABLE DEPARTMENT( ID INT PRIMARY KEY NOT NULL, DEPT CHAR(50) NOT NULL, EMP_ID INT references staff3(ID) ); ``` ## CHECK The CHECK constraint specifies an expression producing a Boolean result where the INSERT or UPDATE operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A CHECK constraint specified as a column constraint should reference only the column's value, while an expression in a table constraint can reference multiple columns. **<>NULL** and **!=NULL** are invalid in an expression. Change them to **IS NOT NULL**. For example, create the **staff4** table and add a CHECK constraint to the **SALARY** column to ensure that the inserted value is greater than **0**. ``` openGauss=# CREATE TABLE staff4( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL CHECK(SALARY > 0) ); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "staff4_pkey" for table "staff4" CREATE TABLE ``` Insert data into the **staff4** table. When the inserted value of the **SALARY** column is not greater than **0**, the database reports an error. ``` openGauss=# INSERT INTO staff4(ID,NAME,AGE,SALARY) VALUES (2, 'JUCE',16,0); ERROR: new row for relation "staff4" violates check constraint "staff4_salary_check" DETAIL: N/A ``` --- --- url: /en/docs/latest/sql_reference/brief_tutorial/constraints.md --- # Constraints Constraint clauses specify constraints that new or updated rows must satisfy for an INSERT or UPDATE operation to succeed. If there is any data behavior that violates the constraints, the behavior is terminated by the constraints. Constraints can be specified when a table is created (by executing the CREATE TABLE statement) or after a table is created (by executing the ALTER TABLE statement). Constraints can be column-level or table-level. Column-level constraints apply only to columns, and table-level constraints apply to the entire table. The common constraints of openGauss are as follows: * NOT NULL: specifies that a column cannot store **NULL** values. * UNIQUE: ensures that the value of a column is unique. * PRIMARY KEY: functions as the combination of NOT NULL and UNIQUE and ensures that a column (or the combination of two or more columns) has a unique identifier to help quickly locate a specific record in a table. * FOREIGN KEY: ensures the referential integrity for data in one table to match values in another table. * CHECK: ensures that values in a column meet specified conditions. ## NOT NULL If no constraint is specified during table creation, the default value is **NULL**, indicating that **NULL** values can be inserted into columns. If you do not want a column to be set to **NULL**, you need to define the NOT NULL constraint on the column to specify that **NULL** values are not allowed in the column. When you insert data, if the column contains **NULL**, an error is reported and the data fails to be inserted. **NULL** does not mean that there is no data. It indicates unknown data. For example, create the **staff** table that contains five columns. The **NAME** and **ID** columns cannot be set to **NULL**. ``` openGauss=# CREATE TABLE staff( ID INT NOT NULL, NAME char(8) NOT NULL, AGE INT , ADDRESS CHAR(50), SALARY REAL ); ``` Insert data into the **staff** table. When a **NULL** value is inserted into the **ID** column, the database returns an error. ``` openGauss=# INSERT INTO staff VALUES (1,'lily',28); INSERT 0 1 openGauss=# INSERT INTO staff (NAME,AGE) VALUES ('JUCE',28); ERROR: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, JUCE , 28, null, null). ``` ## UNIQUE The UNIQUE constraint specifies that a group of one or more columns of a table can contain only unique values. For the UNIQUE constraint, **NULL** is not considered equal. For example, create the **staff1** table that contains five columns, where **AGE** is set to **UNIQUE**. Therefore, you cannot add two records with the same age. ``` openGauss=# CREATE TABLE staff1( ID INT NOT NULL, NAME char(8) NOT NULL, AGE INT NOT NULL UNIQUE , ADDRESS CHAR(50), SALARY REAL ); ``` Insert data into the **staff1** table. When two identical data records are inserted into the **AGE** column, the database returns an error. ``` openGauss=# INSERT INTO staff1 VALUES (1,'lily',28); INSERT 0 1 openGauss=# INSERT INTO staff1 VALUES (2, 'JUCE',28); ERROR: duplicate key value violates unique constraint "staff1_age_key" DETAIL: Key (age)=(28) already exists. ``` ## PRIMARY KEY PRIMARY KEY is the unique identifier of each record in a data table. It specifies that a column or multiple columns in a table can contain only unique (non-duplicate) and non-**NULL** values. PRIMARY KEY is the combination of NOT NULL and UNIQUE. Only one primary key can be specified for a table. For example, create the **staff2** table where **ID** indicates the primary key. ``` openGauss=# CREATE TABLE staff2( ID INT PRIMARY KEY , NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "staff2_pkey" for table "staff2" CREATE TABLE ``` ## FOREIGN KEY The FOREIGN KEY constraint specifies that the value of a column (or a group of columns) must match the value in a row of another table. Generally, the FOREIGN KEY constraint in one table points to the UNIQUE KEY constraint in another table. That is, the referential integrity between two related tables is maintained. For example, create the **staff3** table that contains five columns. ``` openGauss=# CREATE TABLE staff3( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); ``` Create the **DEPARTMENT** table and add three columns. The **EMP\_ID** column indicates the foreign key and it is similar to the **ID** column of the **staff3** table. ``` openGauss=# CREATE TABLE DEPARTMENT( ID INT PRIMARY KEY NOT NULL, DEPT CHAR(50) NOT NULL, EMP_ID INT references staff3(ID) ); ``` ## CHECK The CHECK constraint specifies an expression producing a Boolean result where the INSERT or UPDATE operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A CHECK constraint specified as a column constraint should reference only the column's value, while an expression in a table constraint can reference multiple columns. **<>NULL** and **!=NULL** are invalid in an expression. Change them to **IS NOT NULL**. For example, create the **staff4** table and add a CHECK constraint to the **SALARY** column to ensure that the inserted value is greater than **0**. ``` openGauss=# CREATE TABLE staff4( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL CHECK(SALARY > 0) ); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "staff4_pkey" for table "staff4" CREATE TABLE ``` Insert data into the **staff4** table. When the inserted value of the **SALARY** column is not greater than **0**, the database reports an error. ``` openGauss=# INSERT INTO staff4(ID,NAME,AGE,SALARY) VALUES (2, 'JUCE',16,0); ERROR: new row for relation "staff4" violates check constraint "staff4_salary_check" DETAIL: N/A ``` --- --- url: /en/docs/latest/sql_reference/constraints.md --- # Constraints Constraint clauses specify constraints that new or updated rows must satisfy for an INSERT or UPDATE operation to succeed. If there is any data behavior that violates the constraints, the behavior is terminated by the constraints. Constraints can be specified when a table is created (by executing the CREATE TABLE statement) or after a table is created (by executing the ALTER TABLE statement). Constraints can be column-level or table-level. Column-level constraints apply only to columns, and table-level constraints apply to the entire table. The common constraints of openGauss are as follows: * NOT NULL: specifies that a column cannot store **NULL** values. * UNIQUE: ensures that the value of a column is unique. * PRIMARY KEY: functions as the combination of NOT NULL and UNIQUE and ensures that a column (or the combination of two or more columns) has a unique identifier to help quickly locate a specific record in a table. * FOREIGN KEY: ensures the referential integrity for data in one table to match values in another table. * CHECK: ensures that values in a column meet specified conditions. ## NOT NULL If no constraint is specified during table creation, the default value is **NULL**, indicating that **NULL** values can be inserted into columns. If you do not want a column to be set to **NULL**, you need to define the NOT NULL constraint on the column to specify that **NULL** values are not allowed in the column. When you insert data, if the column contains **NULL**, an error is reported and the data fails to be inserted. **NULL** does not mean that there is no data. It indicates unknown data. For example, create the **staff** table that contains five columns. The **NAME** and **ID** columns cannot be set to **NULL**. ``` openGauss=# CREATE TABLE staff( ID INT NOT NULL, NAME char(8) NOT NULL, AGE INT , ADDRESS CHAR(50), SALARY REAL ); ``` Insert data into the **staff** table. When a **NULL** value is inserted into the **ID** column, the database returns an error. ``` openGauss=# INSERT INTO staff VALUES (1,'lily',28); INSERT 0 1 openGauss=# INSERT INTO staff (NAME,AGE) VALUES ('JUCE',28); ERROR: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, JUCE , 28, null, null). ``` ## UNIQUE The UNIQUE constraint specifies that a group of one or more columns of a table can contain only unique values. For the UNIQUE constraint, **NULL** is not considered equal. For example, create the **staff1** table that contains five columns, where **AGE** is set to **UNIQUE**. Therefore, you cannot add two records with the same age. ``` openGauss=# CREATE TABLE staff1( ID INT NOT NULL, NAME char(8) NOT NULL, AGE INT NOT NULL UNIQUE , ADDRESS CHAR(50), SALARY REAL ); ``` Insert data into the **staff1** table. When two identical data records are inserted into the **AGE** column, the database returns an error. ``` openGauss=# INSERT INTO staff1 VALUES (1,'lily',28); INSERT 0 1 openGauss=# INSERT INTO staff1 VALUES (2, 'JUCE',28); ERROR: duplicate key value violates unique constraint "staff1_age_key" DETAIL: Key (age)=(28) already exists. ``` ## PRIMARY KEY PRIMARY KEY is the unique identifier of each record in a data table. It specifies that a column or multiple columns in a table can contain only unique (non-duplicate) and non-**NULL** values. PRIMARY KEY is the combination of NOT NULL and UNIQUE. Only one primary key can be specified for a table. For example, create the **staff2** table where **ID** indicates the primary key. ``` openGauss=# CREATE TABLE staff2( ID INT PRIMARY KEY , NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "staff2_pkey" for table "staff2" CREATE TABLE ``` ## FOREIGN KEY The FOREIGN KEY constraint specifies that the value of a column (or a group of columns) must match the value in a row of another table. Generally, the FOREIGN KEY constraint in one table points to the UNIQUE KEY constraint in another table. That is, the referential integrity between two related tables is maintained. For example, create the **staff3** table that contains five columns. ``` openGauss=# CREATE TABLE staff3( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); ``` Create the **DEPARTMENT** table and add three columns. The **EMP\_ID** column indicates the foreign key and it is similar to the **ID** column of the **staff3** table. ``` openGauss=# CREATE TABLE DEPARTMENT( ID INT PRIMARY KEY NOT NULL, DEPT CHAR(50) NOT NULL, EMP_ID INT references staff3(ID) ); ``` ## CHECK The CHECK constraint specifies an expression producing a Boolean result where the INSERT or UPDATE operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A CHECK constraint specified as a column constraint should reference only the column's value, while an expression in a table constraint can reference multiple columns. **<>NULL** and **!=NULL** are invalid in an expression. Change them to **IS NOT NULL**. For example, create the **staff4** table and add a CHECK constraint to the **SALARY** column to ensure that the inserted value is greater than **0**. ``` openGauss=# CREATE TABLE staff4( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL CHECK(SALARY > 0) ); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "staff4_pkey" for table "staff4" CREATE TABLE ``` Insert data into the **staff4** table. When the inserted value of the **SALARY** column is not greater than **0**, the database reports an error. ``` openGauss=# INSERT INTO staff4(ID,NAME,AGE,SALARY) VALUES (2, 'JUCE',16,0); ERROR: new row for relation "staff4" violates check constraint "staff4_salary_check" DETAIL: N/A ``` --- --- url: /en/docs/latest-lite/sql_reference/constraints_on_index_use.md --- # Constraints on Index Use The following is an example of index use: ``` openGauss=# create table table1 (c_int int,c_bigint bigint,c_varchar varchar,c_text text) with(orientation=row); openGauss=# create text search configuration ts_conf_1(parser=POUND); openGauss=# create text search configuration ts_conf_2(parser=POUND) with(split_flag='%'); openGauss=# set default_text_search_config='ts_conf_1'; openGauss=# create index idx1 on table1 using gin(to_tsvector(c_text)); openGauss=# set default_text_search_config='ts_conf_2'; openGauss=# create index idx2 on table1 using gin(to_tsvector(c_text)); openGauss=# select c_varchar,to_tsvector(c_varchar) from table1 where to_tsvector(c_text) @@ plainto_tsquery('¥#@...&**') and to_tsvector(c_text) @@ plainto_tsquery('Company ') and c_varchar is not null order by 1 desc limit 3; ``` In this example, **table1** has two GIN indexes created on the same column **c\_text**, **idx1** and **idx2**, but these two indexes are created under different settings of [default\_text\_search\_config](../database_reference/locale_and_formatting.md#en-us_topic_0283136798_en-us_topic_0237124733_en-us_topic_0059778109_sd9a07d429cd4498383931c621742b816). Differences between this example and the scenario where one table has common indexes created on the same column are as follows: * GIN indexes use different parsers (that is, different delimiters). In this case, the index data of **idx1** is different from that of **idx2**. * In the specified scenario, the index data of multiple common indexes created on the same column is the same. As a result, using **idx1** and **idx2** for the same query returns different results. ## Constraints Concluding the example above, when: * Multiple GIN indexes are created on the same column of the same table. * The GIN indexes use different parsers (that is, different delimiters). * The column is used in a query, and an index scan is used in the execution plan. To avoid different query results caused by different GIN indexes, ensure that only one GIN index is available on a column of the physical table. --- --- url: /en/docs/latest/sql_reference/constraints_on_index_use.md --- # Constraints on Index Use The following is an example of index use: ``` openGauss=# create table table1 (c_int int,c_bigint bigint,c_varchar varchar,c_text text) with(orientation=row); openGauss=# create text search configuration ts_conf_1(parser=POUND); openGauss=# create text search configuration ts_conf_2(parser=POUND) with(split_flag='%'); openGauss=# set default_text_search_config='ts_conf_1'; openGauss=# create index idx1 on table1 using gin(to_tsvector(c_text)); openGauss=# set default_text_search_config='ts_conf_2'; openGauss=# create index idx2 on table1 using gin(to_tsvector(c_text)); openGauss=# select c_varchar,to_tsvector(c_varchar) from table1 where to_tsvector(c_text) @@ plainto_tsquery('¥#@...&**') and to_tsvector(c_text) @@ plainto_tsquery('Company ') and c_varchar is not null order by 1 desc limit 3; ``` In this example, **table1** has two GIN indexes created on the same column **c\_text**, **idx1** and **idx2**, but these two indexes are created under different settings of [default\_text\_search\_config](../database_reference/locale_and_formatting.md#en-us_topic_0283136798_en-us_topic_0237124733_en-us_topic_0059778109_sd9a07d429cd4498383931c621742b816). Differences between this example and the scenario where one table has common indexes created on the same column are as follows: * GIN indexes use different parsers (that is, different delimiters). In this case, the index data of **idx1** is different from that of **idx2**. * In the specified scenario, the index data of multiple common indexes created on the same column is the same. As a result, using **idx1** and **idx2** for the same query returns different results. ## Constraints Concluding the example above, when: * Multiple GIN indexes are created on the same column of the same table. * The GIN indexes use different parsers (that is, different delimiters). * The column is used in a query, and an index scan is used in the execution plan. To avoid different query results caused by different GIN indexes, ensure that only one GIN index is available on a column of the physical table. --- --- url: >- /en/docs/latest/database_administration_guide/constraints_on_the_resource_pooling_architecture.md --- # Constraints on the Resource Pooling Architecture ## Description openGauss resource pooling is a new cluster architecture launched by openGauss. The DMS and DSS components are used to implement underlying shared storage among multiple nodes in a cluster and real-time memory sharing among nodes. In this way, underlying storage resources are saved, write-once-read-many is supported in a cluster, and real-time consistent read is supported. This document describes the constraints on the resource pooling architecture. ## Current Constraints * **Note that these are temporary constraints and the features may be supported in the future.** | No.| Constraint| Remarks| |:--:|:--|:--| | 1 | Only segment-page storage is supported. Page-based storage is not supported.| The table creation statement must contain **with (segment = on, xxx)**.| | 2 | Row-store tables are not supported.| None| | 3 | FDW is not supported.| None| | 4 | Unlogged tables are not supported.| None| | 5 | Local temporary tables and global temporary tables are not supported.| None| | 6 | Features with compression are not supported.| None| | 7 | Materialized views are not supported.| None| | 8 | The standby node does not support the operation of starting a transaction.| None| | 9 | XA transactions are not supported.| None| | 10 | When the OM is used for installation, only disk array deployment is supported. Ceph and virtual storage pools are not supported.| None| | 11 | Publication and subscription are not supported.| None| | 12 | The traditional primary/standby architecture cannot be deployed at the same time.| That is, a cluster cannot use both the resource pooling primary/standby mode and the traditional primary/standby mode. That is, the **replconninfo** or **hot\_standby** parameter is not supported.| | 13 | Ustore is not supported.| Flashback is not supported because flashback supports only Ustore.| | 14 | The size of a single Xlog file is changed from 16 MB to 1 GB.| The recycling mechanism is also adapted to 1 GB, and the pg\_xlogdump tool is also adapted.| | 15 | You are not advised to disable Global SysCache.| This function is enabled by default and can be disabled through a configuration item. After this function is disabled, the connection may slow down in the case of high concurrency.| --- --- url: >- /en/docs/latest-lite/getting_started/container_based_installation_on_a_single_node.md --- # Container-based Installation on a Single Node This section describes how to install openGauss using Docker to facilitate installation, configuration, and environment setting for DevOps users. ## Supported Architectures and OSs * x86-64 CentOS 7.6 * ARM64 openEuler 20.03 LTS ## Preparations Use the **buildDockerImage.sh** script to build a Docker image. This script is a shell script that is easy to use and provides SHA-256 check. ## Creating an openGauss Docker Image > \[!NOTE]NOTE > > * Before the installation, you need to provide the openGauss binary installation package. After decompressing the package, place the package (**openGauss-Server-X.X.X-CentOS7-x86\_64.tar.bz2**) in the **dockerfiles/**<*version*> folder. The binary package can be downloaded from . Ensure that the correct yum source is available. > > * If the **-i** option is not specified when you run the **buildDockerImage.sh** script, the SHA-256 check is performed by default. You need to manually write the check result to the **sha256\_file\_amd64** file. > > ``` > ``` ``` ## Modify the SHA-256 verification file. ``` ``` cd /soft/openGauss-server/docker/dockerfiles/6.0.0 sha256sum openGauss-Server-X.X.X-CentOS7-x86_64.tar.bz2 > sha256_file_amd64 ``` > ``` > > - Before the installation, obtain the **openEuler\_aarch64.repo** file from Huawei open-source image website and save it to the **openGauss-server-master/docker/dockerfiles/6.0.0** folder. Run the following command to obtain the **openEuler\_aarch64.repo** file. > > ``` wget -O openEuler\_aarch64.repo > ``` > ``` Run the **buildDockerImage.sh** script in the **dockerfiles** folder. ``` [root@ecs-complie dockerfiles]# ./buildDockerImage.sh Usage: buildDockerImage.sh -v [version] [-i] [Docker build option] Builds a Docker Image for openGauss Parameters: -v: version to build Choose one of: 6.0.0 -i: ignores the SHA-256 checksums LICENSE UPL 1.0 ``` ## Environment Variables To flexibly use an openGauss image, you can set additional parameters. In the future, more control parameters will be added. The current version supports the setting of the following variables: **GS\_PASSWORD** This parameter is mandatory when the openGauss image is used. The value cannot be empty or undefined. This parameter specifies the passwords of superuser **omm** and test user **gaussdb** of the openGauss database. During the openGauss installation, the superuser **omm** is created by default. This username cannot be changed. The test user **gaussdb** is created in **entrypoint.sh**. The local trust mechanism is configured for the openGauss image. Therefore, no password is required for connecting to the database in the container. However, if you want to connect to the database from other hosts or containers, you need to enter the password. **Complexity requirements for openGauss password:** The password must contain at least eight characters, including uppercase letters, lowercase letters, digits, and special characters (**#?!@$%^&\*-**). \*\*!$&\*\*must be escaped using a backslash (\\). **GS\_NODENAME** Specifies the database node name. The default value is **gaussdb**. **GS\_USERNAME** Specifies the username for connecting to the database. The default value is **gaussdb**. **GS\_PORT** Specifies the database port. The default value is **5432**. ## Starting an Instance ``` $ docker run --name opengauss --privileged=true -d -e GS_PASSWORD=xxxxxx opengauss:6.0.0 ``` ## Connecting to the Database from the OS Layer ``` $ docker run --name opengauss --privileged=true -d -e GS_PASSWORD=xxxxxx -p8888:5432 opengauss:6.0.0 $ gsql -d postgres -U gaussdb -W'xxxxxx' -h your-host-ip -p8888 # OS need install gsql client ``` ## Data Persistence ``` $ docker run --name opengauss --privileged=true -d -e GS_PASSWORD=xxxxxx -v /opengauss:/var/lib/opengauss opengauss:6.0.0 ``` > **Note** > > 1. For details about how to use a database of another version to build a container image, see the configuration file in `openGauss-server/docker/dockerfiles/6.0.0`. You only need to change the version number to the corresponding version number. > > 2. If the `openeuler-20.03-lts:latest` image cannot be downloaded, download the container image package `openEuler-docker.aarch64.tar.xz` from the OpenEuler official website `https://repo.openeuler.org/openEuler-20.03-LTS/docker_img/aarch64/` and use `docker load -i openEuler-docker.aarch64.tar.xz` to import the package to the local image list. > > 3. During the build, if the yum source download times out, check the proxy. You can also `--network host` to the end of the `docker build` command in the `buildDockerImage.sh` script to use the network of the host machine. --- --- url: >- /en/docs/latest/getting_started/container_based_installation_on_a_single_node.md --- # Container-based Installation on a Single Node This section describes how to install openGauss using Docker to facilitate installation, configuration, and environment setting for DevOps users. ## Supported Architectures and OSs * x86-64 CentOS 7.6 * ARM64 openEuler 20.03 LTS ## Preparations Use the **buildDockerImage.sh** script to build a Docker image. This script is a shell script that is easy to use and provides SHA-256 check. ## Creating an openGauss Docker Image > \[!NOTE]NOTE > > * Before the installation, you need to provide the openGauss binary installation package. After decompressing the package, place the package (**openGauss-Server-X.X.X-CentOS7-x86\_64.tar.bz2**) in the **dockerfiles/**<*version*> folder. The binary package can be downloaded from . Ensure that the correct yum source is available. > > * If the **-i** option is not specified when you run the **buildDockerImage.sh** script, the SHA-256 check is performed by default. You need to manually write the check result to the **sha256\_file\_amd64** file. > > ``` > ``` ``` ## Modify the SHA-256 verification file. ``` ``` cd /soft/openGauss-server/docker/dockerfiles/6.0.0 sha256sum openGauss-Server-X.X.X-CentOS7-x86_64.tar.bz2 > sha256_file_amd64 ``` > ``` > > - Before the installation, obtain the **openEuler\_aarch64.repo** file from Huawei open-source image website and save it to the **openGauss-server-master/docker/dockerfiles/6.0.0** folder. Run the following command to obtain the **openEuler\_aarch64.repo** file. > > ``` wget -O openEuler\_aarch64.repo > ``` > ``` Run the **buildDockerImage.sh** script in the **dockerfiles** folder. ``` [root@ecs-complie dockerfiles]# ./buildDockerImage.sh Usage: buildDockerImage.sh -v [version] [-i] [Docker build option] Builds a Docker Image for openGauss Parameters: -v: version to build Choose one of: 6.0.0 -i: ignores the SHA-256 checksums LICENSE UPL 1.0 ``` ## Environment Variables To flexibly use an openGauss image, you can set additional parameters. In the future, more control parameters will be added. The current version supports the setting of the following variables: **GS\_PASSWORD** This parameter is mandatory when the openGauss image is used. The value cannot be empty or undefined. This parameter specifies the passwords of superuser **omm** and test user **gaussdb** of the openGauss database. During the openGauss installation, the superuser **omm** is created by default. This username cannot be changed. The test user **gaussdb** is created in **entrypoint.sh**. The local trust mechanism is configured for the openGauss image. Therefore, no password is required for connecting to the database in the container. However, if you want to connect to the database from other hosts or containers, you need to enter the password. **Complexity requirements for openGauss password:** The password must contain at least eight characters, including uppercase letters, lowercase letters, digits, and special characters (**#?!@$%^&\*-**). \*\*!$&\*\*must be escaped using a backslash (\\). **GS\_NODENAME** Specifies the database node name. The default value is **gaussdb**. **GS\_USERNAME** Specifies the username for connecting to the database. The default value is **gaussdb**. **GS\_PORT** Specifies the database port. The default value is **5432**. ## Starting an Instance ``` $ docker run --name opengauss --privileged=true -d -e GS_PASSWORD=xxxxxx opengauss:6.0.0 ``` ## Connecting to the Database from the OS Layer ``` $ docker run --name opengauss --privileged=true -d -e GS_PASSWORD=xxxxxx -p8888:5432 opengauss:6.0.0 $ gsql -d postgres -U gaussdb -W'xxxxxx' -h your-host-ip -p8888 # OS need install gsql client ``` ## Data Persistence ``` $ docker run --name opengauss --privileged=true -d -e GS_PASSWORD=xxxxxx -v /opengauss:/var/lib/opengauss opengauss:6.0.0 ``` > **Note** > > 1. For details about how to use a database of another version to build a container image, see the configuration file in `openGauss-server/docker/dockerfiles/6.0.0`. You only need to change the version number to the corresponding version number. > > 2. If the `openeuler-20.03-lts:latest` image cannot be downloaded, download the container image package `openEuler-docker.aarch64.tar.xz` from the OpenEuler official website `https://repo.openeuler.org/openEuler-20.03-LTS/docker_img/aarch64/` and use `docker load -i openEuler-docker.aarch64.tar.xz` to import the package to the local image list. > > 3. During the build, if the yum source download times out, check the proxy. You can also `--network host` to the end of the `docker build` command in the `buildDockerImage.sh` script to use the network of the host machine. --- --- url: /en/docs/latest-lite/sql_reference/controlling_transactions.md --- # Controlling Transactions A transaction is a user-defined sequence of database operations, which form an integral unit of work. ## Starting a Transaction openGauss starts a transaction using **START TRANSACTION** and **BEGIN**. For details, see [START TRANSACTION](start_transaction.md) and [BEGIN](begin.md). ## Setting a Transaction openGauss sets a transaction using **SET TRANSACTION** or **SET LOCAL TRANSACTION**. For details, see [SET TRANSACTION](set_transaction.md). ## Committing a Transaction openGauss commits all operations of a transaction using **COMMIT** or **END**. For details, see [COMMIT | END](commit_end.md). ## Rolling Back a Transaction If a fault occurs during a transaction and the transaction cannot proceed, the system performs rollback to cancel all the completed database operations related to the transaction. See [ROLLBACK](rollback.md). > \[!NOTE]NOTE > > If an execution request (not in a transaction block) received in the database contains multiple statements, the request is packed into a transaction. If one of the statements fails, the entire request will be rolled back. --- --- url: /en/docs/latest/sql_reference/controlling_transactions.md --- # Controlling Transactions A transaction is a user-defined sequence of database operations, which form an integral unit of work. ## Starting a Transaction openGauss starts a transaction using **START TRANSACTION** and **BEGIN**. For details, see [START TRANSACTION](start_transaction.md) and [BEGIN](begin.md). ## Setting a Transaction openGauss sets a transaction using **SET TRANSACTION** or **SET LOCAL TRANSACTION**. For details, see [SET TRANSACTION](set_transaction.md). ## Committing a Transaction openGauss commits all operations of a transaction using **COMMIT** or **END**. For details, see [COMMIT | END](commit_end.md). ## Rolling Back a Transaction If a fault occurs during a transaction and the transaction cannot proceed, the system performs rollback to cancel all the completed database operations related to the transaction. See [ROLLBACK](rollback.md). > \[!NOTE]NOTE > If an execution request (not in a transaction block) received in the database contains multiple statements, the request is packed into a transaction. If one of the statements fails, the entire request will be rolled back. --- --- url: >- /en/docs/latest-lite/database_administration_guide/converting_a_disk_table_into_an_mot_table.md --- # Converting a Disk Table into an MOT The direct conversion of disk tables into MOTs is not yet possible, meaning that no ALTER TABLE statement yet exists that converts a disk-based table into an MOT. The following describes how to manually perform a few steps in order to convert a disk-based table into an MOT, as well as how the **gs\_dump** tool is used to export data and the **gs\_restore** tool is used to import data. ## Prerequisite Check Check that the schema of the disk table to be converted into an MOT contains all required columns. Check whether the schema contains any unsupported column data types, as described in the Unsupported Data Types\_\_section. If a specific column is not supported, then it is advised to first create a secondary disk table with an updated schema. This schema is the same as the original table, except that all the unsupported types have been converted into supported types. Afterwards, use the following script to export this secondary disk table and then import it into an MOT. ## Conversion To covert a disk-based table into an MOT, perform the following: 1. Suspend application activity. 2. Use **gs\_dump** tool to dump the table's data into a physical file on disk. Make sure to use the **data only**. 3. Rename your original disk-based table. 4. Create an MOT with the same table name and schema. Make sure to use the create FOREIGN keyword to specify that it will be an MOT. 5. Use **gs\_restore** to load/restore data from the disk file into the database table. 6. Visually/manually verify that all the original data was imported correctly into the new MOT. An example is provided below. 7. Resume application activity. > \[!TIP]NOTICE > > In this way, since the table name remains the same, application queries and relevant database stored-procedures will be able to access the new MOT seamlessly without code changes. Please note that MOT does not currently support cross-engine multi-table queries (such as by using Join, Union and sub-query) and cross-engine multi-table transactions. Therefore, if an original table is accessed somewhere in a multi-table query, stored procedure or transaction, you must either convert all related disk-tables into MOTs or alter the relevant code in the application or the database. ## Conversion Example Let's say that you have a database name **benchmarksql** and a table named **customer** (which is a disk-based table) to be migrated it into an MOT. To migrate the customer table into an MOT, perform the following: 1. Check your source table column types. Verify that all types are supported by MOT, refer to section *Unsupported Data Types*. ``` benchmarksql-# \d+ customer Table "public.customer" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+-----------+---------+--------------+------------- x | integer | | plain | | y | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no ``` 2. Check your source table data. ``` benchmarksql=# select * from customer; x | y ---+--- 1 | 2 3 | 4 (2 rows) ``` 3. Dump table data only by using **gs\_dump**. ``` $ gs_dump -Fc benchmarksql -a --table customer -f customer.dump -p 16000 gs_dump[port='15500'][benchmarksql][2020-06-04 16:45:38]: dump database benchmarksql successfully gs_dump[port='15500'][benchmarksql][2020-06-04 16:45:38]: total time: 332 ms ``` 4. Rename the source table name. ``` benchmarksql=# alter table customer rename to customer_bk; ALTER TABLE ``` 5. Create the MOT to be the same as the source table. ``` benchmarksql=# create foreign table customer (x int, y int); CREATE FOREIGN TABLE benchmarksql=# select * from customer; x | y ---+--- (0 rows) ``` 6. Import the source dump data into the new MOT. ``` $ gs_restore -C -d benchmarksql customer.dump -p 16000 restore operation successful total time: 24 ms Check that the data was imported successfully. benchmarksql=# select * from customer; x | y ---+--- 1 | 2 3 | 4 (2 rows) benchmarksql=# \d List of relations Schema | Name | Type | Owner | Storage --------+-------------+---------------+--------+---------------------------------- public | customer | foreign table | aharon | public | customer_bk | table | aharon | {orientation=row,compression=no} (2 rows) ``` --- --- url: >- /en/docs/latest/database_administration_guide/converting_a_disk_table_into_an_mot_table.md --- # Converting a Disk Table into an MOT Table The direct conversion of disk tables into MOT tables is not yet possible, meaning that no ALTER TABLE statement yet exists that converts a disk-based table into an MOT table. The following describes how to manually perform a few steps in order to convert a disk-based table into an MOT table, as well as how the **gs\_dump** tool is used to export data and the **gs\_restore** tool is used to import data. ## Prerequisite Check Check that the schema of the disk table to be converted into an MOT table contains all required columns. Check whether the schema contains any unsupported column data types, as described in the Unsupported Data Types\_\_section. If a specific column is not supported, then it is recommended to first create a secondary disk table with an updated schema. This schema is the same as the original table, except that all the unsupported types have been converted into supported types. Afterwards, use the following script to export this secondary disk table and then import it into an MOT table. ## Converting To covert a disk-based table into an MOT table, perform the following – 1. Suspend application activity. 2. Use **gs\_dump** tool to dump the table's data into a physical file on disk. Make sure to use the **data only**. 3. Rename your original disk-based table. 4. Create an MOT table with the same table name and schema. Make sure to use the create FOREIGN keyword to specify that it will be an MOT table. 5. Use **gs\_restore** to load/restore data from the disk file into the database table. 6. Visually/manually verify that all the original data was imported correctly into the new MOT table. An example is provided below. 7. Resume application activity. **IMPORTANT Note** **–** In this way, since the table name remains the same, application queries and relevant database stored-procedures will be able to access the new MOT table seamlessly without code changes. An additional method is to copy data from a regular (Heap) table into the new MOT table by using an "INSERT INTO SELECT" statement. ``` INSERT INTO [MOT_table] SELECT * FROM [PG_table] WHERE condition; ``` This method is subject to MOT transaction size limitation of less than 1 GB. ## Conversion Example Let's say that you have a database name **benchmarksql** and a table named **customer** (which is a disk-based table) to be migrated it into an MOT table. To migrate the customer table into an MOT table, perform the following – 1. Check your source table column types. Verify that all types are supported by MOT, refer to section *Unsupported Data Types*. ``` benchmarksql-# \d+ customer Table "public.customer" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+-----------+---------+--------------+------------- x | integer | | plain | | y | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no ``` 2. Check your source table data. ``` benchmarksql=# select * from customer; x | y ---+--- 1 | 2 3 | 4 (2 rows) ``` 3. Dump table data only by using **gs\_dump**. ``` $ gs_dump -Fc benchmarksql -a --table customer -f customer.dump -p 16000 gs_dump[port='15500'][benchmarksql][2020-06-04 16:45:38]: dump database benchmarksql successfully gs_dump[port='15500'][benchmarksql][2020-06-04 16:45:38]: total time: 332 ms ``` 4. Rename the source table name. ``` benchmarksql=# alter table customer rename to customer_bk; ALTER TABLE ``` 5. Create the MOT table to be exactly the same as the source table. ``` benchmarksql=# create foreign table customer (x int, y int); CREATE FOREIGN TABLE benchmarksql=# select * from customer; x | y ---+--- (0 rows) ``` 6. Import the source dump data into the new MOT table. ``` $ gs_restore -C -d benchmarksql customer.dump -p 16000 restore operation successful total time: 24 ms Check that the data was imported successfully. benchmarksql=# select * from customer; x | y ---+--- 1 | 2 3 | 4 (2 rows) benchmarksql=# \d List of relations Schema | Name | Type | Owner | Storage --------+-------------+---------------+--------+---------------------------------- public | customer | foreign table | aharon | public | customer_bk | table | aharon | {orientation=row,compression=no} (2 rows) ``` --- --- url: /en/docs/latest-lite/sql_reference/copy.md --- # COPY ## Function **COPY** copies data between tables and files. **COPY FROM** copies data from a file to a table, and **COPY TO** copies data from a table to a file. ## Precautions * When the **enable\_copy\_server\_files** parameter is disabled, only the initial user is allowed to run the **COPY FROM FILENAME** or **COPY TO FILENAME** statement. When the **enable\_copy\_server\_files** parameter is enabled, users with the **SYSADMIN** permission or users who inherit the **gs\_role\_copy\_files** permission of the built-in role are allowed to run the **COPY FROM FILENAME** or **COPY TO FILENAME** statement. By default, **COPY FROM FILENAME** or **COPY TO FILENAME** cannot be run for database configuration file, key files, certificate files, and audit logs to prevent unauthorized users from viewing or modifying sensitive files. * **COPY** applies only to tables but not views. * **COPY TO** requires the select permission on the table to be read, and **COPY FROM** requires the insert permission on the table to be inserted. * If a list of columns is specified, **COPY** copies only the data of the specified columns between the file and the table. If a table has any columns that are not in the column list, **COPY FROM** inserts default values for those columns. * If a data source file is specified, the server must be able to access the file. If **STDIN** is specified, data flows between the client and the server. When entering data, use the **TAB** key to separate the columns of the table and use a backslash and a period (\\.) in a new row to indicate the end of the input. * **COPY FROM** throws an error if any row in the data file contains more or fewer columns than expected. * The end of the data can be represented by a line that contains only backslashes and periods (\\.). If data is read from a file, the end flag is unnecessary. If data is copied between client applications, an end tag must be provided. * In **COPY FROM**, **\N** is an empty string. To enter the actual value **\N**, use **\\\N**. * **COPY FROM** does not support data preprocessing during data import, such as expression operation and default value filling. If you need to preprocess data during the import, you need to import the data to a temporary table and then run SQL statements to insert the data to the table through operations. However, this method causes I/O expansion and reduces the import performance. * When a data format error occurs during **COPY FROM** execution, the transaction is rolled back. However, the error information is insufficient, making it difficult to locate the error data from a large amount of raw data. * **COPY FROM** and **COPY TO** apply to low concurrency and local import and export of a small amount of data. * If the target table has triggers, **COPY** is supported. ## Syntax * Copy data from a file to a table. ``` COPY table_name [ ( column_name [, ...] ) ] FROM { 'filename' | STDIN } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ LOG ERRORS ] [ LOG ERRORS DATA ] [ REJECT LIMIT 'limit' ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ] | [ TRANSFORM ( { column_name [ data_type ] [ AS transform_expr ] } [, ...] ) ]; ``` > \[!NOTE]NOTE > > In the syntax, **FIXED FORMATTER ({column\_name(offset, length)} \[, ...])** and **\[(option \[, ...]) | copy\_option \[...]]** can be in any sequence. * Copy data from a table to a file. ``` COPY table_name [ ( column_name [, ...] ) ] TO { 'filename' | STDOUT } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; COPY query TO { 'filename' | STDOUT } [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; ``` > \[!NOTE]NOTE > > 1. The syntax constraints of **COPY TO** are as follows: > **(query)** is incompatible with **\[USING] DELIMITER**. If the data comes from a query result, **COPY TO** cannot specify **\[USING] DELIMITERS**. > 2. Use spaces to separate **copy\_option** following **FIXED FORMATTTER**. > 3. **copy\_option** is the native parameter, while **option** is the parameter imported by a compatible foreign table. > 4. In the syntax, **FIXED FORMATTER ( { column\_name( offset, length ) } \[, ...] )** and **\[ ( option \[, ...] ) | copy\_option \[ ...] ]** can be in any sequence. The syntax of the optional parameter **option** is as follows: ``` FORMAT format_name | OIDS [ boolean ] | DELIMITER 'delimiter_character' | NULL 'null_string' | HEADER [ boolean ] | FILEHEADER 'header_file_string' | FREEZE [ boolean ] | QUOTE 'quote_character' | ESCAPE 'escape_character' | EOL 'newline_character' | NOESCAPING [ boolean ] | FORCE_QUOTE { ( column_name [, ...] ) | * } | FORCE_NOT_NULL ( column_name [, ...] ) | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA [ boolean ] | FILL_MISSING_FIELDS [ boolean ] | COMPATIBLE_ILLEGAL_CHARS [ boolean ] | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` The syntax of the optional parameter **copy\_option** is as follows: ``` OIDS | NULL 'null_string' | HEADER | FILEHEADER 'header_file_string' | FREEZE | FORCE NOT NULL column_name [, ...] | FORCE QUOTE { column_name [, ...] | * } | BINARY | CSV | QUOTE [ AS ] 'quote_character' | ESCAPE [ AS ] 'escape_character' | EOL 'newline_character' | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA | FILL_MISSING_FIELDS | COMPATIBLE_ILLEGAL_CHARS | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` ## Parameter Description * **query** Specifies that the results are to be copied. Valid value: a **SELECT** or **VALUES** command in parentheses * **table\_name** Specifies the name (possibly schema-qualified) of an existing table. Value range: an existing table name * **column\_name** Specifies an optional list of columns to be copied. Value range: any columns. All columns will be copied if no column list is specified. * **STDIN** Specifies that input comes from the standard input. * **STDOUT** Specifies that output goes to the standard output. * **FIXED** Fixes column length. When the column length is fixed, **DELIMITER**, **NULL**, and **CSV** cannot be specified. When **FIXED** is specified, **BINARY**, **CSV**, and **TEXT** cannot be specified by **option** or **copy\_option**. > \[!NOTE]NOTE > > The definition of fixed length is as follows: > > 1. The column length of each record is the same. > 2. Spaces are used for column padding. Columns of the numeric type are left-aligned and columns of the string type are right-aligned. > 3. No delimiters are used between columns. * **\[USING] DELIMITER 'delimiters'** The string that separates columns within each row (line) of the file, and it cannot be larger than 10 bytes. Value range: The delimiter cannot include any of the following characters: \\.abcdefghijklmnopqrstuvwxyz0123456789 Value range: The default value is a tab character in text format and a comma in CSV format. * **WITHOUT ESCAPING** Specifies, in text format, whether to escape the backslash (\\) and its following characters. Value range: text only * **LOG ERRORS** If this parameter is specified, the error tolerance mechanism for data type errors in the **COPY FROM** statement is enabled. Value range: a value set while data is imported using **COPY FROM**. > \[!NOTE]NOTE > > The restrictions of this error tolerance parameter are as follows: > > * This error tolerance mechanism captures only the data type errors (DATA\_EXCEPTION) that occur during data parsing of **COPY FROM** on the primary node of the database. > * If existing error tolerance parameters (for example, **IGNORE\_EXTRA\_DATA**) of the **COPY** statement are enabled, the error of the corresponding type will be processed as specified by the parameters and no error will be reported. Therefore, the error table does not contain such error data. * **LOG ERRORS DATA** The differences between **LOG ERRORS DATA** and **LOG ERRORS** are as follows: 1. **LOG ERRORS DATA** fills the **rawrecord** column in the error tolerance table. 2. Only users with the **super** permission can use the **LOG ERRORS DATA** parameter. > \[!WARNING]CAUTION > > If error content is too complex, it may fail to be written to the error tolerance table by using **LOG ERRORS DATA**, causing the task failure. * **REJECT LIMIT**'**limit'** Used with the **LOG ERROR** parameter to set the upper limit of the tolerated errors in the **COPY FROM** statement. If the number of errors exceeds the limit, later errors will be reported based on the original mechanism. Value range: a positive integer (1 to *INTMAX*) or **unlimited** Default value: If **LOG ERRORS** is not specified, an error will be reported. If **LOG ERRORS** is specified, the default value is **0**. > \[!NOTE]NOTE > > In the error tolerance mechanism described in the description of **LOG ERRORS**, the count of **REJECT LIMIT** is calculated based on the number of data parsing errors on the primary node of the database where the **COPY FROM** statement is executed, not based on the number of all errors on the primary node. * **FORMATTER** Defines the place of each column in the data file in fixed length mode. Defines the place of each column in the data file in the **column(***offset*,*length***)** format. Value range: * The value of **offset** must be larger than 0. The unit is byte. * The value of **length** must be larger than 0. The unit is byte. The total length of all columns must be less than 1 GB. Replace columns that are not in the file with null. * **OPTION { option\_name ' value ' }** Specifies all types of parameters of a compatible foreign table. * FORMAT Specifies the format of the source data file in the foreign table. Value range: **CSV**, **TEXT**, **FIXED**, and **BINARY** * The CSV file can process newline characters efficiently, but cannot process certain special characters well. * The TEXT file can process certain special characters efficiently, but cannot process newline characters well. * In FIXED files, the column length of each record is the same. Spaces are used for padding, and the excessive part will be truncated. * All data in the BINARY file is stored/read as binary format rather than as text. It is faster than the text and CSV formats, but a binary-format file is less portable. Default value: **TEXT** * DELIMITER Specifies the character that separates columns within each row (line) of the file. > \[!NOTE]NOTE > > * The value of **delimiter** cannot be **\r** or **\n**. > * A delimiter cannot be the same as the null value. The delimiter for the CSV format cannot be same as the **quote** value. > * The delimiter for the TEXT format data cannot contain lowercase letters, digits, or special characters (.\\). > * The data length of a single row should be less than 1 GB. A row that has many columns using long delimiters cannot contain much valid data. > * You are advised to use multi-character delimiters or invisible delimiters. For example, you can use multi-characters (such as $^&) and invisible characters (such as 0x07, 0x08, and 0x1b). Value range: a multi-character delimiter within 10 bytes Default value: * A tab character in text format * A comma (,) in CSV format * No delimiter in FIXED format * NULL Specifies the string that represents a null value. Value range: * A null value cannot be **\r** or **\n**. The maximum length is 100 characters. * A null value cannot be the same as the **delimiter** or **quote** value. Default value: * The default value for the CSV format is an empty string without quotation marks. * The default value for the TEXT format is **\N**. * HEADER Specifies whether a file contains a header with the names of each column in the file. **header** is available only for CSV and FIXED files. When data is imported, if **header** is **on**, the first row of the data file will be identified as the header and ignored. If **header** is **off**, the first row will be identified as a data row. When data is exported, if header is **on**, **fileheader** must be specified. If **header** is **off**, an exported file does not contain a header. Value range: **true**, **on**, **false**, and **off**. Default value: **false** * QUOTE Specifies a quoted character string for a CSV file. Default value: single quotation marks ('') > \[!NOTE]NOTE > > * The value of **quote** cannot be the same as that of the **delimiter** or **null** parameter. > * The value of **quote** must be a single-byte character. > * You are advised to set **quote** to an invisible character, such as **0x07**, **0x08**, or **0x1b**. * ESCAPE Specifies an escape character for a CSV file. The value must be a single-byte character. Default value: single quotation marks ('') If the value is the same as that of **quote**, it will be replaced by **\0**. * EOL 'newline\_character' Specifies the newline character style of the imported or exported data file. Value range: multi-character newline characters within 10 bytes. Common newline characters include **\r** (0x0D), **\n** (0x0A), and **\r\n**(0x0D0A). Special newline characters include **$** and **#**. > \[!NOTE]NOTE > > * The **EOL** parameter supports only the TEXT format for data import and export and does not support the CSV or FIXED format for data import. For forward compatibility, the EOL parameter can be set to **0x0D** or **0x0D0A** for data export in the CSV or FIXED format. > * The value of **EOL** cannot be the same as that of the **delimiter** or **null** parameter. > * The EOL parameter value cannot contain the following characters: .abcdefghijklmnopqrstuvwxyz0123456789. * FORCE\_QUOTE { ( column\_name \[, ...] ) | \* } In **CSV COPY TO** mode, forces quotation marks to be used for all non-null values in each specified column. Null values are not quoted. Value range: an existing column name * FORCE\_NOT\_NULL ( column\_name \[, ...] ) In **CSV COPY FROM** mode, the value for a specified column cannot be null. Value range: an existing column name * ENCODING Specifies the encoding of data files. If this option is omitted, the current client encoding is used. * IGNORE\_EXTRA\_DATA Specifies whether to ignore excessive columns when the number of data source files exceeds the number of foreign table columns. This parameter is used only during data import. Value range: **true**, **on**, **false**, and **off**. * If this parameter is set to **true** or **on** and the number of source data files exceeds the number of foreign table columns, excessive columns will be ignored. * When the parameter is **false** or **off**, and the number of data source files is more than the number of foreign table columns, the following error information will be displayed: ``` extra data after last expected column ``` Default value: **false** > \[!TIP]NOTICE > > If a newline character at the end of a row is missing and the row and another row are integrated into one, data in another row is ignored after the parameter is set to **true**. * COMPATIBLE\_ILLEGAL\_CHARS Specifies whether to tolerate invalid characters during data import. The parameter is valid only for data import using **COPY FROM**. Value range: **true**, **on**, **false**, and **off**. * If this parameter is set to **true** or **on**, invalid characters are tolerated and imported to the database after conversion. * If this parameter is set to **false** or **off** and an error occurs when there are invalid characters, the import will be interrupted. Default value: **false** or **off** > \[!NOTE]NOTE > > The rules for converting invalid characters are as follows: > > 1. **\0** is converted to a space. > 2. Other invalid characters are converted to question marks. > (3) If **compatible\_illegal\_chars** is set to **true** or **on**, invalid characters are tolerated. If **NULL**, **DELIMITER**, **QUOTE**, and **ESCAPE** are set to a spaces or question marks, errors like "illegal chars conversion may confuse COPY escape 0x20" will be displayed to prompt users to change parameter values that cause confusion, preventing import errors. * FILL\_MISSING\_FIELDS Specifies how to handle the problem that the last column of a row in a source data file is lost during data import. Value range: **true**, **on**, **false**, and **off**. Default value: **false** or **off** * DATE\_FORMAT Specifies the DATE format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid DATE value For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). > \[!NOTE]NOTE > > You can use the **TIMESTAMP\_FORMAT** parameter to set the DATE format to **TIMESTAMP** for data import. For details, see **TIMESTAMP\_FORMAT** below. * TIME\_FORMAT Specifies the TIME format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid TIME value. Time zones cannot be used. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * TIMESTAMP\_FORMAT Specifies the TIMESTAMP format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid TIMESTAMP value. Time zones cannot be used. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * SMALLDATETIME\_FORMAT Specifies the SMALLDATETIME format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid SMALLDATETIME value. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * **COPY\_OPTION { option\_name ' value ' }** Specifies all types of native parameters of **COPY**. * NULL null\_string Specifies the string that represents a null value. > \[!TIP]NOTICE > > When using **COPY FROM**, any data item that matches this string will be stored as a null value, so make sure that you use the same string as you used with **COPY TO**. Value range: * A null value cannot be **\r** or **\n**. The maximum length is 100 characters. * A null value cannot be the same as the **delimiter** or **quote** value. Default value: * The default value for the TEXT format is **\N**. * The default value for the CSV format is an empty string without quotation marks. * HEADER Specifies whether a file contains a header with the names of each column in the file. **header** is available only for CSV and FIXED files. When data is imported, if **header** is **on**, the first row of the data file will be identified as the header and ignored. If **header** is **off**, the first row will be identified as a data row. When data is exported, if header is **on**, **fileheader** must be specified. If **header** is **off**, an exported file does not contain a header. * FILEHEADER Specifies a file that defines the content in the header for exported data. The file contains data description of each column. > \[!TIP]NOTICE > > * This parameter is available only when **header** is **on** or **true**. > * **fileheader** specifies an absolute path. > * The file can contain only one row of header information, and ends with a newline character. Excess rows will be discarded. (Header information cannot contain newline characters.) > * The length of the file including the newline character cannot exceed 1 MB. * FREEZE Sets the **COPY** loaded data row as **frozen**, like these data have executed **VACUUM FREEZE**. This is a performance option of initial data loading. The data will be frozen only when the following three requirements are met: * The table being loaded has been created or truncated in the same transaction before copying. * There are no cursors open in the current transaction. * There are no original snapshots in the current transaction. > \[!NOTE]NOTE > > When **COPY** is completed, all the other sessions will see the data immediately. However, this violates the general principle of MVCC visibility, and users should understand that this may cause potential risks. * FORCE NOT NULL column\_name \[, ...] In **CSV COPY FROM** mode, the specified column is not null. If the column is null, its value is regarded as a string of 0 characters. Value range: an existing column name * FORCE NULL column\_name \[, ...] In **CSV COPY FROM** mode, set the string representing null value in the specified column to NULL, including the quoted null value string. Value range: an existing column name * FORCE QUOTE { column\_name \[, ...] | \* } In **CSV COPY TO** mode, forces quotation marks to be used for all non-null values in each specified column. Null values are not quoted. Value range: an existing column name * BINARY Specifies that data is stored and read in binary mode instead of text mode. In binary mode, you cannot declare **DELIMITER**, **NULL**, or **CSV**. When **BINARY** is specified, **CSV**, **FIXED**, and **TEXT** cannot be specified through **option** or **copy\_option**. * CSV Enables the CSV mode. When **CSV** is specified, **BINARY**, **FIXED**, and **TEXT** cannot be specified through **option** or **copy\_option**. * QUOTE \[AS] 'quote\_character' Specifies a quotation mark character string for a CSV file. Default value: single quotation marks ('') > \[!NOTE]NOTE > > * The value of **quote** cannot be the same as that of the **delimiter** or **null** parameter. > * The value of **quote** must be a single-byte character. > * You are advised to set **quote** to an invisible character, such as **0x07**, **0x08**, or **0x1b**. * ESCAPE \[AS] 'escape\_character' Specifies an escape character for a CSV file. The value must be a single-byte character. The default value is single quotation marks (''). If the value is the same as that of **quote**, it will be replaced by **\0**. * EOL 'newline\_character' Specifies the newline character style of the imported or exported data file. Value range: multi-character newline characters within 10 bytes. Common newline characters include **\r** (0x0D), **\n** (0x0A), and **\r\n** (0x0D0A). Special newline characters include **$** and **#**. > \[!NOTE]NOTE > > * The **EOL** parameter supports only the TEXT format for data import and export and does not support the CSV or FIXED format. For forward compatibility, the **EOL** parameter can be set to **0x0D** or **0x0D0A** for data export in the CSV or FIXED format. > * The value of **EOL** cannot be the same as that of the **delimiter** or **null** parameter. > * The EOL parameter value cannot contain the following characters: .abcdefghijklmnopqrstuvwxyz0123456789. * ENCODING 'encoding\_name' Specifies the name of a file encoding format. Value range: a valid encoding format Default value: current encoding format * IGNORE\_EXTRA\_DATA Specifies that when the number of data source files exceeds the number of foreign table columns, excess columns at the end of the row are ignored. This parameter is used only during data import. If this parameter is not used and the number of columns in the data source file is greater than that defined in the foreign table, the following error information is displayed: ``` extra data after last expected column ``` * COMPATIBLE\_ILLEGAL\_CHARS Specifies that invalid characters are tolerated during data import. Invalid characters are converted and then imported to the database. No error is reported and the import is not interrupted. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. If this parameter is not used, an error is reported when invalid characters are encountered during the import, and the import is interrupted. > \[!NOTE]NOTE > > The rules for converting invalid characters are as follows: > > 1. **\0** is converted to a space. > 2. Other invalid characters are converted to question marks. > 3. When **compatible\_illegal\_chars** is set to **true** or **on**, after invalid characters such as **NULL**, **DELIMITER**, **QUOTE**, and **ESCAPE** are converted to spaces or question marks, an error message like "illegal chars conversion may confuse COPY escape 0x20" will be displayed to remind you of possible parameter confusion caused by the conversion. * FILL\_MISSING\_FIELDS \[ { 'one' | 'multi' } ] Specifies how to handle the problem that the last columns of a row in a source data file are lost during data import. If **one** or **multi** is not specified or **one** is specified, the missing of the last column is handled in the default mode. If **multi** is specified, the missing of the last multiple columns are handled in the default mode. Value range: **true**, **on**, **false**, and **off**. Default value: **false** or **off** > \[!TIP]NOTICE > > Do not specify this option. Currently, it does not enable error tolerance, but will make the parser ignore the said errors during data parsing on the primary node of the database. Such errors will not be recorded in the COPY error table (enabled using **LOG ERRORS REJECT LIMIT**) but will be reported later by database node. Therefore, do not specify this option. * DATE\_FORMAT 'date\_format\_string' Specifies the DATE format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid DATE value For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). > \[!NOTE]NOTE > > You can use the **TIMESTAMP\_FORMAT** parameter to set the DATE format to **TIMESTAMP** for data import. For details, see **TIMESTAMP\_FORMAT** below. * TIME\_FORMAT 'time\_format\_string' Specifies the TIME format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid TIME value. Time zones cannot be used. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * TIMESTAMP\_FORMAT 'timestamp\_format\_string' Specifies the TIMESTAMP format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid TIMESTAMP value. Time zones cannot be used. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * SMALLDATETIME\_FORMAT 'smalldatetime\_format\_string' Specifies the SMALLDATETIME format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid SMALLDATETIME value. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * TRANSFORM ( { column\_name \[ data\_type ] \[ AS transform\_expr ] } \[, ...] ) Specify the conversion expression of each column in the table. **data\_type** specifies the data type of the column in the expression parameter. **transform\_expr** is the target expression that returns the result value whose data type is the same as that of the target column in the table. For details about the expression, see [Expressions](simple_expressions.md). * SKIP int\_number Specifies that the first *int\_number* rows of the data file are skipped during data import. * WHEN { ( start - end ) | column\_name } { = | != } 'string' When data is imported, each row of data is checked. Only the rows that meet the WHEN condition are imported to the table. * SEQUENCE ( { column\_name ( integer \[, incr] ) \[, ...] } ) During data import, columns modified by SEQUENCE do not read data from the data file. The values are incremented by the value of **incr** based on the specified integer. If **incr** is not specified, the values are incremented from 1 by default. * FILLER ( { column\_name \[, ...] } ) When data is imported, the column modified by FILLER is discarded after being read from the data file. > \[!NOTE]NOTE > > To use FILLER, you need to specify the list of columns to be copied. During data processing, data is processed based on the position of the **filler** column in the column list. * CONSTANT ( { column\_name 'constant\_string' \[, ...] } ) When data is imported, the column modified by CONSTANT is not read from the data file, and **constant\_string** is used to assign a value to the column. The following special backslash sequences are recognized by **COPY FROM**: * **\b**: Backslash (ASCII 8) * **\f**: Form feed (ASCII 12) * **\n**: Newline character (ASCII 10) * **\r**: Carriage return character (ASCII 13) * **\t**: Tab (ASCII 9) * **\v**: Vertical tab (ASCII 11) * **\digits**: Backslash followed by one to three octal digits specifies that the ASCII value is the character with that numeric code. * **\xdigits**: Backslash followed by an x and one or two hex digits specifies the character with that numeric code. ## Examples ``` -- Copy data from the tpcds.ship_mode file to the /home/omm/ds_ship_mode.dat file: openGauss=# COPY tpcds.ship_mode TO '/home/omm/ds_ship_mode.dat'; -- Output tpcds.ship_mode to stdout. openGauss=# COPY tpcds.ship_mode TO stdout; -- Create the tpcds.ship_mode_t1 table. openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- Copy data from stdin to the tpcds.ship_mode_t1 table. openGauss=# COPY tpcds.ship_mode_t1 FROM stdin; -- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table. openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat'; -- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table, convert the data using the TRANSFORM expression, and insert the 10 characters on the left of the SM_TYPE column into the table. openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' TRANSFORM (SM_TYPE AS LEFT(SM_TYPE, 10)); -- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table, with the import format set to TEXT (format 'text'), the delimiter set to \t' (delimiter E'\t'), excessive columns ignored (ignore_extra_data 'true'), and characters not escaped (noescaping 'true'). openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' WITH(format 'text', delimiter E'\t', ignore_extra_data 'true', noescaping 'true'); -- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table, with the import format set to FIXED, fixed-length format specified (FORMATTER(SM_SHIP_MODE_SK(0, 2), SM_SHIP_MODE_ID(2,16), SM_TYPE(18,30), SM_CODE(50,10), SM_CARRIER(61,20), SM_CONTRACT(82,20))), excessive columns ignored (ignore_extra_data), and headers included (header). openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' FIXED FORMATTER(SM_SHIP_MODE_SK(0, 2), SM_SHIP_MODE_ID(2,16), SM_TYPE(18,30), SM_CODE(50,10), SM_CARRIER(61,20), SM_CONTRACT(82,20)) header ignore_extra_data; -- Delete the tpcds.ship_mode_t1 table. openGauss=# DROP TABLE tpcds.ship_mode_t1; ``` --- --- url: /en/docs/latest/sql_reference/copy.md --- # COPY ## Function **COPY** copies data between tables and files. **COPY FROM** copies data from a file to a table, and **COPY TO** copies data from a table to a file. ## Precautions * When the **enable\_copy\_server\_files** parameter is disabled, only the initial user is allowed to run the **COPY FROM FILENAME** or **COPY TO FILENAME** statement. When the **enable\_copy\_server\_files** parameter is enabled, users with the **SYSADMIN** permission or users who inherit the **gs\_role\_copy\_files** permission of the built-in role are allowed to run the **COPY FROM FILENAME** or **COPY TO FILENAME** statement. By default, **COPY FROM FILENAME** or **COPY TO FILENAME** cannot be run for database configuration file, key files, certificate files, and audit logs to prevent unauthorized users from viewing or modifying sensitive files. * **COPY** applies only to tables but not views. * **COPY TO** requires the select permission on the table to be read, and **COPY FROM** requires the insert permission on the table to be inserted. * If a list of columns is specified, **COPY** copies only the data of the specified columns between the file and the table. If a table has any columns that are not in the column list, **COPY FROM** inserts default values for those columns. * If a data source file is specified, the server must be able to access the file. If **STDIN** is specified, data flows between the client and the server. When entering data, use the **TAB** key to separate the columns of the table and use a backslash and a period (\\.) in a new row to indicate the end of the input. * **COPY FROM** throws an error if any row in the data file contains more or fewer columns than expected. * The end of the data can be represented by a line that contains only backslashes and periods (\\.). If data is read from a file, the end flag is unnecessary. If data is copied between client applications, an end tag must be provided. * In **COPY FROM**, **\N** is an empty string. To enter the actual value **\N**, use **\\\N**. * **COPY FROM** does not support data preprocessing during data import, such as expression operation and default value filling. If you need to preprocess data during the import, you need to import the data to a temporary table and then run SQL statements to insert the data to the table through operations. However, this method causes I/O expansion and reduces the import performance. * When a data format error occurs during **COPY FROM** execution, the transaction is rolled back. However, the error information is insufficient, making it difficult to locate the error data from a large amount of raw data. * **COPY FROM** and **COPY TO** apply to low concurrency and local import and export of a small amount of data. * If the target table has triggers, **COPY** is supported. ## Syntax * Copy data from a file to a table. ``` COPY table_name [ ( column_name [, ...] ) ] FROM { 'filename' | STDIN } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ LOG ERRORS ] [ LOG ERRORS DATA ] [ REJECT LIMIT 'limit' ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ] | [ TRANSFORM ( { column_name [ data_type ] [ AS transform_expr ] } [, ...] ) ]; ``` > \[!NOTE]NOTE > In the syntax, **FIXED FORMATTER ({column\_name(offset, length)} \[, ...])** and **\[(option \[, ...]) | copy\_option \[...]]** can be in any sequence. * Copy data from a table to a file. ``` COPY table_name [ ( column_name [, ...] ) ] TO { 'filename' | STDOUT } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; COPY query TO { 'filename' | STDOUT } [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; ``` > \[!NOTE]NOTE > > 1. The syntax constraints of **COPY TO** are as follows: > **(query)** is incompatible with **\[USING] DELIMITER**. If the data comes from a query result, **COPY TO** cannot specify **\[USING] DELIMITERS**. > 2. Use spaces to separate **copy\_option** following **FIXED FORMATTTER**. > 3. **copy\_option** is the native parameter, while **option** is the parameter imported by a compatible foreign table. > 4. In the syntax, **FIXED FORMATTER ( { column\_name( offset, length ) } \[, ...] )** and **\[ ( option \[, ...] ) | copy\_option \[ ...] ]** can be in any sequence. The syntax of the optional parameter **option** is as follows: ``` FORMAT format_name | OIDS [ boolean ] | DELIMITER 'delimiter_character' | NULL 'null_string' | HEADER [ boolean ] | FILEHEADER 'header_file_string' | FREEZE [ boolean ] | QUOTE 'quote_character' | ESCAPE 'escape_character' | EOL 'newline_character' | NOESCAPING [ boolean ] | FORCE_QUOTE { ( column_name [, ...] ) | * } | FORCE_NOT_NULL ( column_name [, ...] ) | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA [ boolean ] | FILL_MISSING_FIELDS [ boolean ] | COMPATIBLE_ILLEGAL_CHARS [ boolean ] | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` The syntax of the optional parameter **copy\_option** is as follows: ``` OIDS | NULL 'null_string' | HEADER | FILEHEADER 'header_file_string' | FREEZE | FORCE NOT NULL column_name [, ...] | FORCE QUOTE { column_name [, ...] | * } | BINARY | CSV | QUOTE [ AS ] 'quote_character' | ESCAPE [ AS ] 'escape_character' | EOL 'newline_character' | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA | FILL_MISSING_FIELDS | COMPATIBLE_ILLEGAL_CHARS | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` ## Parameter Description * **query** Specifies that the results are to be copied. Valid value: a **SELECT** or **VALUES** command in parentheses * **table\_name** Specifies the name (possibly schema-qualified) of an existing table. Value range: an existing table name * **column\_name** Specifies an optional list of columns to be copied. Value range: any columns. All columns will be copied if no column list is specified. * **STDIN** Specifies that input comes from the standard input. * **STDOUT** Specifies that output goes to the standard output. * **FIXED** Fixes column length. When the column length is fixed, **DELIMITER**, **NULL**, and **CSV** cannot be specified. When **FIXED** is specified, **BINARY**, **CSV**, and **TEXT** cannot be specified by **option** or **copy\_option**. > \[!NOTE]NOTE > The definition of fixed length is as follows: > > 1. The column length of each record is the same. > 2. Spaces are used for column padding. Columns of the numeric type are left-aligned and columns of the string type are right-aligned. > 3. No delimiters are used between columns. * **\[USING] DELIMITER 'delimiters'** The string that separates columns within each row (line) of the file, and it cannot be larger than 10 bytes. Value range: The delimiter cannot include any of the following characters: \\.abcdefghijklmnopqrstuvwxyz0123456789 Value range: The default value is a tab character in text format and a comma in CSV format. * **WITHOUT ESCAPING** Specifies, in text format, whether to escape the backslash (\\) and its following characters. Value range: text only * **LOG ERRORS** If this parameter is specified, the error tolerance mechanism for data type errors in the **COPY FROM** statement is enabled. Value range: a value set while data is imported using **COPY FROM**. > \[!NOTE]NOTE > The restrictions of this error tolerance parameter are as follows: > > * This error tolerance mechanism captures only the data type errors (DATA\_EXCEPTION) that occur during data parsing of **COPY FROM** on the primary node of the database. > * If existing error tolerance parameters (for example, **IGNORE\_EXTRA\_DATA**) of the **COPY** statement are enabled, the error of the corresponding type will be processed as specified by the parameters and no error will be reported. Therefore, the error table does not contain such error data. * **LOG ERRORS DATA** The differences between **LOG ERRORS DATA** and **LOG ERRORS** are as follows: 1. **LOG ERRORS DATA** fills the **rawrecord** column in the error tolerance table. 2. Only users with the **super** permission can use the **LOG ERRORS DATA** parameter. > \[!WARNING]CAUTION > If error content is too complex, it may fail to be written to the error tolerance table by using **LOG ERRORS DATA**, causing the task failure. * **REJECT LIMIT**'**limit'** Used with the **LOG ERROR** parameter to set the upper limit of the tolerated errors in the **COPY FROM** statement. If the number of errors exceeds the limit, later errors will be reported based on the original mechanism. Value range: a positive integer (1 to *INTMAX*) or **unlimited** Default value: If **LOG ERRORS** is not specified, an error will be reported. If **LOG ERRORS** is specified, the default value is **0**. > \[!NOTE]NOTE > In the error tolerance mechanism described in the description of **LOG ERRORS**, the count of **REJECT LIMIT** is calculated based on the number of data parsing errors on the primary node of the database where the **COPY FROM** statement is executed, not based on the number of all errors on the primary node. * **FORMATTER** Defines the place of each column in the data file in fixed length mode. Defines the place of each column in the data file in the **column(***offset*,*length***)** format. Value range: * The value of **offset** must be larger than 0. The unit is byte. * The value of **length** must be larger than 0. The unit is byte. The total length of all columns must be less than 1 GB. Replace columns that are not in the file with null. * **OPTION { option\_name ' value ' }** Specifies all types of parameters of a compatible foreign table. * FORMAT Specifies the format of the source data file in the foreign table. Value range: **CSV**, **TEXT**, **FIXED**, and **BINARY** * The CSV file can process newline characters efficiently, but cannot process certain special characters well. * The TEXT file can process certain special characters efficiently, but cannot process newline characters well. * In FIXED files, the column length of each record is the same. Spaces are used for padding, and the excessive part will be truncated. * All data in the BINARY file is stored/read as binary format rather than as text. It is faster than the text and CSV formats, but a binary-format file is less portable. Default value: **TEXT** * DELIMITER Specifies the character that separates columns within each row (line) of the file. > \[!NOTE]NOTE > > * The value of **delimiter** cannot be **\r** or **\n**. > * A delimiter cannot be the same as the null value. The delimiter for the CSV format cannot be same as the **quote** value. > * The delimiter for the TEXT format data cannot contain lowercase letters, digits, or special characters (.\\). > * The data length of a single row should be less than 1 GB. A row that has many columns using long delimiters cannot contain much valid data. > * You are advised to use multi-character delimiters or invisible delimiters. For example, you can use multi-characters (such as $^&) and invisible characters (such as 0x07, 0x08, and 0x1b). Value range: a multi-character delimiter within 10 bytes Default value: * A tab character in text format * A comma (,) in CSV format * No delimiter in FIXED format * NULL Specifies the string that represents a null value. Value range: * A null value cannot be **\r** or **\n**. The maximum length is 100 characters. * A null value cannot be the same as the **delimiter** or **quote** value. Default value: * The default value for the CSV format is an empty string without quotation marks. * The default value for the TEXT format is **\N**. * HEADER Specifies whether a file contains a header with the names of each column in the file. **header** is available only for CSV and FIXED files. When data is imported, if **header** is **on**, the first row of the data file will be identified as the header and ignored. If **header** is **off**, the first row will be identified as a data row. When data is exported, if header is **on**, **fileheader** must be specified. If **header** is **off**, an exported file does not contain a header. Value range: **true**, **on**, **false**, and **off**. Default value: **false** * QUOTE Specifies a quoted character string for a CSV file. Default value: single quotation marks ('') > \[!NOTE]NOTE > > * The value of **quote** cannot be the same as that of the **delimiter** or **null** parameter. > * The value of **quote** must be a single-byte character. > * You are advised to set **quote** to an invisible character, such as **0x07**, **0x08**, or **0x1b**. * ESCAPE Specifies an escape character for a CSV file. The value must be a single-byte character. Default value: single quotation marks ('') If the value is the same as that of **quote**, it will be replaced by **\0**. * EOL 'newline\_character' Specifies the newline character style of the imported or exported data file. Value range: multi-character newline characters within 10 bytes. Common newline characters include **\r** (0x0D), **\n** (0x0A), and **\r\n**(0x0D0A). Special newline characters include **$** and **#**. > \[!NOTE]NOTE > > * The **EOL** parameter supports only the TEXT format for data import and export and does not support the CSV or FIXED format for data import. For forward compatibility, the EOL parameter can be set to **0x0D** or **0x0D0A** for data export in the CSV or FIXED format. > * The value of **EOL** cannot be the same as that of the **delimiter** or **null** parameter. > * The EOL parameter value cannot contain the following characters: .abcdefghijklmnopqrstuvwxyz0123456789. * FORCE\_QUOTE { ( column\_name \[, ...] ) | \* } In **CSV COPY TO** mode, forces quotation marks to be used for all non-null values in each specified column. Null values are not quoted. Value range: an existing column name * FORCE\_NOT\_NULL ( column\_name \[, ...] ) The column specified by this function will not match (recognize) the input as a NULL string. NULL value strings will be defaulted to empty strings (that is, zero-length strings), even if they are not enclosed in quotation marks. This option can be used only in the COPY FROM statement and only when the CSV format is specified. Value range: an existing column name * ENCODING Specifies the encoding of data files. If this option is omitted, the current client encoding is used. * IGNORE\_EXTRA\_DATA Specifies whether to ignore excessive columns when the number of data source files exceeds the number of foreign table columns. This parameter is used only during data import. Value range: **true**, **on**, **false**, and **off**. * If this parameter is set to **true** or **on** and the number of source data files exceeds the number of foreign table columns, excessive columns will be ignored. * When the parameter is **false** or **off**, and the number of data source files is more than the number of foreign table columns, the following error information will be displayed: ``` extra data after last expected column ``` Default value: **false** > \[!TIP]NOTICE > If a newline character at the end of a row is missing and the row and another row are integrated into one, data in another row is ignored after the parameter is set to **true**. * COMPATIBLE\_ILLEGAL\_CHARS Specifies whether to tolerate invalid characters during data import. The parameter is valid only for data import using **COPY FROM**. Value range: **true**, **on**, **false**, and **off**. * If this parameter is set to **true** or **on**, invalid characters are tolerated and imported to the database after conversion. * If this parameter is set to **false** or **off** and an error occurs when there are invalid characters, the import will be interrupted. Default value: **false** or **off** > \[!NOTE]NOTE > The rules for converting invalid characters are as follows: > > 1. **\0** is converted to a space. > 2. Other invalid characters are converted to question marks. > (3) If **compatible\_illegal\_chars** is set to **true** or **on**, invalid characters are tolerated. If **NULL**, **DELIMITER**, **QUOTE**, and **ESCAPE** are set to a spaces or question marks, errors like "illegal chars conversion may confuse COPY escape 0x20" will be displayed to prompt users to change parameter values that cause confusion, preventing import errors. * FILL\_MISSING\_FIELDS Specifies how to handle the problem that the last column of a row in a source data file is lost during data import. Value range: **true**, **on**, **false**, and **off**. Default value: **false** or **off** * DATE\_FORMAT Specifies the DATE format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid DATE value For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). > \[!NOTE]NOTE > You can use the **TIMESTAMP\_FORMAT** parameter to set the DATE format to **TIMESTAMP** for data import. For details, see **TIMESTAMP\_FORMAT** below. * TIME\_FORMAT Specifies the TIME format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid TIME value. Time zones cannot be used. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * TIMESTAMP\_FORMAT Specifies the TIMESTAMP format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid TIMESTAMP value. Time zones cannot be used. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * SMALLDATETIME\_FORMAT Specifies the SMALLDATETIME format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid SMALLDATETIME value. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * **COPY\_OPTION { option\_name ' value ' }** Specifies all types of native parameters of **COPY**. * NULL null\_string Specifies the string that represents a null value. > \[!TIP]NOTICE > When using **COPY FROM**, any data item that matches this string will be stored as a null value, so make sure that you use the same string as you used with **COPY TO**. Value range: * A null value cannot be **\r** or **\n**. The maximum length is 100 characters. * A null value cannot be the same as the **delimiter** or **quote** value. Default value: * The default value for the TEXT format is **\N**. * The default value for the CSV format is an empty string without quotation marks. * HEADER Specifies whether a file contains a header with the names of each column in the file. **header** is available only for CSV and FIXED files. When data is imported, if **header** is **on**, the first row of the data file will be identified as the header and ignored. If **header** is **off**, the first row will be identified as a data row. When data is exported, if header is **on**, **fileheader** must be specified. If **header** is **off**, an exported file does not contain a header. * FILEHEADER Specifies a file that defines the content in the header for exported data. The file contains data description of each column. > \[!TIP]NOTICE > > * This parameter is available only when **header** is **on** or **true**. > * **fileheader** specifies an absolute path. > * The file can contain only one row of header information, and ends with a newline character. Excess rows will be discarded. (Header information cannot contain newline characters.) > * The length of the file including the newline character cannot exceed 1 MB. * FREEZE Sets the **COPY** loaded data row as **frozen**, like these data have executed **VACUUM FREEZE**. This is a performance option of initial data loading. The data will be frozen only when the following three requirements are met: * The table being loaded has been created or truncated in the same transaction before copying. * There are no cursors open in the current transaction. * There are no original snapshots in the current transaction. > \[!NOTE]NOTE > When **COPY** is completed, all the other sessions will see the data immediately. However, this violates the general principle of MVCC visibility, and users should understand that this may cause potential risks. * FORCE NOT NULL column\_name \[, ...] In **CSV COPY FROM** mode, the specified column is not null. If the column is null, its value is regarded as a string of 0 characters. Value range: an existing column name * FORCE QUOTE { column\_name \[, ...] | \* } In **CSV COPY TO** mode, forces quotation marks to be used for all non-null values in each specified column. Null values are not quoted. Value range: an existing column name * BINARY Specifies that data is stored and read in binary mode instead of text mode. In binary mode, you cannot declare **DELIMITER**, **NULL**, or **CSV**. When **BINARY** is specified, **CSV**, **FIXED**, and **TEXT** cannot be specified through **option** or **copy\_option**. * CSV Enables the CSV mode. When **CSV** is specified, **BINARY**, **FIXED**, and **TEXT** cannot be specified through **option** or **copy\_option**. * QUOTE \[AS] 'quote\_character' Specifies a quoted character string for a CSV file. Default value: single quotation marks ('') > \[!NOTE]NOTE > > * The value of **quote** cannot be the same as that of the **delimiter** or **null** parameter. > * The value of **quote** must be a single-byte character. > * You are advised to set **quote** to an invisible character, such as **0x07**, **0x08**, or **0x1b**. * ESCAPE \[AS] 'escape\_character' Specifies an escape character for a CSV file. The value must be a single-byte character. The default value is single quotation marks (''). If the value is the same as that of **quote**, it will be replaced by **\0**. * EOL 'newline\_character' Specifies the newline character style of the imported or exported data file. Value range: multi-character newline characters within 10 bytes. Common newline characters include **\r** (0x0D), **\n** (0x0A), and **\r\n** (0x0D0A). Special newline characters include **$** and **#**. > \[!NOTE]NOTE > > * The **EOL** parameter supports only the TEXT format for data import and export and does not support the CSV or FIXED format. For forward compatibility, the **EOL** parameter can be set to **0x0D** or **0x0D0A** for data export in the CSV or FIXED format. > * The value of **EOL** cannot be the same as that of the **delimiter** or **null** parameter. > * The EOL parameter value cannot contain the following characters: .abcdefghijklmnopqrstuvwxyz0123456789. * ENCODING 'encoding\_name' Specifies the name of a file encoding format. Value range: a valid encoding format Default value: current encoding format * IGNORE\_EXTRA\_DATA Specifies that when the number of data source files exceeds the number of foreign table columns, excess columns at the end of the row are ignored. This parameter is used only during data import. If this parameter is not used and the number of columns in the data source file is greater than that defined in the foreign table, the following error information is displayed: ``` extra data after last expected column ``` * COMPATIBLE\_ILLEGAL\_CHARS Specifies that invalid characters are tolerated during data import. Invalid characters are converted and then imported to the database. No error is reported and the import is not interrupted. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. If this parameter is not used, an error is reported when invalid characters are encountered during the import, and the import is interrupted. > \[!NOTE]NOTE > The rules for converting invalid characters are as follows: > > 1. **\0** is converted to a space. > 2. Other invalid characters are converted to question marks. > 3. When **compatible\_illegal\_chars** is set to **true** or **on**, after invalid characters such as **NULL**, **DELIMITER**, **QUOTE**, and **ESCAPE** are converted to spaces or question marks, an error message like "illegal chars conversion may confuse COPY escape 0x20" will be displayed to remind you of possible parameter confusion caused by the conversion. * FILL\_MISSING\_FIELDS Specifies how to handle the problem that the last column of a row in a source data file is lost during data import. Value range: **true**, **on**, **false**, and **off**. Default value: **false** or **off** > \[!TIP]NOTICE > Do not specify this option. Currently, it does not enable error tolerance, but will make the parser ignore the said errors during data parsing on the primary node of the database. Such errors will not be recorded in the COPY error table (enabled using **LOG ERRORS REJECT LIMIT**) but will be reported later by the database node. Therefore, do not specify this option. * DATE\_FORMAT 'date\_format\_string' Specifies the DATE format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid DATE value For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). > \[!NOTE]NOTE > You can use the **TIMESTAMP\_FORMAT** parameter to set the DATE format to **TIMESTAMP** for data import. For details, see **TIMESTAMP\_FORMAT** below. * TIME\_FORMAT 'time\_format\_string' Specifies the TIME format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid TIME value. Time zones cannot be used. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * TIMESTAMP\_FORMAT 'timestamp\_format\_string' Specifies the TIMESTAMP format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid TIMESTAMP value. Time zones cannot be used. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * SMALLDATETIME\_FORMAT 'smalldatetime\_format\_string' Specifies the SMALLDATETIME format for data import. The BINARY format is not supported. When data of such format is imported, error "cannot specify bulkload compatibility options in BINARY mode" will occur. The parameter is valid only for data import using **COPY FROM**. Value range: a valid SMALLDATETIME value. For details, see [Date and Time Processing Functions and Operators](date_and_time_processing_functions_and_operators.md). * TRANSFORM ( { column\_name \[ data\_type ] \[ AS transform\_expr ] } \[, ...] ) Specify the conversion expression of each column in the table. **data\_type** specifies the data type of the column in the expression parameter. **transform\_expr** is the target expression that returns the result value whose data type is the same as that of the target column in the table. For details about the expression, see [Expressions](simple_expressions.md). The following special backslash sequences are recognized by **COPY FROM**: * **\b**: Backslash (ASCII 8) * **\f**: Form feed (ASCII 12) * **\n**: Newline character (ASCII 10) * **\r**: Carriage return character (ASCII 13) * **\t**: Tab (ASCII 9) * **\v**: Vertical tab (ASCII 11) * **\digits**: Backslash followed by one to three octal digits specifies that the ASCII value is the character with that numeric code. * **\xdigits**: Backslash followed by an x and one or two hex digits specifies the character with that numeric code. ## Examples ``` -- Copy data from the tpcds.ship_mode file to the /home/omm/ds_ship_mode.dat file: openGauss=# COPY tpcds.ship_mode TO '/home/omm/ds_ship_mode.dat'; -- Output tpcds.ship_mode to stdout. openGauss=# COPY tpcds.ship_mode TO stdout; -- Create the tpcds.ship_mode_t1 table. openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; -- Copy data from stdin to the tpcds.ship_mode_t1 table. openGauss=# COPY tpcds.ship_mode_t1 FROM stdin; -- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table. openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat'; -- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table, convert the data using the TRANSFORM expression, and insert the 10 characters on the left of the SM_TYPE column into the table. openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' TRANSFORM (SM_TYPE AS LEFT(SM_TYPE, 10)); -- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table, with the import format set to TEXT (format 'text'), the delimiter set to \t' (delimiter E'\t'), excessive columns ignored (ignore_extra_data 'true'), and characters not escaped (noescaping 'true'). openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' WITH(format 'text', delimiter E'\t', ignore_extra_data 'true', noescaping 'true'); -- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table, with the import format set to FIXED, fixed-length format specified (FORMATTER(SM_SHIP_MODE_SK(0, 2), SM_SHIP_MODE_ID(2,16), SM_TYPE(18,30), SM_CODE(50,10), SM_CARRIER(61,20), SM_CONTRACT(82,20))), excessive columns ignored (ignore_extra_data), and headers included (header). openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' FIXED FORMATTER(SM_SHIP_MODE_SK(0, 2), SM_SHIP_MODE_ID(2,16), SM_TYPE(18,30), SM_CODE(50,10), SM_CARRIER(61,20), SM_CONTRACT(82,20)) header ignore_extra_data; -- Delete the tpcds.ship_mode_t1 table. openGauss=# DROP TABLE tpcds.ship_mode_t1; ``` --- --- url: /zh/docs/latest-lite/sql_reference/copy.md --- # COPY ## 功能描述 通过COPY命令实现在表和文件之间拷贝数据。 COPY FROM从一个文件拷贝数据到一个表,COPY TO把一个表的数据拷贝到一个文件。 ## 注意事项 * 当参数enable\_copy\_server\_files关闭时,只允许初始用户执行COPY FROM FILENAME或COPY TO FILENAME命令,当参数enable\_copy\_server\_files打开,允许具有SYSADMIN权限的用户或继承了内置角色gs\_role\_copy\_files权限的用户执行,但默认禁止对数据库配置文件,密钥文件,证书文件和审计日志执行COPY FROM FILENAME或COPY TO FILENAME,以防止用户越权查看或修改敏感文件。 * COPY只能用于表,不能用于视图。 * COPY TO需要读取的表的select权限,copy from需要插入的表的insert权限。 * 如果声明了一个字段列表,COPY将只在文件和表之间拷贝已声明字段的数据。如果表中有任何不在字段列表里的字段,COPY FROM将为那些字段插入缺省值。 * 如果声明了数据源文件,服务器必须可以访问该文件;如果指定了STDIN,数据将在客户前端和服务器之间流动,输入时,表的列与列之间使用TAB键分隔,在新的一行中以反斜杠和句点(\\.)表示输入结束。 * 如果数据文件的任意行包含比预期多或者少的字段,COPY FROM将抛出一个错误。 * 数据的结束可以用一个只包含反斜杠和句点(\\.)的行表示。如果从文件中读取数据,数据结束的标记是不必要的;如果在客户端应用之间拷贝数据,必须要有结束标记。 * COPY FROM中\N为空字符串,如果要输入实际数据值\N ,使用\\\N。 * COPY FROM不支持在导入过程中对数据做预处理(比如说表达式运算,填充指定默认值等)。如果需要在导入过程中对数据做预处理,用户需先把数据导入到临时表中,然后执行SQL语句通过运算插入到表中,但此方法会导致I/O膨胀,降低导入性能。 * COPY FROM在遇到数据格式错误时会回滚事务,但没有足够的错误信息,不方便用户从大量的原始数据中定位错误数据。 * COPY FROM/TO适合低并发,本地小数据量导入导出。 * 目标表存在trigger,支持COPY操作。 * COPY命令中,生成列不能出现在指定列的列表中。使用COPY… TO导出数据时,如果没有指定列的列表,则该表的所有列除了生成列都会被导出。COPY… FROM导入数据时,生成列会自动更新,并像普通列一样保存。 ## 语法格式 * 从一个文件复制数据到一个表。 ``` COPY table_name [ ( column_name [, ...] ) ] FROM { 'filename' | STDIN } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ LOG ERRORS ] [ LOG ERRORS DATA ] [ REJECT LIMIT 'limit' ] [ [ WITH ] ( option [, ...] ) | ( copy_option [, ...] ) | [ TRANSFORM ( { column_name [ data_type ] [ AS transform_expr ] } [, ...] ) ] | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ] ] ``` > \[!NOTE]说明 > > * 上述语法中fixed formatter与copy\_option语法兼容、与option语法不兼容;copy\_option与option语法不兼容;transform与copy\_option、fixed formatter语法兼容。 * 把一个表的数据拷贝到一个文件。 ``` COPY table_name [ ( column_name [, ...] ) ] TO { 'filename' | STDOUT } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; COPY query TO { 'filename' | STDOUT } [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; ``` > \[!NOTE]说明 > > 1. COPY TO语法形式约束如下: > (query)与\[USING] DELIMITER不兼容,即若COPY TO的数据来自于一个query的查询结果,那么COPY TO语法不能再指定\[USING] DELIMITERS语法子句。 > 2. 对于FIXED FORMATTTER语法后面跟随的copy\_option是以空格进行分隔的。 > 3. copy\_option是指COPY原生的参数形式,而option是兼容外表导入的参数形式。 > 4. 语法中的FIXED FORMATTER ( { column\_name( offset, length ) } \[, ...] )以及 \[ ( option \[, ...] ) | copy\_option \[ ...] ] 可以任意排列组合。 其中可选参数option子句语法为: ``` FORMAT format_name | OIDS [ boolean ] | DELIMITER 'delimiter_character' | NULL 'null_string' | HEADER [ boolean ] | FILEHEADER 'header_file_string' | FREEZE [ boolean ] | QUOTE 'quote_character' | ESCAPE 'escape_character' | EOL 'newline_character' | NOESCAPING [ boolean ] | FORCE_QUOTE { ( column_name [, ...] ) | * } | FORCE_NOT_NULL ( column_name [, ...] ) | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA [ boolean ] | FILL_MISSING_FIELDS [ boolean ] | COMPATIBLE_ILLEGAL_CHARS [ boolean ] | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` 其中可选参数copy\_option子句语法为: ``` OIDS | NULL 'null_string' | HEADER | FILEHEADER 'header_file_string' | FREEZE | FORCE NOT NULL column_name [, ...] | FORCE QUOTE { column_name [, ...] | * } | BINARY | CSV | QUOTE [ AS ] 'quote_character' | ESCAPE [ AS ] 'escape_character' | EOL 'newline_character' | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA | FILL_MISSING_FIELDS | COMPATIBLE_ILLEGAL_CHARS | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` ## 参数说明 * **query** 其结果将被拷贝。 取值范围:一个必须用圆括弧包围的SELECT或VALUES命令。 * **table\_name** 表的名称(可以有模式修饰)。 取值范围:已存在的表名。 * **column\_name** 可选的待拷贝字段列表。 取值范围:如果没有声明字段列表,将使用所有字段。 * **STDIN** 声明输入是来自标准输入。 * **STDOUT** 声明输出打印到标准输出。 * **FIXED** 打开字段固定长度模式。在字段固定长度模式下,不能声明DELIMITER,NULL,CSV选项。指定FIXED类型后,不能再通过option或copy\_option指定BINARY、CSV、TEXT等类型。 > \[!NOTE]说明 > > 定长格式定义如下: > > 1. 每条记录的每个字段长度相同。 > 2. 长度不足的字段以空格填充,数字类型字段左对齐,字符字段右对齐。 > 3. 字段和字段之间没有分隔符。 * **\[USING] DELIMITER 'delimiters'** 在文件中分隔各个字段的字符串,分隔符最大长度不超过10个字节。 取值范围:不允许包含\\.abcdefghijklmnopqrstuvwxyz0123456789中的任何一个字符。 缺省值:在文本模式下,缺省是水平制表符,在CSV模式下是一个逗号。 * **WITHOUT ESCAPING** 在TEXT格式中,不对'\\'和后面的字符进行转义。 取值范围:仅支持TEXT格式。 * **LOG ERRORS** 若指定,则开启对于COPY FROM语句中数据类型错误的容错机制。 取值范围:仅支持导入(即COPY FROM)时指定。 > \[!NOTE]说明 > > 此容错选项的使用限制如下: > > * 此容错机制仅捕捉COPY FROM过程中数据库主节点上数据解析过程中相关的数据类型错误(DATA\_EXCEPTION)。 > * COPY已有的容错选项(如IGNORE\_EXTRA\_DATA)开启时,对应类型的错误会按照已有的方式处理而不会报出异常,因此错误表也不会有相应数据。 * **LOG ERRORS DATA** LOG ERRORS DATA和LOG ERRORS的区别: 1. LOG ERRORS DATA会填充容错表的rawrecord字段。 2. 只有supper权限的用户才能使用LOG ERRORS DATA参数选项。 > \[!WARNING]注意 > > 使用\*\*“LOG ERRORS DATA”\*\*时,若错误内容过于复杂可能存在写入容错表失败的风险,导致任务失败。 * **REJECT LIMIT**'**limit'** 与LOG ERROR选项共同使用,对COPY FROM的容错机制设置数值上限,一旦此COPY FROM语句错误数据超过选项指定条数,则会按照原有机制报错。 取值范围:正整数(1-INTMAX),'unlimited'(无最大值限制) 缺省值:若未指定LOG ERRORS,则会报错;若指定LOG ERRORS,则默认为0。 > \[!NOTE]说明 > > 如上述LOG ERRORS中描述的容错机制,REJECT LIMIT的计数也是按照执行COPY FROM的数据库主节点上遇到的解析错误数量计算,而不是数据库节点的错误数量。 * **FORMATTER** 在固定长度模式中,定义每一个字段在数据文件中的位置。按照column(offset,length)格式定义每一列在数据文件中的位置。 取值范围: * offset取值不能小于0,以字节为单位。 * length取值不能小于0,以字节为单位。 所有列的总长度和不能大于1GB。 文件中没有出现的列默认以空值代替。 * **OPTION { option\_name ' value ' }** 用于指定兼容外表的各类参数。 * FORMAT 数据源文件的格式。 取值范围:CSV、TEXT、FIXED、BINARY。 * CSV格式的文件,可以有效处理数据列中的换行符,但对一些特殊字符处理有欠缺。 * TEXT格式的文件,可以有效处理一些特殊字符,但无法正确处理数据列中的换行符。 * FIXED格式的文件,适用于每条数据的数据列都比较固定的数据,长度不足的列会添加空格补齐,过长的列则会自动截断。 * BINARY形式的选项会使得所有的数据被存储/读作二进制格式而不是文本。 这比TEXT和CSV格式的要快一些,但是一个BINARY格式文件可移植性比较差。 缺省值:TEXT * DELIMITER 指定数据文件行数据的字段分隔符。 > \[!NOTE]说明 > > * 分隔符不能是\r和\n。 > * 分隔符不能和null参数相同,CSV格式数据的分隔符不能和quote参数相同。 > * TEXT格式数据的分隔符不能包含: 小写字母、数字和特殊字符.\。 > * 数据文件中单行数据长度需<1GB,如果分隔符较长且数据列较多的情况下,会影响导出有效数据的长度。 > * 分隔符推荐使用多字符和不可见字符。多字符例如'$^&';不可见字符例如0x07,0x08,0x1b等。 取值范围:支持多字符分隔符,但分隔符不能超过10个字节。 缺省值: * TEXT格式的默认分隔符是水平制表符(tab)。 * CSV格式的默认分隔符为“,”。 * FIXED格式没有分隔符。 * NULL 用来指定数据文件中空值的表示。 取值范围: * null值不能是\r和\n,最大为100个字符。 * null值不能和分隔符、quote参数相同。 缺省值: * CSV格式下默认值是一个没有引号的空字符串。 * 在TEXT格式下默认值是\N。 * HEADER 指定导出数据文件是否包含标题行,标题行一般用来描述表中每个字段的信息。header只能用于CSV,FIXED格式的文件中。 在导入数据时,如果header选项为on,则数据文本第一行会被识别为标题行,会忽略此行。如果header为off,而数据文件中第一行会被识别为数据。 在导出数据时,如果header选项为on,且未指定fileheader,则将把表的列名信息导出到文件的第一行;如果指定了fileheader,则将把fileheader文件的第一行导出到最终输出文件的第一行。如果header为off,则导出数据文件不包含标题行。 取值范围:true/on,false/off。 缺省值:false * QUOTE CSV格式文件下的引号字符。 缺省值:双引号 > \[!NOTE]说明 > > * quote参数不能和分隔符、null参数相同。 > * quote参数只能是单字节的字符。 > * 推荐不可见字符作为quote,例如0x07,0x08,0x1b等。 * ESCAPE CSV格式下,用来指定逃逸字符,逃逸字符只能指定为单字节字符。 缺省值:双引号。当与quote值相同时,会被替换为'\0'。 * EOL 'newline\_character' 指定导入导出数据文件换行符样式。 取值范围:支持多字符换行符,但换行符不能超过10个字节。常见的换行符,如\r、\n、\r\n(设成0x0D、0x0A、0x0D0A效果是相同的),其他字符或字符串,如$、#。 > \[!NOTE]说明 > > * EOL参数只能用于TEXT格式的导入导出,不支持CSV格式和FIXED格式导入。为了兼容原有EOL参数,仍然支持导出CSV格式和FIXED格式时指定EOL参数为0x0D或0x0D0A。 > * EOL参数不能和分隔符、null参数相同。 > * EOL参数不能包含:.abcdefghijklmnopqrstuvwxyz0123456789。 * FORCE\_QUOTE { ( column\_name \[, ...] ) | \* } 在CSV COPY TO模式下,强制在每个声明的字段周围对所有非NULL值都使用引号包围。NULL输出不会被引号包围。 取值范围:已存在的字段。 * FORCE\_NOT\_NULL ( column\_name \[, ...] ) 在CSV COPY FROM模式下,指定的字段输入不能为空。 取值范围:已存在的字段。 * ENCODING 指定数据文件的编码格式名称,缺省为当前数据库编码格式。 * IGNORE\_EXTRA\_DATA 若数据源文件比外表定义列数多,是否会忽略对多出的列。该参数只在数据导入过程中使用。 取值范围:true/on、false/off。 * 参数为true/on,若数据源文件比外表定义列数多,则忽略行尾多出来的列。 * 参数为false/off,若数据源文件比外表定义列数多,会显示如下错误信息。 ``` extra data after last expected column ``` 缺省值:false。 > \[!TIP]须知 > > 如果行尾换行符丢失,使两行变成一行时,设置此参数为true将导致后一行数据被忽略掉。 * COMPATIBLE\_ILLEGAL\_CHARS 导入非法字符容错参数。此语法仅对COPY FROM导入有效。 取值范围:true/on,false/off。 * 参数为true/on,则导入时遇到非法字符进行容错处理,非法字符转换后入库,不报错,不中断导入。 * 参数为false/off,导入时遇到非法字符进行报错,中断导入。 缺省值:false/off > \[!NOTE]说明 > > 导入非法字符容错规则如下: > (1)对于'\0',容错后转换为空格; > (2)对于其他非法字符,容错后转换为问号; > (3)若compatible\_illegal\_chars为true/on标识导入时对于非法字符进行容错处理,则若NULL、DELIMITER、QUOTE、ESCAPE设置为空格或问号则会通过如"illegal chars conversion may confuse COPY escape 0x20"等报错信息提示用户修改可能引起混淆的参数以避免导入错误。 * FILL\_MISSING\_FIELDS 当数据加载时,若数据源文件中一行的最后一个字段缺失的处理方式。 取值范围:true/on,false/off。 缺省值:false/off * DATE\_FORMAT 导入对于DATE类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法DATE格式。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 > \[!NOTE]说明 > > 对于DATE类型内建为TIMESTAMP类型的数据库,在导入的时候,若需指定格式,可以参考下面的timestamp\_format参数。 * TIME\_FORMAT 导入对于TIME类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法TIME格式,不支持时区。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * TIMESTAMP\_FORMAT 导入对于TIMESTAMP类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法TIMESTAMP格式,不支持时区。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * SMALLDATETIME\_FORMAT 导入对于SMALLDATETIME类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法SMALLDATETIME格式。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * **COPY\_OPTION { option\_name ' value ' }** 用于指定COPY原生的各类参数。 * NULL null\_string 用来指定数据文件中空值的表示。 > \[!TIP]须知 > > 在使用COPY FROM的时候,任何匹配这个字符串的字符串将被存储为NULL值,所以应该确保指定的字符串和COPY TO相同。 取值范围: * null值不能是\r和\n,最大为100个字符。 * null值不能和分隔符、quote参数相同。 缺省值: * 在TEXT格式下默认值是\N。 * CSV格式下默认值是一个没有引号的空字符串。 * HEADER 指定导出数据文件是否包含标题行,标题行一般用来描述表中每个字段的信息。header只能用于CSV,FIXED格式的文件中。 在导入数据时,如果header选项为on,则数据文本第一行会被识别为标题行,会忽略此行。如果header为off,而数据文件中第一行会被识别为数据。 在导出数据时,如果header选项为on,且未指定fileheader,则将把表的列名信息导出到文件的第一行;如果指定了fileheader,则将把fileheader文件的第一行导出到最终输出文件的第一行。如果header为off,则导出数据文件不包含标题行。 * FILEHEADER 导出数据时用于定义标题行的文件,一般用来描述每一列的数据信息。 > \[!TIP]须知 > > * 仅在header为on或true的情况下有效。 > * fileheader指定的是绝对路径。 > * 该文件只能包含一行标题信息,并以换行符结尾,多余的行将被丢弃(标题信息不能包含换行符)。 > * 该文件包括换行符在内长度不超过1M。 * FREEZE 将COPY加载的数据行设置为已经被frozen,就像这些数据行执行过VACUUM FREEZE。 这是一个初始数据加载的性能选项。仅当以下三个条件同时满足时,数据行会被frozen: * 在同一事务中create或truncate这张表之后执行COPY。 * 当前事务中没有打开的游标。 * 当前事务中没有原有的快照。 > \[!NOTE]说明 > > * COPY完成后,所有其他会话将会立刻看到这些数据。但是这违反了MVCC可见性的一般原则,用户应当了解这样会导致潜在的风险。 > * 当条件不满足时,FREEZE 选项将会被忽略而不会报错。 * FORCE NOT NULL column\_name \[, ...] 在CSV COPY FROM模式下,指定的字段不为空。若输入为空,则将视为长度为0的字符串。 取值范围:已存在的字段。 * FORCE NULL column\_name \[, ...] 在CSV COPY FROM模式下,将指定的字段表示空值的字符串设置为NULL,包括加了引号的空值字符串。 取值范围:已存在的字段。 * FORCE QUOTE { column\_name \[, ...] | \* } 在CSV COPY TO模式下,强制在每个声明的字段周围对所有非NULL值都使用引号包围。NULL输出不会被引号包围。 取值范围:已存在的字段。 * BINARY 使用二进制格式存储和读取,而不是以文本的方式。在二进制模式下,不能声明DELIMITER,NULL,CSV选项。指定BINARY类型后,不能再通过option或copy\_option指定CSV、FIXED、TEXT等类型。 * CSV 打开逗号分隔变量(CSV)模式。指定CSV类型后,不能再通过option或copy\_option指定BINARY、FIXED、TEXT等类型。 * QUOTE \[AS] 'quote\_character' CSV格式文件下的引号字符。 缺省值:双引号。 > \[!NOTE]说明 > > * quote参数不能和分隔符、null参数相同。 > * quote参数只能是单字节的字符。 > * 推荐不可见字符作为quote,例如0x07,0x08,0x1b等。 * ESCAPE \[AS] 'escape\_character' CSV格式下,用来指定逃逸字符,逃逸字符只能指定为单字节字符。 默认值为双引号。当与quote值相同时,会被替换为'\0'。 * EOL 'newline\_character' 指定导入导出数据文件换行符样式。 取值范围:支持多字符换行符,但换行符不能超过10个字节。常见的换行符,如\r、\n、\r\n(设成0x0D、0x0A、0x0D0A效果是相同的),其他字符或字符串,如$、#。 > \[!NOTE]说明 > > * EOL参数只能用于TEXT格式的导入导出,不支持CSV格式和FIXED格式。为了兼容原有EOL参数,仍然支持导出CSV格式和FIXED格式时指定EOL参数为0x0D或0x0D0A。 > * EOL参数不能和分隔符、null参数相同。 > * EOL参数不能包含:.abcdefghijklmnopqrstuvwxyz0123456789。 * ENCODING 'encoding\_name' 指定文件编码格式名称。 取值范围:有效的编码格式。 缺省值:当前编码格式。 * IGNORE\_EXTRA\_DATA 指定当数据源文件比外表定义列数多时,忽略行尾多出来的列。该参数只在数据导入过程中使用。 若不使用该参数,在数据源文件比外表定义列数多,会显示如下错误信息。 ``` extra data after last expected column ``` * COMPATIBLE\_ILLEGAL\_CHARS 指定导入时对非法字符进行容错处理,非法字符转换后入库。不报错,不中断导入。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 若不使用该参数,导入时遇到非法字符进行报错,中断导入。 > \[!NOTE]说明 > > 导入非法字符容错规则如下: > (1)对于'\0',容错后转换为空格; > (2)对于其他非法字符,容错后转换为问号; > (3)若compatible\_illegal\_chars为true/on标识,导入时对于非法字符进行容错处理,则若NULL、DELIMITER、QUOTE、ESCAPE设置为空格或问号则会通过如"illegal chars conversion may confuse COPY escape 0x20"等报错信息提示用户修改可能引起混淆的参数以避免导入错误。 * FILL\_MISSING\_FIELDS \[ { 'one' | 'multi' } ] 当数据加载时,若数据源文件中一行的最后部分字段缺失的处理方式。不指定one/multi或者指定one则最后一个字段缺失按默认方式处理,指定multi则最后多个字段缺失都按默认方式处理。 取值范围:true/on,false/off。 缺省值:false/off。 > \[!TIP]须知 > > 目前COPY指定此Option实际不会生效,即不会有相应的容错处理效果(不生效)。需要额外注意的是,打开此选项会导致解析器在数据库主节点数据解析阶段(即COPY错误表容错的涵盖范围)忽略此数据问题,而到数据库节点重新报错,从而使得COPY错误表(打开LOG ERRORS REJECT LIMIT)在此选项打开的情况下无法成功捕获这类少列的数据异常。因此请不要指定此选项。 * DATE\_FORMAT 'date\_format\_string' 导入对于DATE类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法DATE格式。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md) > \[!NOTE]说明 > > 对于DATE类型内建为TIMESTAMP类型的数据库,在导入的时候,若需指定格式,可以参考下面的timestamp\_format参数。 * TIME\_FORMAT 'time\_format\_string' 导入对于TIME类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法TIME格式,不支持时区。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * TIMESTAMP\_FORMAT 'timestamp\_format\_string' 导入对于TIMESTAMP类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法TIMESTAMP格式,不支持时区。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * SMALLDATETIME\_FORMAT 'smalldatetime\_format\_string' 导入对于SMALLDATETIME类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法SMALLDATETIME格式。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * TRANSFORM ( { column\_name \[ data\_type ] \[ AS transform\_expr ] } \[, ...] ) 指定表中各个列的转换表达式;其中data\_type指定该列在表达式参数中的数据类型;transform\_expr为目标表达式,返回与表中目标列数据类型一致的结果值,表达式可参考[表达式](simple_expression.md)。 * SKIP int\_number 指定数据导入时,跳过数据文件的前 int\_number行。 * WHEN { ( start - end ) | column\_name } { = | != } 'string' 数据导入时,检查导入的每一行数据,只有符合WHEN条件的数据行才导入表中。 * SEQUENCE ( { column\_name ( integer \[, incr] ) \[, ...] } ) 数据导入时,SEQUENCE修饰的列,不从数据文件读取数据,通过指定的integer,按照incr递增数值;不指定incr则默认从1开始递增。 * FILLER ( { column\_name \[, ...] } ) 数据导入时,FILLER修饰的列,从数据文件读取数据后丢弃。 > \[!NOTE]说明 > > 使用FILLER需要指定待拷贝字段列表,数据处理时根据filler列在字段列表中的位置进行处理。 * CONSTANT ( { column\_name 'constant\_string' \[, ...] } ) 数据导入时,CONSTANT修饰的列,不从数据文件读取数据,使用constant\_string对该列进行赋值。 COPY FROM能够识别的特殊反斜杠序列如下所示。 * **\b**:反斜杠 (ASCII 8) * **\f**:换页(ASCII 12) * **\n**:换行符 (ASCII 10) * **\r**:回车符 (ASCII 13) * **\t**:水平制表符 (ASCII 9) * **\v**:垂直制表符 (ASCII 11) * **\digits**:反斜杠后面跟着一到三个八进制数,表示ASCII值为该数的字符。 * **\xdigits**:反斜杠x后面跟着一个或两个十六进制位声明指定数值编码的字符。 ## 示例 ``` --将tpcds.ship_mode中的数据拷贝到/home/omm/ds_ship_mode.dat文件中。 openGauss=# COPY tpcds.ship_mode TO '/home/omm/ds_ship_mode.dat'; --将tpcds.ship_mode 输出到stdout。 openGauss=# COPY tpcds.ship_mode TO stdout; --创建tpcds.ship_mode_t1表。 openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; --从stdin拷贝数据到表tpcds.ship_mode_t1。 openGauss=# COPY tpcds.ship_mode_t1 FROM stdin; --从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1。 openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat'; --从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1,应用TRANSFORM表达式转换,取SM_TYPE列左边10个字符插入到表中。 openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' TRANSFORM (SM_TYPE AS LEFT(SM_TYPE, 10)); --从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1,使用参数如下:导入格式为TEXT(format 'text'),分隔符为'\t'(delimiter E'\t'),忽略多余列(ignore_extra_data 'true'),不指定转义(noescaping 'true')。 openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' WITH(format 'text', delimiter E'\t', ignore_extra_data 'true', noescaping 'true'); --从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1,使用参数如下:导入格式为FIXED(FIXED),指定定长格式(FORMATTER(SM_SHIP_MODE_SK(0, 2), SM_SHIP_MODE_ID(2,16), SM_TYPE(18,30), SM_CODE(50,10), SM_CARRIER(61,20), SM_CONTRACT(82,20))),忽略多余列(ignore_extra_data),有数据头(header)。 openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' FIXED FORMATTER(SM_SHIP_MODE_SK(0, 2), SM_SHIP_MODE_ID(2,16), SM_TYPE(18,30), SM_CODE(50,10), SM_CARRIER(61,20), SM_CONTRACT(82,20)) header ignore_extra_data; --删除tpcds.ship_mode_t1。 openGauss=# DROP TABLE tpcds.ship_mode_t1; ``` ## 相关链接 [PG\_STAT\_PROGRESS\_COPY](../database_reference/pg_stat_progress_copy.md) --- --- url: /zh/docs/latest/sql_reference/copy.md --- # COPY ## 功能描述 通过COPY命令实现在表和文件之间拷贝数据。 COPY FROM从一个文件拷贝数据到一个表,COPY TO把一个表的数据拷贝到一个文件。 ## 注意事项 * 当参数enable\_copy\_server\_files关闭时,只允许初始用户执行COPY FROM FILENAME或COPY TO FILENAME命令,当参数enable\_copy\_server\_files打开,允许具有SYSADMIN权限的用户或继承了内置角色gs\_role\_copy\_files权限的用户执行,但默认禁止对数据库配置文件、密钥文件、证书文件和审计日志执行COPY FROM FILENAME或COPY TO FILENAME,以防止用户越权查看或修改敏感文件。 * COPY只能用于表,不能用于视图。 * COPY TO需要读取的表的select权限,copy from需要插入的表的insert权限。 * 如果声明了一个字段列表,COPY将只在文件和表之间拷贝已声明字段的数据。如果表中有任何不在字段列表里的字段,COPY FROM将为那些字段插入缺省值。 * 如果声明了数据源文件,服务器必须可以访问该文件;如果指定了STDIN,数据将在客户前端和服务器之间流动,输入时,表的列与列之间使用TAB键分隔,在新的一行中以反斜杠和句点(\\.)表示输入结束。 * 如果数据文件的任意行包含比预期多或者少的字段,COPY FROM将抛出一个错误。 * 数据的结束可以用一个只包含反斜杠和句点(\\.)的行表示。如果从文件中读取数据,数据结束的标记是不必要的;如果在客户端应用之间拷贝数据,必须要有结束标记。 * COPY FROM中\N为空字符串,如果要输入实际数据值\N ,使用\\\N。 * COPY FROM不支持在导入过程中对数据做预处理(比如说表达式运算、填充指定默认值等)。如果需要在导入过程中对数据做预处理,用户需先把数据导入到临时表中,然后执行SQL语句通过运算插入到表中,但此方法会导致I/O膨胀,降低导入性能。 * COPY FROM在遇到数据格式错误时会回滚事务,但没有足够的错误信息,不方便用户从大量的原始数据中定位错误数据。 * COPY FROM/TO适合低并发,本地小数据量导入导出。 * 目标表存在trigger,支持COPY操作。 * COPY命令中,生成列不能出现在指定列的列表中。使用COPY… TO导出数据时,如果没有指定列的列表,则该表的所有列除了生成列都会被导出。COPY… FROM导入数据时,生成列会自动更新,并像普通列一样保存。 ## 语法格式 * 从一个文件复制数据到一个表。 ``` COPY table_name [ ( column_name [, ...] ) ] FROM { 'filename' | STDIN } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ LOG ERRORS ] [ LOG ERRORS DATA ] [ REJECT LIMIT 'limit' ] [ [ WITH ] ( option [, ...] ) | ( copy_option [, ...] ) | [ TRANSFORM ( { column_name [ data_type ] [ AS transform_expr ] } [, ...] ) ] | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ] ] ``` > \[!NOTE]说明 > > * 上述语法中fixed formatter与copy\_option语法兼容、与option语法不兼容;copy\_option与option语法不兼容;transform与copy\_option、fixed formatter语法兼容。 * 把一个表的数据拷贝到一个文件。 ``` COPY table_name [ ( column_name [, ...] ) ] TO { 'filename' | STDOUT } [ [ USING ] DELIMITERS 'delimiters' ] [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; COPY query TO { 'filename' | STDOUT } [ WITHOUT ESCAPING ] [ [ WITH ] ( option [, ...] ) ] | copy_option | [ FIXED FORMATTER ( { column_name( offset, length ) } [, ...] ) ]; ``` > \[!NOTE]说明 > > 1. COPY TO语法形式约束如下: > (query)与\[USING] DELIMITER不兼容,即若COPY TO的数据来自于一个query的查询结果,那么COPY TO语法不能再指定\[USING] DELIMITERS语法子句。 > 2. 对于FIXED FORMATTTER语法后面跟随的copy\_option是以空格进行分隔的。 > 3. copy\_option是指COPY原生的参数形式,而option是兼容外表导入的参数形式。 > 4. 语法中的FIXED FORMATTER ( { column\_name( offset, length ) } \[, ...] )以及 \[ ( option \[, ...] ) | copy\_option \[ ...] ] 可以任意排列组合。 其中可选参数option子句语法为: ``` FORMAT format_name | OIDS [ boolean ] | DELIMITER 'delimiter_character' | NULL 'null_string' | HEADER [ boolean ] | FILEHEADER 'header_file_string' | FREEZE [ boolean ] | QUOTE 'quote_character' | ESCAPE 'escape_character' | EOL 'newline_character' | NOESCAPING [ boolean ] | FORCE_QUOTE { ( column_name [, ...] ) | * } | FORCE_NOT_NULL ( column_name [, ...] ) | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA [ boolean ] | FILL_MISSING_FIELDS [ boolean ] | COMPATIBLE_ILLEGAL_CHARS [ boolean ] | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` 其中可选参数copy\_option子句语法为: ``` OIDS | NULL 'null_string' | HEADER | FILEHEADER 'header_file_string' | FREEZE | FORCE NOT NULL column_name [, ...] | FORCE QUOTE { column_name [, ...] | * } | BINARY | CSV | QUOTE [ AS ] 'quote_character' | ESCAPE [ AS ] 'escape_character' | EOL 'newline_character' | ENCODING 'encoding_name' | IGNORE_EXTRA_DATA | FILL_MISSING_FIELDS | COMPATIBLE_ILLEGAL_CHARS | DATE_FORMAT 'date_format_string' | TIME_FORMAT 'time_format_string' | TIMESTAMP_FORMAT 'timestamp_format_string' | SMALLDATETIME_FORMAT 'smalldatetime_format_string' ``` ## 参数说明 * **query** 其结果将被拷贝。 取值范围:一个必须用圆括弧包围的SELECT或VALUES命令。 * **table\_name** 表的名称(可以有模式修饰)。 取值范围:已存在的表名。 * **column\_name** 可选的待拷贝字段列表。 取值范围:如果没有声明字段列表,将使用所有字段。 * **STDIN** 声明输入是来自标准输入。 * **STDOUT** 声明输出打印到标准输出。 * **FIXED** 打开字段固定长度模式。在字段固定长度模式下,不能声明DELIMITER、NULL、CSV选项。指定FIXED类型后,不能再通过option或copy\_option指定BINARY、CSV、TEXT等类型。 > \[!NOTE]说明 > 定长格式定义如下: > > 1. 每条记录的每个字段长度相同。 > 2. 长度不足的字段以空格填充,数字类型字段左对齐,字符字段右对齐。 > 3. 字段和字段之间没有分隔符。 * **\[USING] DELIMITER 'delimiters'** 在文件中分隔各个字段的字符串,分隔符最大长度不超过10个字节。 取值范围:不允许包含\\.abcdefghijklmnopqrstuvwxyz0123456789中的任何一个字符。 缺省值:在文本模式下,缺省是水平制表符,在CSV模式下是一个逗号。 * **WITHOUT ESCAPING** 在TEXT格式中,不对'\\'和后面的字符进行转义。 取值范围:仅支持TEXT格式。 * **LOG ERRORS** 若指定,则开启对于COPY FROM语句中数据类型错误的容错机制。 取值范围:仅支持导入(即COPY FROM)时指定。 > \[!NOTE]说明 > > 此容错选项的使用限制如下: > > * 此容错机制仅捕捉COPY FROM过程中数据库主节点上数据解析过程中相关的数据类型错误(DATA\_EXCEPTION)。 > * COPY已有的容错选项(如IGNORE\_EXTRA\_DATA)开启时,对应类型的错误会按照已有的方式处理而不会报出异常,因此错误表也不会有相应数据。 * **LOG ERRORS DATA** LOG ERRORS DATA和LOG ERRORS的区别: 1. LOG ERRORS DATA会填充容错表的rawrecord字段。 2. 只有supper权限的用户才能使用LOG ERRORS DATA参数选项。 > \[!WARNING]注意 > 使用**LOG ERRORS DATA**时,若错误内容过于复杂可能存在写入容错表失败的风险,导致任务失败。 * **REJECT LIMIT** **'imit'** 与LOG ERROR选项共同使用,对COPY FROM的容错机制设置数值上限,一旦此COPY FROM语句错误数据超过选项指定条数,则会按照原有机制报错。 取值范围:正整数(1-INTMAX),'unlimited'(无最大值限制) 缺省值:若未指定LOG ERRORS,则会报错;若指定LOG ERRORS,则默认为0。 > \[!NOTE]说明 > 如上述LOG ERRORS中描述的容错机制,REJECT LIMIT的计数也是按照执行COPY FROM的数据库主节点上遇到的解析错误数量计算,而不是数据库节点的错误数量。 * **FORMATTER** 在固定长度模式中,定义每一个字段在数据文件中的位置。按照column(offset,length)格式定义每一列在数据文件中的位置。 取值范围: * offset取值不能小于0,以字节为单位。 * length取值不能小于0,以字节为单位。 所有列的总长度和不能大于1GB。 文件中没有出现的列默认以空值代替。 * **OPTION { option\_name ' value ' }** 用于指定兼容外表的各类参数。 * FORMAT 数据源文件的格式。 取值范围:CSV、TEXT、FIXED、BINARY。 * CSV格式的文件,可以有效处理数据列中的换行符,但对一些特殊字符处理有欠缺。 * TEXT格式的文件,可以有效处理一些特殊字符,但无法正确处理数据列中的换行符。 * FIXED格式的文件,适用于每条数据的数据列都比较固定的数据,长度不足的列会添加空格补齐,过长的列则会自动截断。 * BINARY形式的选项会使得所有的数据被存储/读作二进制格式而不是文本。 这比TEXT和CSV格式的要快一些,但是一个BINARY格式文件可移植性比较差。 缺省值:TEXT * DELIMITER 指定数据文件行数据的字段分隔符。 > \[!NOTE]说明 > > * 分隔符不能是\r和\n。 > > * 分隔符不能和null参数相同,CSV格式数据的分隔符不能和quote参数相同。 > > * TEXT格式数据的分隔符不能包含:小写字母、数字和特殊字符.\。 > > * 数据文件中单行数据长度需<1GB,如果分隔符较长且数据列较多的情况下,会影响导出有效数据的长度。 > > * 分隔符推荐使用多字符和不可见字符。多字符例如'$^&';不可见字符例如0x07、0x08、0x1b等。 取值范围:支持多字符分隔符,但分隔符不能超过10个字节。 缺省值: * TEXT格式的默认分隔符是水平制表符(tab)。 * CSV格式的默认分隔符为“,”。 * FIXED格式没有分隔符。 * NULL 用来指定数据文件中空值的表示。 取值范围: * null值不能是\r和\n,最大为100个字符。 * null值不能和分隔符、quote参数相同。 缺省值: * CSV格式下默认值是一个没有引号的空字符串。 * 在TEXT格式下默认值是\N。 * HEADER 指定导出数据文件是否包含标题行,标题行一般用来描述表中每个字段的信息。header只能用于CSV、FIXED格式的文件中。 在导入数据时,如果header选项为on,则数据文本第一行会被识别为标题行,会忽略此行。如果header为off,而数据文件中第一行会被识别为数据。 在导出数据时,如果header选项为on,且未指定fileheader,则将把表的列名信息导出到文件的第一行;如果指定了fileheader,则将把fileheader文件的第一行导出到最终输出文件的第一行。如果header为off,则导出数据文件不包含标题行。 取值范围:true/on、false/off。 缺省值:false * QUOTE CSV格式文件下的引号字符。 缺省值:双引号 > \[!NOTE]说明 > > * quote参数不能和分隔符、null参数相同。 > * quote参数只能是单字节的字符。 > * 推荐不可见字符作为quote,例如0x07、0x08、0x1b等。 > 例如quote e'\x22' :使用ASCII编码为16进制22的字符。 * ESCAPE CSV格式下,用来指定逃逸字符,逃逸字符只能指定为单字节字符。 缺省值:双引号。当与quote值相同时,会被替换为'\0'。 * EOL 'newline\_character' 指定导入导出数据文件换行符样式。 取值范围:支持多字符换行符,但换行符不能超过10个字节。常见的换行符,如\r、\n、\r\n(设成0x0D、0x0A、0x0D0A效果是相同的),其他字符或字符串,如$、#。 > \[!NOTE]说明 > > * EOL参数只能用于TEXT格式的导入导出,不支持CSV格式和FIXED格式导入。为了兼容原有EOL参数,仍然支持导出CSV格式和FIXED格式时指定EOL参数为0x0D或0x0D0A。 > > * EOL参数不能和分隔符、null参数相同。 > > * EOL参数不能包含:.abcdefghijklmnopqrstuvwxyz0123456789。 * FORCE\_QUOTE { ( column\_name \[, ...] ) | \* } 在CSV COPY TO模式下,强制在每个声明的字段周围对所有非NULL值都使用引号包围。NULL输出不会被引号包围。 取值范围:已存在的字段。 * FORCE\_NOT\_NULL ( column\_name \[, ...] ) 此函数指定的列将不会把输入匹配(识别)为 null 字符串。null 值字符串将被默认为空字符串,即长度为零的字符串而不是 null,即使它们没有用引号引起来。 此选项仅允许在“COPY FROM”语句中,并且仅在指定为 CSV 格式时被允许使用。 取值范围:已存在的字段。 * ENCODING 指定数据文件的编码格式名称,缺省为当前数据库编码格式。 * IGNORE\_EXTRA\_DATA 若数据源文件比外表定义列数多,是否会忽略对多出的列。该参数只在数据导入过程中使用。 取值范围:true/on、false/off。 * 参数为true/on,若数据源文件比外表定义列数多,则忽略行尾多出来的列。 * 参数为false/off,若数据源文件比外表定义列数多,会显示如下错误信息。 ``` extra data after last expected column ``` 缺省值:false。 > \[!TIP]须知 > > 如果行尾换行符丢失,使两行变成一行时,设置此参数为true将导致后一行数据被忽略掉。 * COMPATIBLE\_ILLEGAL\_CHARS 导入非法字符容错参数。此语法仅对COPY FROM导入有效。 取值范围:true/on、false/off。 * 参数为true/on,则导入时遇到非法字符进行容错处理,非法字符转换后入库,不报错,不中断导入。 * 参数为false/off,导入时遇到非法字符进行报错,中断导入。 缺省值:false/off > \[!NOTE]说明 > > 导入非法字符容错规则如下: > > (1)对于'\0',容错后转换为空格; > > (2)对于其他非法字符,容错后转换为问号; > > (3)若compatible\_illegal\_chars为true/on标识导入时对于非法字符进行容错处理,则若NULL、DELIMITER、QUOTE、ESCAPE设置为空格或问号则会通过如“illegal chars conversion may confuse COPY escape 0x20”等报错信息提示用户修改可能引起混淆的参数以避免导入错误。 * FILL\_MISSING\_FIELDS 当数据加载时,若数据源文件中一行的最后一个字段缺失的处理方式。 取值范围:true/on、false/off。 缺省值:false/off * DATE\_FORMAT 导入对于DATE类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法DATE格式。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 > \[!NOTE]说明 > > 对于DATE类型内建为TIMESTAMP类型的数据库,在导入的时候,若需指定格式,可以参考下面的timestamp\_format参数。 * TIME\_FORMAT 导入对于TIME类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法TIME格式,不支持时区。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * TIMESTAMP\_FORMAT 导入对于TIMESTAMP类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法TIMESTAMP格式,不支持时区。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * SMALLDATETIME\_FORMAT 导入对于SMALLDATETIME类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 ``` 取值范围:合法SMALLDATETIME格式。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 ``` * **COPY\_OPTION { option\_name ' value ' }** 用于指定COPY原生的各类参数。 * NULL null\_string 用来指定数据文件中空值的表示。 > \[!TIP]须知 > > 在使用COPY FROM的时候,任何匹配这个字符串的字符串将被存储为NULL值,所以应该确保指定的字符串和COPY TO相同。 取值范围: * null值不能是\r和\n,最大为100个字符。 * null值不能和分隔符、quote参数相同。 缺省值: * 在TEXT格式下默认值是\N。 * CSV格式下默认值是一个没有引号的空字符串。 * HEADER 指定导出数据文件是否包含标题行,标题行一般用来描述表中每个字段的信息。header只能用于CSV、FIXED格式的文件中。 在导入数据时,如果header选项为on,则数据文本第一行会被识别为标题行,会忽略此行。如果header为off,而数据文件中第一行会被识别为数据。 在导出数据时,如果header选项为on,且未指定fileheader,则将把表的列名信息导出到文件的第一行;如果指定了fileheader,则将把fileheader文件的第一行导出到最终输出文件的第一行。如果header为off,则导出数据文件不包含标题行。 * FILEHEADER 导出数据时用于定义标题行的文件,一般用来描述每一列的数据信息。 > \[!TIP]须知 > > * 仅在header为on或true的情况下有效。 > > * fileheader指定的是绝对路径。 > > * 该文件只能包含一行标题信息,并以换行符结尾,多余的行将被丢弃(标题信息不能包含换行符)。 > > * 该文件包括换行符在内长度不超过1M。 * FREEZE 将COPY加载的数据行设置为已经被frozen,就像这些数据行执行过VACUUM FREEZE。 这是一个初始数据加载的性能选项。仅当以下三个条件同时满足时,数据行会被frozen: * 在同一事务中create或truncate这张表之后执行COPY。 * 当前事务中没有打开的游标。 * 当前事务中没有原有的快照。 > \[!NOTE]说明 > > * COPY完成后,所有其他会话将会立刻看到这些数据。但是这违反了MVCC可见性的一般原则,用户应当了解这样会导致潜在的风险。 > * 当条件不满足时,FREEZE选项将会被忽略而不会报错。 * FORCE NOT NULL column\_name \[, ...] 在CSV COPY FROM模式下,指定的字段不为空。若输入为空,则将视为长度为0的字符串。 取值范围:已存在的字段。 * FORCE NULL column\_name \[, ...] 在CSV COPY FROM模式下,将指定的字段表示空值的字符串设置为NULL,包括加了引号的空值字符串。 取值范围:已存在的字段。 * FORCE QUOTE { column\_name \[, ...] | \* } 在CSV COPY TO模式下,强制在每个声明的字段周围对所有非NULL值都使用引号包围。NULL输出不会被引号包围。 取值范围:已存在的字段。 * BINARY 使用二进制格式存储和读取,而不是以文本的方式。在二进制模式下,不能声明DELIMITER、NULL、CSV选项。指定BINARY类型后,不能再通过option或copy\_option指定CSV、FIXED、TEXT等类型。 * CSV 打开逗号分隔变量(CSV)模式。指定CSV类型后,不能再通过option或copy\_option指定BINARY、FIXED、TEXT等类型。 * QUOTE \[AS] 'quote\_character' CSV格式文件下的引号字符。 缺省值:双引号。 > \[!NOTE]说明 > > * quote参数不能和分隔符、null参数相同。 > * quote参数只能是单字节的字符。 > * 推荐不可见字符作为quote,例如0x07、0x08、0x1b等。 > 例如quote e'\x22' :使用ASCII编码为16进制22的字符。 * ESCAPE \[AS] 'escape\_character' ``` CSV格式下,用来指定逃逸字符,逃逸字符只能指定为单字节字符。 默认值为双引号。当与quote值相同时,会被替换为'\\0'。 ``` * EOL 'newline\_character' 指定导入导出数据文件换行符样式。 取值范围:支持多字符换行符,但换行符不能超过10个字节。常见的换行符,如\r、\n、\r\n(设成0x0D、0x0A、0x0D0A效果是相同的),其他字符或字符串,如$、#。 > \[!NOTE]说明 > > * EOL参数只能用于TEXT格式的导入导出,不支持CSV格式和FIXED格式。为了兼容原有EOL参数,仍然支持导出CSV格式和FIXED格式时指定EOL参数为0x0D或0x0D0A。 > * EOL参数不能和分隔符、null参数相同。 > * EOL参数不能包含:.abcdefghijklmnopqrstuvwxyz0123456789。 * ENCODING 'encoding\_name' 指定文件编码格式名称。 取值范围:有效的编码格式。 缺省值:当前编码格式。 * IGNORE\_EXTRA\_DATA 指定当数据源文件比外表定义列数多时,忽略行尾多出来的列。该参数只在数据导入过程中使用。 若不使用该参数,在数据源文件比外表定义列数多,会显示如下错误信息。 ``` extra data after last expected column ``` * COMPATIBLE\_ILLEGAL\_CHARS 指定导入时对非法字符进行容错处理,非法字符转换后入库。不报错,不中断导入。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 若不使用该参数,导入时遇到非法字符进行报错,中断导入。 > \[!NOTE]说明 > > 导入非法字符容错规则如下: > (1)对于'\0',容错后转换为空格; > (2)对于其他非法字符,容错后转换为问号; > (3)若compatible\_illegal\_chars为true/on标识,导入时对于非法字符进行容错处理,则若NULL、DELIMITER、QUOTE、ESCAPE设置为空格或问号则会通过如“illegal chars conversion may confuse COPY escape 0x20”等报错信息提示用户修改可能引起混淆的参数以避免导入错误。 * FILL\_MISSING\_FIELDS 当数据加载时,若数据源文件中一行的最后一个字段缺失的处理方式。 取值范围:true/on、false/off。 缺省值:false/off。 > \[!TIP]须知 > > 目前COPY指定此Option实际不会生效,即不会有相应的容错处理效果(不生效)。需要额外注意的是,打开此选项会导致解析器在数据库主节点数据解析阶段(即COPY错误表容错的涵盖范围)忽略此数据问题,而到数据库节点重新报错,从而使得COPY错误表(打开LOG ERRORS REJECT LIMIT)在此选项打开的情况下无法成功捕获这类少列的数据异常。因此请不要指定此选项。 * DATE\_FORMAT 'date\_format\_string' 导入对于DATE类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法DATE格式。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 > \[!NOTE]说明 > > 对于DATE类型内建为TIMESTAMP类型的数据库,在导入的时候,若需指定格式,可以参考下面的timestamp\_format参数。 * TIME\_FORMAT 'time\_format\_string' 导入对于TIME类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法TIME格式,不支持时区。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * TIMESTAMP\_FORMAT 'timestamp\_format\_string' 导入对于TIMESTAMP类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法TIMESTAMP格式,不支持时区。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * SMALLDATETIME\_FORMAT 'smalldatetime\_format\_string' 导入对于SMALLDATETIME类型指定格式。此参数不支持BINARY格式,会报“cannot specify bulkload compatibility options in BINARY mode”错误信息。此参数仅对COPY FROM导入有效。 取值范围:合法SMALLDATETIME格式。可参考[时间和日期处理函数和操作符](date_and_time_processing_functions_and_operators.md)。 * TRANSFORM ( { column\_name \[ data\_type ] \[ AS transform\_expr ] } \[, ...] ) 指定表中各个列的转换表达式;其中data\_type指定该列在表达式参数中的数据类型;transform\_expr为目标表达式,返回与表中目标列数据类型一致的结果值,表达式可参考[表达式](simple_expressions.md)。 COPY FROM能够识别的特殊反斜杠序列如下所示。 * **\b**:反斜杠 (ASCII 8) * **\f**:换页(ASCII 12) * **\n**:换行符 (ASCII 10) * **\r**:回车符 (ASCII 13) * **\t**:水平制表符 (ASCII 9) * **\v**:垂直制表符 (ASCII 11) * **\digits**:反斜杠后面跟着一到三个八进制数,表示ASCII值为该数的字符。 * **\xdigits**:反斜杠x后面跟着一个或两个十六进制位声明指定数值编码的字符。 ## 示例 ``` --将tpcds.ship_mode中的数据拷贝到/home/omm/ds_ship_mode.dat文件中。 openGauss=# COPY tpcds.ship_mode TO '/home/omm/ds_ship_mode.dat'; --将tpcds.ship_mode 输出到stdout。 openGauss=# COPY tpcds.ship_mode TO stdout; --创建tpcds.ship_mode_t1表。 openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) ; --从stdin拷贝数据到表tpcds.ship_mode_t1。 openGauss=# COPY tpcds.ship_mode_t1 FROM stdin; --从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1。 openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat'; --从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1,应用TRANSFORM表达式转换,取SM_TYPE列左边10个字符插入到表中。 openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' TRANSFORM (SM_TYPE AS LEFT(SM_TYPE, 10)); --从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1,使用参数如下:导入格式为TEXT(format 'text'),分隔符为'\t'(delimiter E'\t'),忽略多余列(ignore_extra_data 'true'),不指定转义(noescaping 'true')。 openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' WITH(format 'text', delimiter E'\t', ignore_extra_data 'true', noescaping 'true'); --从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1,使用参数如下:导入格式为FIXED(FIXED),指定定长格式(FORMATTER(SM_SHIP_MODE_SK(0, 2), SM_SHIP_MODE_ID(2,16), SM_TYPE(18,30), SM_CODE(50,10), SM_CARRIER(61,20), SM_CONTRACT(82,20))),忽略多余列(ignore_extra_data),有数据头(header)。 openGauss=# COPY tpcds.ship_mode_t1 FROM '/home/omm/ds_ship_mode.dat' FIXED FORMATTER(SM_SHIP_MODE_SK(0, 2), SM_SHIP_MODE_ID(2,16), SM_TYPE(18,30), SM_CODE(50,10), SM_CARRIER(61,20), SM_CONTRACT(82,20)) header ignore_extra_data; --删除tpcds.ship_mode_t1。 openGauss=# DROP TABLE tpcds.ship_mode_t1; ``` ## 相关链接 [PG\_STAT\_PROGRESS\_COPY](../database_reference/pg_stat_progress_copy.md) --- --- url: >- /en/docs/latest-lite/characteristic_description/copy_interface_for_error_tolerance.md --- # Copy Interface for Error Tolerance ## Availability This feature is available since openGauss 1.0.0. ## Introduction Certain errors that occur during the copy process are imported to a specified error table without interrupting the process. ## Benefits Refine the copy function and improve the tolerance and robustness to common errors such as invalid formats. ## Description openGauss provides the encapsulated copy error tables for creating functions and allows users to specify error tolerance options when using the **Copy From** statement. In this way, errors related to parsing, data format, and character set during the execution of the **Copy From** statement are recorded in the error table instead of being reported which may interrupt transactions. Even if a small amount of data in the target file of **Copy From** is incorrect, the data can be imported to the database. You can locate and rectify the fault in the error table later. ## Enhancements None ## Constraints For details, see [handling-import-errors](../database_om_guide/running_the_copy_from_stdin_statement_to_import_data.md). ## Dependencies None --- --- url: >- /en/docs/latest/characteristic_description/copy_interface_for_error_tolerance.md --- # Copy Interface for Error Tolerance ## Availability This feature is available since openGauss 1.0.0. ## Introduction Certain errors that occur during the copy process are imported to a specified error table without interrupting the process. ## Benefits Refine the copy function and improve the tolerance and robustness to common errors such as invalid formats. ## Description openGauss provides the encapsulated copy error tables for creating functions and allows users to specify error tolerance options when using the **Copy From** statement. In this way, errors related to parsing, data format, and character set during the execution of the **Copy From** statement are recorded in the error table instead of being reported and interrupted. Even if a small amount of data in the target file of **Copy From** is incorrect, the data can be imported to the database. You can locate and rectify the fault in the error table later. ## Enhancements None ## Constraints For details, see [handling-import-errors](../database_om_guide/running_the_copy_from_stdin_statement_to_import_data.md). ## Dependencies None --- --- url: /en/docs/latest-lite/developer_guide/copymanager.md --- # CopyManager CopyManager is an API class provided by the JDBC driver in openGauss. It is used to import data to openGauss in batches. ## Inheritance Relationship of CopyManager The CopyManager class is in the **org.opengauss.copy** package and inherits the java.lang.Object class. The declaration of the class is as follows: ``` public class CopyManager extends Object ``` ## Construction Method public CopyManager(BaseConnection connection) throws SQLException ## Common Methods **Table 1** Common methods of CopyManager --- --- url: /en/docs/latest/developer_guide/copymanager.md --- # CopyManager CopyManager is an API class provided by the JDBC driver in openGauss. It is used to import data to openGauss in batches. ## Inheritance Relationship of CopyManager The CopyManager class is in the **org.opengauss.copy** package and inherits the java.lang.Object class. The declaration of the class is as follows: ``` public class CopyManager extends Object ``` ## Construction Method public CopyManager(BaseConnection connection) throws SQLException ## Common Methods **Table 1** Common methods of CopyManager --- --- url: /zh/docs/latest-lite/developer_guide/copymanager.md --- # CopyManager CopyManager是openGauss JDBC驱动中提供的一个API接口类,用于批量向openGauss中导入数据。 ## CopyManager的继承关系 CopyManager类位于org.postgresql.copy Package中,继承自java.lang.Object类,该类的声明如下: ``` public class CopyManager extends Object ``` ## 构造方法 public CopyManager(BaseConnection connection) throws SQLException ## 常用方法 **表 1** CopyManager常用方法 --- --- url: /zh/docs/latest/developer_guide/copymanager.md --- # CopyManager CopyManager是openGauss JDBC驱动中提供的一个API接口类,用于批量向openGauss中导入数据。 ## CopyManager的继承关系 CopyManager类位于org.postgresql.copy Package中,继承自java.lang.Object类,该类的声明如下: ``` public class CopyManager extends Object ``` ## 构造方法 public CopyManager(BaseConnection connection) throws SQLException ## 常用方法 **表 1** CopyManager常用方法 --- --- url: >- /zh/docs/latest-lite/characteristic_description/copy_interface_for_error_tolerance.md --- # Copy接口支持容错机制 ## 可获得性 本特性自openGauss 1.0.0版本开始引入。 ## 特性简介 支持将Copy过程中的部分错误导入到指定的错误表中,并且保持Copy过程不被中断。 ## 客户价值 提升Copy功能的可用性和易用性,提升对于源数据格式异常等常见错误的容忍性和鲁棒性。 ## 特性描述 openGauss提供用户封装好的Copy错误表创建函数,并允许用户在使用Copy From指令时指定容错选项,使得Copy From语句在执行过程中部分解析、数据格式、字符集等相关的错误不会报错而中断事务,而是被记录至错误表中,使得在Copy From的目标文件即使有少量数据错误也可以完成入库操作。用户随后可以在错误表中对相关的错误进行定位以及进一步排查。 ## 特性增强 无。 ## 特性约束 支持容错的具体错误种类请参见《数据库运维指南》中“导入数据 > 使用COPY FROM STDIN导入数据 > 处理错误表”章节。 ## 依赖关系 无。 --- --- url: >- /zh/docs/latest/characteristic_description/copy_interface_for_error_tolerance.md --- # Copy接口支持容错机制 ## 可获得性 本特性自openGauss 1.0.0版本开始引入。 ## 特性简介 支持将Copy过程中的部分错误导入到指定的错误表中,并且保持Copy过程不被中断。 ## 客户价值 提升Copy功能的可用性和易用性,提升对于源数据格式异常等常见错误的容忍性和鲁棒性。 ## 特性描述 openGauss提供用于创建函数的封装好的Copy错误表,并允许用户在使用Copy From指令时指定容错选项,使得Copy From语句在执行过程中部分解析、数据格式、字符集等相关的报错不会中断事务,而是被记录至错误表中,使得在Copy From的目标文件即使有少量数据错误也可以完成入库操作。用户随后可以在错误表中对相关的错误进行定位以及进一步排查。 ## 特性增强 无。 ## 特性约束 支持容错的具体错误种类请参见《数据库运维指南》中“导入数据 > 使用COPY FROM STDIN导入数据 > 处理错误表”章节。 ## 依赖关系 无。 --- --- url: /en/docs/latest-lite/about_opengauss/core_database_technologies.md --- # Core Database Technologies * **[Basic Functions Oriented to Application Development](#basic-functions-oriented-to-application-development)** * **[High Performance](#high-performance)** * **[High Availability](##high-availability)** * **[Maintainability](#maintainability)** * **[Database Security](#database-security)** ## Basic Functions Oriented to Application Development * Standard SQL openGauss supports standard SQL statements. The SQL standard is an international standard and is updated periodically. SQL standards are classified into core features and optional features. Most databases do not fully support 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. openGauss supports most of the SQL:2011 core features and some optional features. For details about the feature list, see [SQL Syntax](../sql_reference/sql_syntax_formats.md). The introduction of standard SQL provides a unified SQL interface for all database vendors, reducing the learning costs of users and openGauss application migration costs. * Standard Development Interfaces Standard ODBC and JDBC interfaces are provided to ensure quick migration of user services to openGauss. Currently, the standard ODBC 3.5 and JDBC 4.0 interfaces are supported. The ODBC interface supports SUSE Linux, Windows 32-bit, and Windows 64-bit platforms. The JDBC interface supports all platforms. * Multiple Storage Engines openGauss is based on the unified transaction mechanism, log system, concurrency control system, metadata information, and cache management, provides Table Access Method API, and supports different storage engines. Currently, the Astore and Ustore storage engines are supported. * Transaction Support Transaction support refers to the system capability to ensure the atomicity, consistency, isolation, and durability (ACID) features of global transactions. Transaction support and data consistency assurance are the basic functions of most databases and the prerequisites for a database to satisfy transaction-based application requirements. * Atomicity A transaction is comprised of an indivisible unit of work. Operations performed in a transaction must be all finished or have not been performed. * Consistency Transactions must be consistent within a system no matter when or how many concurrent transactions are ongoing. * Isolation Transactions are isolated for execution, as if each of them is the only operation performed during the specified period planned by the system. If there are two transactions that are executed within the same period of time and performing the same function, the transaction isolation makes each of them regard itself as the only transaction using the system. * Durability After a transaction is complete, the changes made by the transaction to the database are permanently stored in the database and will not be rolled back. The default transaction isolation level is READ COMMITTED, ensuring no dirty data will be read. Transactions are categorized into single-statement transactions and transaction blocks. Their basic interfaces are as follows: * Start transaction; * Commit; * Rollback; Set transaction (used for setting the isolation level, read/write mode, and delay mode). For details about the syntax, see the *SQLReference*. * Support for Functions and Stored Procedures Functions are important database objects. They encapsulate SQL statement sets used for certain functions so that the statements can be easily invoked. A stored procedure is a combination of SQL and PL/SQL. Stored procedures can move the code that executes business rules from the application to the database. Therefore, the code storage can be used by multiple programs at a time. 1. Allows customers to modularize program design and encapsulate SQL statement sets, easy to invoke. 2. Caches the compilation results of stored procedures to accelerate SQL statement set execution. 3. Allows system administrators to restrict the permission for executing a specific stored procedure and controls access to the corresponding type of data. This prevents access from unauthorized users and ensures data security. 4. To process SQL statements, the stored procedure process assigns a memory fragment to store context association. Cursors are handles or pointers to context areas. With cursors, stored procedures can control alterations in context areas. 5. Six levels of exception information are supported to facilitate the debugging of stored procedures. Stored procedure debugging is a debugging method. During the development of a stored procedure, you can trace the process executed by the stored procedure step by step and find the error cause or program bug based on the variable value to improve the fault locating efficiency. You can set breakpoints and perform independent debugging. openGauss supports functions and stored procedures in the SQL standard, which enhances the usability of stored procedures. For details about how to use the stored procedures, see the *SQLReference*. * PG Interface Compatibility Compatible with PostgreSQL clients and interfaces. * SQL Hints SQL hints are supported, which can override any execution plan and thus improve SQL query performance. In plan hints, you can specify a join order; join, stream, and scan operations; and the number of rows in a result to tune an execution plan, improving query performance. * Copy Interface for Error Tolerance openGauss provides the encapsulated copy error tables for creating functions and allows users to specify error tolerance options when using the **Copy From** statement. In this way, errors related to parsing, data format, and character set during the execution of the **Copy From** statement are recorded in the error table instead of being reported and interrupted. Even if a small amount of data in the target file of **Copy From** is incorrect, the data can be imported to the database. You can locate and rectify the fault in the error table later. ## High Performance ### CBO Optimizer The openGauss optimizer is a typical Cost-based Optimization (CBO). By using CBO, the database calculates the number of tuples and the execution cost for each execution step under each execution plan based on the number of table tuples, column width, NULL record ratio, and characteristic values, such as distinct, MCV, and HB values, and certain cost calculation methods. The database then selects the execution plan that takes the lowest cost for the overall execution or for the return of the first tuple. The CBO optimizer can select the most efficient execution plan among multiple plans based on the cost to meet customer service requirements to the maximum extent. ### Hybrid Row-Column Storage openGauss supports both row-store and column-store models. Users can choose a row-store or column-store table based on their needs. Column-store is recommended if a table contains many columns (called a wide table) but its query involves only a few columns. Row-store is recommended if a table contains only a few columns and a query involves most of the columns. [Figure 1](#en-us_topic_0242724708_fig4487133722819) shows the column-store model. **Figure 1** Column-store\ In a wide table containing a huge amount of data, a query usually only includes certain columns. In this case, the query performance of the row-store engine is poor. For example, a single table containing the data of a meteorological agency has 200 to 800 columns. Among these columns, only 10 are frequently accessed. In this case, a vectorized execution and column-store engine can significantly improve performance by saving storage space. Row-store tables and column-store tables have their own advantages and disadvantages. You are advised to select a table based on the site requirements. * Row-store table Row-store tables are created by default. Data is stored by row. Row-store supports adding, deleting, modifying, and querying data of a complete row. Therefore, this storage model applies to scenarios where data needs to be updated frequently. * Column-store table Data is stored by column. The I/O of data query in a single column is small, and column-store tables occupy less storage space than row-store tables. This storage model applies to scenarios where data is inserted in batches, less updated, and queried for statistical analysis. The performance of single point query and single record insertion in a column-store table is poor. The principles for selecting row-store and column-store tables are as follows: * Update frequency If data is frequently updated, use a row-store table. * Insert frequency If a small amount of data is frequently inserted each time, use a row-store table. If a large amount of data is inserted at a time, use column storage. * Number of columns If a table is to contain many columns, use a column-store table. * Number of columns to be queried If only a small number of columns (less than 50% of the total) is queried each time, use a column-store table. * Compression ratio The compression ratio of a column-store table is higher than that of a row-store table. The higher the compression ratio is, the more CPU resources will be consumed. ### In-place Upate Storage The in-place update storage engine solves the problems of space expansion and large tuples of the Append update storage engine. The design of efficient rollback segments is the basis of the in-place update storage engine. ### Xlog Lockless Update and Parallel Page Playback **Figure 2** Xlog lock less Design\ ![](figures/xlog-lock-less-design.png "xlog-lock-less-design") This feature optimizes the WalInsertLock mechanism by using log sequence numbers (LSNs) and log record counts (LRCs) to record the copy progress of each backend and canceling the WalInsertLock mechanism. The backend can directly copy logs to the WalBuffer without contending for the WalInsertLock. In addition, a dedicated WALWriter thread is used to write logs, and the backend thread does not need to ensure the Xlog flushing. After the preceding optimization, the WalInsertLock contention and WalWriter dedicated disk write threads are canceled. The system performance can be further improved while the original XLog function remains unchanged. This feature optimizes the Ustore in-place update WALs and Ustore DML operation parallel playback and distribution. Prefixes and suffixes are used to reduce the update WALs. The playback thread is divided into multiple types to solve the problem that most Ustore DML WALs are replayed on multiple pages. In addition, the Ustore data page playback is distributed based on blkno to improve the degree of parallel playback. ### Adaptive Compression Currently, mainstream databases usually use the data compression technology. Various compression algorithms are used for different data types. If pieces of data of the same type have different characteristics, their compression algorithms and results will also be different. Adaptive compression chooses the suitable compression algorithm for data based on the data type and characteristics, achieving high performance in compression ratio, import, and query. Importing and frequently querying a huge amount of data are the main application scenarios. When you import data, adaptive compression greatly reduces the data volume, increases I/O operation efficiency several times, and clusters data before storage, achieving fast data import. In this way, only a small number of I/O operations is required and data is quickly decompressed in a query. Data can be quickly retrieved and the query result is quickly returned. Currently, the database has implemented various compression algorithms, including RLE, DELTA, BYTEPACK/BITPACK, LZ4, ZLIB, and LOCAL DICTIONARY. The following table lists data types and the compression algorithms suitable for them. For example, large integer compression of mobile number-like character strings, large integer compression of the numeric type, and adjustment of the compression algorithm compression level are supported. ### Partition In the openGauss system, data is partitioned horizontally on an instance using a specified policy. This operation splits a table into multiple partitions that are not overlapped. In common scenarios, a partitioned table has the following advantages over a common table: * High query performance: You can specify partitions when querying partitioned tables, improving query efficiency. * High availability: If a certain partition in a partitioned table is faulty, data in the other partitions is still available. * Easy maintenance: If a partition in a partitioned table is faulty, only this partition needs to be repaired. * Balanced I/O: Partitions can be mapped to different disks to balance I/O and improve the overall system performance. Currently, openGauss supports range partitioned tables, list partitioned tables, and hash partitioned tables. * In a range partitioned table, data within a certain range is mapped to each partition. The range is determined by the partition key specified when the partitioned table is created. This partitioning mode is most commonly used. With the range partitioning function, the database divides a record, which is to be inserted into a table, into multiple ranges using one or multiple columns and creates a partition for each range to store data. Partition ranges do no overlap. * In a list partitioned table, data is mapped to each partition based on the key values contained in each partition. The key values contained in a partition are specified when the partition is created. The list partitioning function divides the key values in the records to be inserted into a table into multiple lists (the lists do not overlap in different partitions) based on a column of the table, and then creates a partition for each list to store the corresponding data. * In a hash partitioned table, data is mapped to each partition using the hash algorithm, and each partition stores records with the same hash value. The hash partitioning function uses the internal hash algorithm to divide records to be inserted into a table into partitions based on a column of the table. If you specify the **PARTITION** parameter when running the **CREATE TABLE** statement, data in the table will be partitioned. Users can modify partition keys as needed during table creation to make the query result stored in the same or least partitions (called partition pruning), so as to obtain consecutive I/O to improve the query performance. In actual services, time is often used as a filter criterion for query objects. Therefore, you can select the time column as the partition key. The key value range can be adjusted based on the total data volume and the data volume queried at a time. ### SQL Bypass In a typical OLTP scenario, simple queries account for a large proportion. This type of queries involves only single tables and simple expressions. To accelerate such query, the SQL bypass framework is proposed. After simple mode judgment is performed on such query at the parse layer, the query enters a special execution path and skips the classic execution framework, including operator initialization and execution, expression, and projection. Instead, it directly rewrites a set of simple execution paths and directly invokes storage interfaces, greatly accelerating the execution of simple queries. ### Kunpeng NUMA Architecture Optimization **Figure 2** Kunpeng NUMA architecture optimization\ ![](figures/kunpeng-numa-architecture-optimization.png "kunpeng-numa-architecture-optimization") 1. Based on the multi-core NUMA architecture of the Kunpeng processor, openGauss optimizes the NUMA architecture to reduce the cross-core memory access latency and maximize the multi-core Kunpeng computing capability. The key technologies include redo log batch insertion, NUMA distribution of hotspot data, and Clog partitions, greatly improving the processing performance of the TP system. 2. Based on the ARMv8.1 architecture used by the Kunpeng chip, openGauss uses the LSE instruction set to implement efficient atomic operations, effectively improving the CPU usage, multi-thread synchronization performance, and XLog write performance. 3. Based on the wider L3 cacheline provided by the Kunpeng chip, openGauss optimizes hotspot data access, effectively improving the cache access hit ratio, reducing the cache consistency maintenance overhead, and greatly improving the overall data access performance of the system. ### High Concurrency of the Thread Pool In the OLTP field, a database needs to process a large quantity of client connections. Therefore, the processing capability in high-concurrency scenarios is one of the important capabilities of the database. The simplest processing mode for external connections is the per-thread-per-connection mode, in which a user connection generates a thread. This mode features simple processing thanks to its architecture. However, in high-concurrency scenarios, there are too many threads, causing heavy workload in thread switchover and large conflict between the lightweight lock areas of the database. As a result, the performance (throughput) deteriorates sharply and the SLA of user performance cannot be met. Therefore, a thread resource pooling and reuse technology needs to be used to resolve this problem. The overall design idea of the thread pool technology is to pool thread resources and reuse them among different connections. After the system is started, a fixed number of working threads are started based on the current number of cores or user configuration. A working thread serves one or more connection sessions. In this way, the session and thread are decoupled. The number of worker threads is fixed. Therefore, frequent thread switchover does not occur in case of high concurrency. The database layer schedules and manages sessions. ### Parallel Query The Symmetric Multi-Processing (SMP) parallel technology of openGauss uses the multi-core CPU architecture of a computer to implement multi-thread parallel computing, fully using CPU resources to improve query performance. In complex query scenarios, a single query execution takes long time and the system concurrency is low. Therefore, the SMP parallel execution technology is used to implement operator-level parallel execution, which effectively reduces the query execution time and improves the query performance and resource utilization. The overall implementation of the SMP parallel technology is as follows: For query operators that can be executed in parallel, data is sliced, multiple working threads are started for computation, and then the results are summarized and returned to the frontend. The data interaction operator **Stream** is added to SMP parallel execution to implement data interaction between multiple working threads, ensuring the correctness of the query and completing the overall query. ### Dynamic Build and Execution Based on the query execution plan tree, with the library functions provided by the LLVM, openGauss moves the process of determining the actual execution path from the executor phase to the execution initialization phase. In this way, problems such as function calling, logic condition branch determination, and a large amount of data reading that are related to the original query execution are avoided, to improve the query performance. ## High Scalability ### High Concurrency of the Thread Pool In the OLTP field, a database needs to process a large quantity of client connections. Therefore, the processing capability in high-concurrency scenarios is one of the important capabilities of the database. The simplest processing mode for external connections is the per-thread-per-connection mode, in which a user connection generates a thread. This mode features simple processing thanks to its architecture. However, in high-concurrency scenarios, there are too many threads, causing heavy workload in thread switchover and large conflict between the lightweight lock areas of the database. As a result, the performance (throughput) deteriorates sharply and the SLA of user performance cannot be met. Therefore, a thread resource pooling and reuse technology needs to be used to resolve this problem. The overall design idea of the thread pool technology is to pool thread resources and reuse them among different connections. After the system is started, a fixed number of working threads are started based on the current number of cores or user configuration. A working thread serves one or more connection sessions. In this way, the session and thread are decoupled. The number of worker threads is fixed. Therefore, frequent thread switchover does not occur in case of high concurrency. The database layer schedules and manages sessions. ## HA ### Primary/Standby To ensure that a fault can be rectified, data needs to be written into multiple copies. Multiple copies are configured for the primary and standby nodes, and logs are used for data synchronization. In this way, openGauss has no data lost when a node is faulty or the system restarts after a stop, meeting the ACID feature requirements. The primary/standby environment supports two modes: primary/standby, and one primary and multiple standbys. In primary/standby mode, if the standby node needs to redo logs, it can be promoted to primary. In the one primary and multiple standbys mode, all standby nodes need to redo logs and can be promoted to primary. The primary/standby mode is mainly used for OLTP systems with general reliability to save storage resources. The one primary and multiple standbys mode provides higher DR capabilities and is suitable for the OLTP system with higher availability transaction processing. The **switchover** command can be used to trigger a switchover between the primary and standby nodes. If the primary node is faulty, the **failover** command can be used to promote the standby node to the primary. To ensure that the failover time is controllable, you can enable the log flow control function to control the rate of sending logs to the standby node. This ensures that the logs accumulated on the standby node will be replayed within the time configured for flow control. After flow control is enabled, the rate of sending logs to the standby node is dynamically adjusted. As a result, the overall transaction performance deteriorates. In scenarios such as initial installation or backup and restoration, data on the standby node needs to be rebuilt based on the primary node. In this case, the build function is required to send the data and WALs of the primary node to the standby node. When the primary node is faulty and joins again as a standby node, the build function needs to be used to synchronize data and WALs with those of the new primary node. Build includes full build and incremental build. Full build depends on primary node data for rebuild. The amount of data to be copied is large and the time required is long. Incremental build copies only differential files. The amount of data to be copied is small and the time required is short. Generally, the incremental build is preferred for fault recovery. If the incremental build fails, the full build continues until the fault is rectified. In addition to streaming replication in primary/standby mode, openGauss also supports logical replication. In logical replication, the primary database is called the source database, and the standby database is called the target database. The source database parses the WAL file based on the specified logical parsing rule and parses the DML operation into certain logical change information (standard SQL statements). The source database sends standard SQL statements to the target database. After receiving the SQL statements, the target database applies them to implement data synchronization. Logical replication involves only DML operations. Logical replication can implement cross-version replication, heterogeneous database replication, dual-write database replication, and table-level replication. ### Logical Backup openGauss provides the logical backup capability to back up data in user tables to local disk files in text or CSV format and restore the data in homogeneous or heterogeneous databases. ### Physical Backup openGauss provides the physical backup capability to back up data of the entire instance to local disk files in the internal database format, and restore data of the entire instance in a homogeneous database. Physical backup is classified into full backup and incremental backup. The difference is as follows: Full backup includes the full data of the database at the backup time point. The time required for full backup is long (in direct proportion to the total data volume of the database), and a complete database can be restored. Incremental backup involves only incremental data modified after a specified time point. It takes a short period of time (in direct proportion to the incremental data volume and irrelevant to the total data volume). However, a complete database can be restored only after the incremental backup and full backup are performed. openGauss supports both full and incremental backup modes. ### Flashback Restoration The flashback function is used to restore dropped tables from the recycle bin. Like in a Window OS, dropped table information is stored in the recycle bin of databases. The MVCC mechanism is used to restore data to a specified point in time or system change number (SCN). ### Ultimate RTO After the ultimate RTO function is enabled, multi-level pipelines are established for Xlog log playback to improve the concurrency and log playback speed. When the service load is heavy, the playback speed of the standby node cannot catch up with that of the primary node. After the system runs for a long time, logs are accumulated on the standby node. If a host is faulty, data restoration takes a long time and the database is unavailable, which severely affects system availability. The ultimate recovery time object (RTO) is enabled to reduce the data recovery time after a host fault occurs and improve availability. ### Logical Replication openGauss provides the logical decoding function to reversely parse physical logs into logical logs. Logical replication tools such as DRS convert logical logs to SQL statements and replay the SQL statements in the peer database. In this way, data can be synchronized between heterogeneous databases. Currently, unidirectional and bidirectional logical replication between the openGauss database and the MySQL or Oracle database is supported. DNs reversely parse physical logs to logical logs. Logical replication tools such as DRS extract logical logs from DNs, convert the logs to SQL statements, and replay the SQL statements in MySQL. Logical replication tools also extract logical logs from a MySQL database, reversely parse the logs to SQL statements, and replay the SQL statements in openGauss. In this way, data can be synchronized between heterogeneous databases. ### Point-In-Time Recovery (PITR) PITR uses basic hot backup, WALs, and WAL archive logs for backup and recovery. When replaying a WAL record, you can stop at any point in time, so that there is a snapshot of the consistent database at any point in time. That is, you can restore the database to the state at any time since the backup starts. During recovery, openGauss supports specifying the recovery stop point as TID, time, and LSN. ### High Availability Based on the Paxos Protocol (DCF) After DCF is enabled, DNs support Paxos-based replication and quorum, achieving high availability and disaster recovery. DNs support automatic primary node selection and log replication. The replication process supports compression and stream control to prevent high bandwidth usage. Node types based on Paxos roles are provided and can be adjusted. ### Two-City Three-DC DR Two-city three-DC indicates that the three DCs (production center, intra-city DR center, and remote DR center) are deployed in two cities. In recent years, natural disasters have occurred frequently at home and abroad. The two-city three-DC DR solution comes into being with the combination of two intra-city DCs and remote DR DCs. This solution features high availability and disaster backup capabilities. The two intra-city DCs are two data centers that can carry critical applications independently. They have similar data processing capabilities and can synchronize data in real time through high-speed links. Under normal circumstances, the two DCs manage services and system operation together and can be switched over. When disaster occurs, services can be switched over to the DR DC with almost no data loss, ensuring service continuity. Compared with the remote DR DC, two intra-city DCs have lower investment cost, faster building speed, easier operation and maintenance, and higher reliability. A remote DR DC is deployed in a different city and is used to back up data of the two DCs. When faults occur in the two DCs, the remote DR DC can recover services from backup data. Specifications * Streaming replication-based remote DR solution: * The network latency within the primary or DR database instance must be less than or equal to 10 ms, and the network latency between the primary and standby database instances must be less than or equal to 100 ms. The DR can run normally within the range of the required network latency. Otherwise, the primary and standby nodes will be disconnected. * The following table lists the log generation speeds in the primary database instance supported by different hardware specifications when the network bandwidth is not a bottleneck and the parallel playback function is enabled in the DR database instance. The RPO and RTO can be ensured only under the log generation speed. **Table 1** Log generation speed supported by different hardware specifications * A certain amount of data can be lost when the DR database instance is promoted to primary, and the RPO is less than or equal to 10 seconds. When the DR database instance is normal, the RTO for promoting the DR database instance to primary is less than or equal to 10 minutes. When the DR database instance is degraded, the RTO for promoting the DR database instance to primary is within 20 minutes. * Practice: Planned primary/standby database instance switchover, no data loss, RPO = 0, RTO ≤ 20 minutes (including the processes of demoting the primary database instance to the DR instance and promoting the DR database instance to the primary database instance) > \[!TIP]NOTICE > Tests show that the maximum write rate of SATA SSDs is about 240 MB/s, that of SAS SSDs is over 500 MB/s, and that of NVMe SSDs is even better. Currently, only the performance metric under the SATA SSD hardware specifications is provided. If the hardware conditions do not meet the preceding specifications, the single-shard log generation speed in the primary database instance must be reduced to ensure the RPO and RTO. > > Resources such as file handles and memory are used up in the primary and standby database instances. As a result, the RPO and RTO cannot be ensured. ## Maintainability ### Workload Diagnosis Report The workload diagnosis report (WDR) generates a performance report between two different time points based on the system performance snapshot data at two different time points. The report is used to diagnose database kernel performance faults. WDR depends on the following two components: * SNAPSHOT: The performance snapshot can be configured to collect a certain amount of performance data from the kernel at a specified interval and store the data in the user tablespace. Any snapshot can be used as a performance baseline for comparison with other snapshots. * WDR Reporter: This tool analyzes the overall system performance based on two snapshots, calculates the changes of more specific performance indicators between the two time periods, and generates summarized and detailed performance data. For details, see [Table 1](#en-us_concept_0238164494_table14895120191613) and [Table 2](#en-us_concept_0238164494_table23331848193120). **Table 1** Summarized diagnosis report **Table 2** Detailed diagnosis report Benefits: * WDR is the main method for diagnosing long-term performance problems. Based on the performance baseline of a snapshot, performance analysis is performed from multiple dimensions, helping DBAs understand the system load, performance of each component, and performance bottlenecks. * Snapshots are also an important data source for subsequent performance problem self-diagnosis and self-optimization suggestions. ### Slow SQL Diagnosis Slow SQL records information about all jobs whose execution time exceeds the threshold. Historical slow SQL provides table-based and function-based query interfaces. You can query the execution plan, start time, end time, query statement, row activity, kernel time, CPU time, execution time, parsing time, compilation time, query rewriting time, plan generation time, network time, I/O time, network overhead, lock overhead, and wait event. All information is anonymized. Slow SQL provides detailed information required for slow SQL diagnosis. You can diagnose performance problems of specific slow SQL statements offline without reproducing the problem. The table-based and function-based APIs help users collect statistics on slow SQL indicators and connect to third-party platforms. Both primary and standby nodes support slow SQL diagnosis. ## Database Security ### Access Control Access control is to manage users' database access control permissions, including database system permissions and object permissions. Role-based access control is supported. Roles and permissions are associated. Permissions are assigned to roles and then roles are assigned to users, implementing user access control permission management. The login access control is implemented by using the user ID and authentication technology. The object access control is implemented by checking the object permission based on the user permission on the object. You can assign the minimum permissions required for completing tasks to related database users to minimize database usage risks. An access control model based on separation of permissions is supported. Database roles are classified into system administrator, security administrator, and audit administrator. The security administrator creates and manages users, the system administrator grants and revokes user permissions, and the audit administrator audits all user behaviors. By default, the role-based access control model is used. You can set parameters to determine whether to enable the access control model based on separation of permissions. ### Separation of Control and Access Permissions For the system administrator, the control and access permissions on table objects are separated to improve data security of common users and restrict the object access permissions of administrators. This feature applies to the following scenarios: An enterprise has multiple business departments using different database users to perform service operations. Database maintenance departments at the same level use the database administrator to perform O\&M operations. The business departments require that administrators can only perform control operations (DROP, ALTER, and TRUNCATE) on data of each department and cannot perform access operations (INSERT, DELETE, UPDATE, SELECT, and COPY) without authorization. That is, the control permissions of database administrators for tables need to be isolated from their access permissions to improve the data security of common users. The system administrators can specify the **INDEPENDENT** attribute when creating a user, indicating that the user is a private user. Database administrators (including initial users and other administrators) can control (**DROP**, **ALTER**, and **TRUNCATE**) objects of private users but cannot access (**INSERT**, **DELETE**, **UPDATE**, **SELECT**, **COPY**, **GRANT**, **REVOKE**, and **ALTER OWNER**) the objects without authorization. ### Built-in Database Role Permission Management openGauss provides a group of default roles whose names start with **gs\_role\_**. These roles are provided to access to specific, typically high-privileged operations. You can grant these roles to other users or roles within the database so that they can use specific functions. These roles should be given with great care to ensure that they are used where they are needed. [Table 1](#table2118117460) describes the permissions of built-in roles. **Table 1** Built-in role permissions ### Database Encryption Authentication The password encryption method based on the RFC5802 mechanism is used for authentication. The unidirectional, irreversible Hash encryption algorithm PBKDF2 is used for encryption and authentication, effectively defending against rainbow attacks. The password of the created user is encrypted and stored in the system catalog. During the entire authentication process, passwords are encrypted for storage and transmission. The hash value is calculated and compared with the value stored on the server to verify the correctness. The message processing flow in the unified encryption and authentication process effectively prevents attackers from cracking the username or password by capturing packets. ### Database Audit Audit logs record user operations performed on database startup and stopping, connection, and DDL, DML, and DCL operations. The audit log mechanism enhances the database capability of tracing illegal operations and collecting evidence. You can set parameters to specify the statements or operations for which audit logs are recorded. Audit logs record the event time, type, execution result, username, database, connection information, database object, database instance name, port number, and details. You can query audit logs by start time and end time and filter audit logs by recorded field. 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. ### Network Communication Security SSL can be used to encrypt communication data between the client and server, ensuring communication security between the client and server. The TLS 1.2 protocol and a highly secure encryption algorithm suite are adopted. [Table 2](#table13251121491017) lists the supported encryption algorithm suites. **Table 2** Encryption algorithm suites ### Row-Level Security The row-level security (RLS) feature enables database access control to be accurate to each row of data tables. When different users perform the same SQL query operation, the read results may be different according to the RLS policy. You can create an RLS policy for a data table. The policy defines an expression that takes effect only for specific database users and SQL operations. When a database user accesses the data table, if a SQL statement meets the specified RLS policy of the data table, the expressions that meet the specified condition will be combined by using **AND** or **OR** based on the attribute type (**PERMISSIVE** | **RESTRICTIVE**) and applied to the execution plan in the query optimization phase. RLS is used to control the visibility of row-level data in tables. By predefining filters for data tables, the expressions that meet the specified condition can be applied to execution plans in the query optimization phase, which will affect the final execution result. Currently, RLS supports the following SQL statements: SELECT, UPDATE, and DELETE. ### Resource Labels The resource label feature classifies database resources based on user-defined rules to implement resource classification and management. Administrators can configure resource labels to configure security policies, such as auditing or data masking, for a group of database resources. Resource labels can be used to group database resources based on features and application scenarios. You can manage all database resources with specified labels, which greatly reduces policy configuration complexity and information redundancy and improves management efficiency. Currently, resource labels support the following database resource types: schema, table, column, view, and function. ### Dynamic Data Masking To prevent unauthorized users from sniffing privacy data, the dynamic data masking feature can be used to protect user privacy data. When an unauthorized user accesses the data for which a dynamic data masking policy is configured, the database returns the anonymized data to protect privacy data. Administrators can create dynamic data masking policies on data columns. The policies specify the data masking methods for specific user scenarios. After the dynamic data masking function is enabled, the system matches user identity information (such as the access IP address, client tool, and username) with the masking policy when a user accesses data in the sensitive column. After the matching is successful, the system masks the sensitive data in the query result of the column based on the masking policy. The purpose of dynamic data masking is to flexibly protect privacy data by configuring the filter, and specifying sensitive column labels and corresponding masking functions in the masking policy without changing the source data. ### Unified Auditing Unified auditing allows administrators to configure audit policies for database resources or resource labels to simplify management, generate audit logs, reduce redundant audit logs, and improve management efficiency. Administrators can customize audit policies for configuring operation behaviors or database resources. The policies are used to audit specific user scenarios, user behaviors, or database resources. After the unified auditing function is enabled, when a user accesses the database, the system matches the corresponding unified audit policy based on the user identity information, such as the access IP address, client tool, and username. Then, the system classifies the user behaviors based on the access resource label and user operation type (DML or DDL) in the policy to perform unified auditing. The purpose of unified auditing is to change the existing traditional audit behavior into specific tracking audit behavior and exclude other behaviors from the audit, thereby simplifying management and improving the security of audit data generated by the database. ### Password Strength Verification To harden the security of customer accounts and data, do not set weak passwords. You need to specify a password when initializing the database, creating a user, or modifying a user. The password must meet the strength requirements. Otherwise, the system prompts you to enter the password again. The account password complexity policy restricts the minimum number of uppercase letters, lowercase letters, digits, and special characters in a password, the maximum and minimum length of a password, the password cannot be the same as the username or the reverse of the username, and the password cannot be a weak password. This policy enhances user account security. Weak passwords are easy to crack. The definition of weak passwords may vary with users or user groups. Users can define their own weak passwords. The **password\_policy** parameter specifies whether to enable the password strength verification mechanism. The default value is **1**, indicating that the password strength verification mechanism is enabled. ### Data Encryption and Storage Imported data is encrypted before stored. This feature provides data encryption and decryption APIs for users and uses encryption functions to encrypt sensitive information columns identified by users, so that data can be stored in tables after being encrypted. If you need to encrypt the entire table, you need to write an encryption function for each column. Different attribute columns can use different input parameters. If a user with the required permission wants to view specific data, the user can decrypt required columns using the decryption function API. ### Ledger Database To prevent database O\&M personnel from stealing, tampering with, and erasing traces of the database, you can use the ledger database feature to perform comprehensive audit and trace the history. When a tamper-proof user table is modified, the database records the modification behavior to the history table where only data can be appended. In this way, the operation history can be recorded and the operation source can be traced. The ledger database stores and verifies historical operations by generating data hash digests. Ledgers refer to user history tables and global blockchain tables. For table-level data modification operations, the system records the operation information and hash digest in a global blockchain table. In addition, each tamper-proof user table corresponds to a user history table to record the hash digest of row-level data changes. You can determine whether the user table is tampered by recalculating the hash digest and verifying the hash digest consistency. Each record in the ledger represents a given operation fact that has occurred. The content of the record can only be appended and cannot be modified. The consistency between the tamper-proof user table and the corresponding history table can be checked to identify and track the tampering behavior. In addition, the ledger database provides an API for checking the tamper-proof user table consistency and an API for restoring and archiving history tables to meet the requirements of tampering identification, data expansion and mitigation, and historical data restoration and archiving. --- --- url: /en/docs/latest/about_opengauss/core_database_technologies.md --- # Core Database Technologies ## Basic Functions Oriented to Application Development * Standard SQL openGauss supports standard SQL statements. The SQL standard is an international standard and is updated periodically. SQL standards are classified into core features and optional features. Most databases do not fully support 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. openGauss supports most of the SQL:2011 core features and some optional features. For details about the feature list, see [SQL Syntax](../sql_reference/sql_syntax_formats.md). The introduction of standard SQL provides a unified SQL interface for all database vendors, reducing the learning costs of users and openGauss application migration costs. * Standard Development Interfaces Standard ODBC and JDBC interfaces are provided to ensure quick migration of user services to openGauss. Currently, the standard ODBC 3.5 and JDBC 4.0 interfaces are supported. The ODBC interface supports SUSE Linux, Windows 32-bit, and Windows 64-bit platforms. The JDBC interface supports all platforms. * Multiple Storage Engines openGauss is based on the unified transaction mechanism, log system, concurrency control system, metadata information, and cache management, provides Table Access Method API, and supports different storage engines. Currently, the Astore and Ustore storage engines are supported. * Transaction Support Transaction support refers to the system capability to ensure the atomicity, consistency, isolation, and durability (ACID) features of global transactions. Transaction support and data consistency assurance are the basic functions of most databases and the prerequisites for a database to satisfy transaction-based application requirements. * Atomicity A transaction is comprised of an indivisible unit of work. Operations performed in a transaction must be all finished or have not been performed. * Consistency Transactions must be consistent within a system no matter when or how many concurrent transactions are ongoing. * Isolation Transactions are isolated for execution, as if each of them is the only operation performed during the specified period planned by the system. If there are two transactions that are executed within the same period of time and performing the same function, the transaction isolation makes each of them regard itself as the only transaction using the system. * Durability After a transaction is complete, the changes made by the transaction to the database are permanently stored in the database and will not be rolled back. The default transaction isolation level is READ COMMITTED, ensuring no dirty data will be read. Transactions are categorized into single-statement transactions and transaction blocks. Their basic interfaces are as follows: * Start transaction; * Commit; * Rollback; Set transaction (used for setting the isolation level, read/write mode, and delay mode). For details about the syntax, see the *SQLReference*. * Support for Functions and Stored Procedures Functions are important database objects. They encapsulate SQL statement sets used for certain functions so that the statements can be easily invoked. A stored procedure is a combination of SQL and PL/SQL. Stored procedures can move the code that executes business rules from the application to the database. Therefore, the code storage can be used by multiple programs at a time. 1. Allows customers to modularize program design and encapsulate SQL statement sets, easy to invoke. 2. Caches the compilation results of stored procedures to accelerate SQL statement set execution. 3. Allows system administrators to restrict the permission for executing a specific stored procedure and controls access to the corresponding type of data. This prevents access from unauthorized users and ensures data security. 4. To process SQL statements, the stored procedure process assigns a memory fragment to store context association. Cursors are handles or pointers to context areas. With cursors, stored procedures can control alterations in context areas. 5. Six levels of exception information are supported to facilitate the debugging of stored procedures. Stored procedure debugging is a debugging method. During the development of a stored procedure, you can trace the process executed by the stored procedure step by step and find the error cause or program bug based on the variable value to improve the fault locating efficiency. You can set breakpoints and perform independent debugging. openGauss supports functions and stored procedures in the SQL standard, which enhances the usability of stored procedures. For details about how to use the stored procedures, see the *SQLReference*. * PG Interface Compatibility Compatible with PostgreSQL clients and interfaces. * SQL Hints SQL hints are supported, which can override any execution plan and thus improve SQL query performance. In plan hints, you can specify a join order; join, stream, and scan operations; and the number of rows in a result to tune an execution plan, improving query performance. * Copy Interface for Error Tolerance openGauss provides the encapsulated copy error tables for creating functions and allows users to specify error tolerance options when using the **Copy From** statement. In this way, errors related to parsing, data format, and character set during the execution of the **Copy From** statement are recorded in the error table instead of being reported and interrupted. Even if a small amount of data in the target file of **Copy From** is incorrect, the data can be imported to the database. You can locate and rectify the fault in the error table later. ## High Performance ### CBO Optimizer The openGauss optimizer is a typical Cost-based Optimization (CBO). By using CBO, the database calculates the number of tuples and the execution cost for each execution step under each execution plan based on the number of table tuples, column width, NULL record ratio, and characteristic values, such as distinct, MCV, and HB values, and certain cost calculation methods. The database then selects the execution plan that takes the lowest cost for the overall execution or for the return of the first tuple. The CBO optimizer can select the most efficient execution plan among multiple plans based on the cost to meet customer service requirements to the maximum extent. ### Hybrid Row-Column Storage openGauss supports both row-store and column-store models. Users can choose a row-store or column-store table based on their needs. Column-store is recommended if a table contains many columns (called a wide table) but its query involves only a few columns. Row-store is recommended if a table contains only a few columns and a query involves most of the columns. [Figure 1](#en-us_topic_0242724708_fig4487133722819) shows the column-store model. **Figure 1** Column-store\ In a wide table containing a huge amount of data, a query usually only includes certain columns. In this case, the query performance of the row-store engine is poor. For example, a single table containing the data of a meteorological agency has 200 to 800 columns. Among these columns, only 10 are frequently accessed. In this case, a vectorized execution and column-store engine can significantly improve performance by saving storage space. Row-store tables and column-store tables have their own advantages and disadvantages. You are advised to select a table based on the site requirements. * Row-store table Row-store tables are created by default. Data is stored by row. Row-store supports adding, deleting, modifying, and querying data of a complete row. Therefore, this storage model applies to scenarios where data needs to be updated frequently. * Column-store table Data is stored by column. The I/O of data query in a single column is small, and column-store tables occupy less storage space than row-store tables. This storage model applies to scenarios where data is inserted in batches, less updated, and queried for statistical analysis. The performance of single point query and single record insertion in a column-store table is poor. The principles for selecting row-store and column-store tables are as follows: * Update frequency If data is frequently updated, use a row-store table. * Insert frequency If a small amount of data is frequently inserted each time, use a row-store table. If a large amount of data is inserted at a time, use column storage. * Number of columns If a table is to contain many columns, use a column-store table. * Number of columns to be queried If only a small number of columns (less than 50% of the total) is queried each time, use a column-store table. * Compression ratio The compression ratio of a column-store table is higher than that of a row-store table. The higher the compression ratio is, the more CPU resources will be consumed. ### In-place Upate Storage The in-place update storage engine solves the problems of space expansion and large tuples of the Append update storage engine. The design of efficient rollback segments is the basis of the in-place update storage engine. ### Xlog Lockless Update and Parallel Page Playback **Figure 2** Xlog lock less Design\ ![](figures/xlog-lock-less-design.png "xlog-lock-less-design") This feature optimizes the WalInsertLock mechanism by using log sequence numbers (LSNs) and log record counts (LRCs) to record the copy progress of each backend and canceling the WalInsertLock mechanism. The backend can directly copy logs to the WalBuffer without contending for the WalInsertLock. In addition, a dedicated WALWriter thread is used to write logs, and the backend thread does not need to ensure the Xlog flushing. After the preceding optimization, the WalInsertLock contention and WalWriter dedicated disk write threads are canceled. The system performance can be further improved while the original XLog function remains unchanged. This feature optimizes the Ustore in-place update WALs and Ustore DML operation parallel playback and distribution. Prefixes and suffixes are used to reduce the update WALs. The playback thread is divided into multiple types to solve the problem that most Ustore DML WALs are replayed on multiple pages. In addition, the Ustore data page playback is distributed based on blkno to improve the degree of parallel playback. ### Adaptive Compression Currently, mainstream databases usually use the data compression technology. Various compression algorithms are used for different data types. If pieces of data of the same type have different characteristics, their compression algorithms and results will also be different. Adaptive compression chooses the suitable compression algorithm for data based on the data type and characteristics, achieving high performance in compression ratio, import, and query. Importing and frequently querying a huge amount of data are the main application scenarios. When you import data, adaptive compression greatly reduces the data volume, increases I/O operation efficiency several times, and clusters data before storage, achieving fast data import. In this way, only a small number of I/O operations is required and data is quickly decompressed in a query. Data can be quickly retrieved and the query result is quickly returned. Currently, the database has implemented various compression algorithms, including RLE, DELTA, BYTEPACK/BITPACK, LZ4, ZLIB, and LOCAL DICTIONARY. The following table lists data types and the compression algorithms suitable for them. For example, large integer compression of mobile number-like character strings, large integer compression of the numeric type, and adjustment of the compression algorithm compression level are supported. ### Partition In the openGauss system, data is partitioned horizontally on an instance using a specified policy. This operation splits a table into multiple partitions that are not overlapped. In common scenarios, a partitioned table has the following advantages over a common table: * High query performance: You can specify partitions when querying partitioned tables, improving query efficiency. * High availability: If a certain partition in a partitioned table is faulty, data in the other partitions is still available. * Easy maintenance: If a partition in a partitioned table is faulty, only this partition needs to be repaired. * Balanced I/O: Partitions can be mapped to different disks to balance I/O and improve the overall system performance. Currently, openGauss supports range partitioned tables, list partitioned tables, and hash partitioned tables. * In a range partitioned table, data within a certain range is mapped to each partition. The range is determined by the partition key specified when the partitioned table is created. This partitioning mode is most commonly used. With the range partitioning function, the database divides a record, which is to be inserted into a table, into multiple ranges using one or multiple columns and creates a partition for each range to store data. Partition ranges do no overlap. * In a list partitioned table, data is mapped to each partition based on the key values contained in each partition. The key values contained in a partition are specified when the partition is created. The list partitioning function divides the key values in the records to be inserted into a table into multiple lists (the lists do not overlap in different partitions) based on a column of the table, and then creates a partition for each list to store the corresponding data. * In a hash partitioned table, data is mapped to each partition using the hash algorithm, and each partition stores records with the same hash value. The hash partitioning function uses the internal hash algorithm to divide records to be inserted into a table into partitions based on a column of the table. If you specify the **PARTITION** parameter when running the **CREATE TABLE** statement, data in the table will be partitioned. Users can modify partition keys as needed during table creation to make the query result stored in the same or least partitions (called partition pruning), so as to obtain consecutive I/O to improve the query performance. In actual services, time is often used as a filter criterion for query objects. Therefore, you can select the time column as the partition key. The key value range can be adjusted based on the total data volume and the data volume queried at a time. ### SQL Bypass In a typical OLTP scenario, simple queries account for a large proportion. This type of queries involves only single tables and simple expressions. To accelerate such query, the SQL bypass framework is proposed. After simple mode judgment is performed on such query at the parse layer, the query enters a special execution path and skips the classic execution framework, including operator initialization and execution, expression, and projection. Instead, it directly rewrites a set of simple execution paths and directly invokes storage interfaces, greatly accelerating the execution of simple queries. ### Kunpeng NUMA Architecture Optimization **Figure 2** Kunpeng NUMA architecture optimization\ ![](figures/kunpeng-numa-architecture-optimization.png "kunpeng-numa-architecture-optimization") 1. Based on the multi-core NUMA architecture of the Kunpeng processor, openGauss optimizes the NUMA architecture to reduce the cross-core memory access latency and maximize the multi-core Kunpeng computing capability. The key technologies include redo log batch insertion, NUMA distribution of hotspot data, and Clog partitions, greatly improving the processing performance of the TP system. 2. Based on the ARMv8.1 architecture used by the Kunpeng chip, openGauss uses the LSE instruction set to implement efficient atomic operations, effectively improving the CPU usage, multi-thread synchronization performance, and XLog write performance. 3. Based on the wider L3 cacheline provided by the Kunpeng chip, openGauss optimizes hotspot data access, effectively improving the cache access hit ratio, reducing the cache consistency maintenance overhead, and greatly improving the overall data access performance of the system. ### High Concurrency of the Thread Pool In the OLTP field, a database needs to process a large quantity of client connections. Therefore, the processing capability in high-concurrency scenarios is one of the important capabilities of the database. The simplest processing mode for external connections is the per-thread-per-connection mode, in which a user connection generates a thread. This mode features simple processing thanks to its architecture. However, in high-concurrency scenarios, there are too many threads, causing heavy workload in thread switchover and large conflict between the lightweight lock areas of the database. As a result, the performance (throughput) deteriorates sharply and the SLA of user performance cannot be met. Therefore, a thread resource pooling and reuse technology needs to be used to resolve this problem. The overall design idea of the thread pool technology is to pool thread resources and reuse them among different connections. After the system is started, a fixed number of working threads are started based on the current number of cores or user configuration. A working thread serves one or more connection sessions. In this way, the session and thread are decoupled. The number of worker threads is fixed. Therefore, frequent thread switchover does not occur in case of high concurrency. The database layer schedules and manages sessions. ### Parallel Query The Symmetric Multi-Processing (SMP) parallel technology of openGauss uses the multi-core CPU architecture of a computer to implement multi-thread parallel computing, fully using CPU resources to improve query performance. In complex query scenarios, a single query execution takes long time and the system concurrency is low. Therefore, the SMP parallel execution technology is used to implement operator-level parallel execution, which effectively reduces the query execution time and improves the query performance and resource utilization. The overall implementation of the SMP parallel technology is as follows: For query operators that can be executed in parallel, data is sliced, multiple working threads are started for computation, and then the results are summarized and returned to the frontend. The data interaction operator **Stream** is added to SMP parallel execution to implement data interaction between multiple working threads, ensuring the correctness of the query and completing the overall query. ### Dynamic Build and Execution Based on the query execution plan tree, with the library functions provided by the LLVM, openGauss moves the process of determining the actual execution path from the executor phase to the execution initialization phase. In this way, problems such as function calling, logic condition branch determination, and a large amount of data reading that are related to the original query execution are avoided, to improve the query performance. ## High Scalability ### High Concurrency of the Thread Pool In the OLTP field, a database needs to process a large quantity of client connections. Therefore, the processing capability in high-concurrency scenarios is one of the important capabilities of the database. The simplest processing mode for external connections is the per-thread-per-connection mode, in which a user connection generates a thread. This mode features simple processing thanks to its architecture. However, in high-concurrency scenarios, there are too many threads, causing heavy workload in thread switchover and large conflict between the lightweight lock areas of the database. As a result, the performance (throughput) deteriorates sharply and the SLA of user performance cannot be met. Therefore, a thread resource pooling and reuse technology needs to be used to resolve this problem. The overall design idea of the thread pool technology is to pool thread resources and reuse them among different connections. After the system is started, a fixed number of working threads are started based on the current number of cores or user configuration. A working thread serves one or more connection sessions. In this way, the session and thread are decoupled. The number of worker threads is fixed. Therefore, frequent thread switchover does not occur in case of high concurrency. The database layer schedules and manages sessions. ## HA ### Primary/Standby To ensure that a fault can be rectified, data needs to be written into multiple copies. Multiple copies are configured for the primary and standby nodes, and logs are used for data synchronization. In this way, openGauss has no data lost when a node is faulty or the system restarts after a stop, meeting the ACID feature requirements. The primary/standby environment supports two modes: primary/standby, and one primary and multiple standbys. In primary/standby mode, if the standby node needs to redo logs, it can be promoted to primary. In the one primary and multiple standbys mode, all standby nodes need to redo logs and can be promoted to primary. The primary/standby mode is mainly used for OLTP systems with general reliability to save storage resources. The one primary and multiple standbys mode provides higher DR capabilities and is suitable for the OLTP system with higher availability transaction processing. The **switchover** command can be used to trigger a switchover between the primary and standby nodes. If the primary node is faulty, the **failover** command can be used to promote the standby node to the primary. To ensure that the failover time is controllable, you can enable the log flow control function to control the rate of sending logs to the standby node. This ensures that the logs accumulated on the standby node will be replayed within the time configured for flow control. After flow control is enabled, the rate of sending logs to the standby node is dynamically adjusted. As a result, the overall transaction performance deteriorates. In scenarios such as initial installation or backup and restoration, data on the standby node needs to be rebuilt based on the primary node. In this case, the build function is required to send the data and WALs of the primary node to the standby node. When the primary node is faulty and joins again as a standby node, the build function needs to be used to synchronize data and WALs with those of the new primary node. Build includes full build and incremental build. Full build depends on primary node data for rebuild. The amount of data to be copied is large and the time required is long. Incremental build copies only differential files. The amount of data to be copied is small and the time required is short. Generally, the incremental build is preferred for fault recovery. If the incremental build fails, the full build continues until the fault is rectified. In addition to streaming replication in primary/standby mode, openGauss also supports logical replication. In logical replication, the primary database is called the source database, and the standby database is called the target database. The source database parses the WAL file based on the specified logical parsing rule and parses the DML operation into certain logical change information (standard SQL statements). The source database sends standard SQL statements to the target database. After receiving the SQL statements, the target database applies them to implement data synchronization. Logical replication involves only DML operations. Logical replication can implement cross-version replication, heterogeneous database replication, dual-write database replication, and table-level replication. ### Logical Backup openGauss provides the logical backup capability to back up data in user tables to local disk files in text or CSV format and restore the data in homogeneous or heterogeneous databases. ### Physical Backup openGauss provides the physical backup capability to back up data of the entire instance to local disk files in the internal database format, and restore data of the entire instance in a homogeneous database. Physical backup is classified into full backup and incremental backup. The difference is as follows: Full backup includes the full data of the database at the backup time point. The time required for full backup is long (in direct proportion to the total data volume of the database), and a complete database can be restored. Incremental backup involves only incremental data modified after a specified time point. It takes a short period of time (in direct proportion to the incremental data volume and irrelevant to the total data volume). However, a complete database can be restored only after the incremental backup and full backup are performed. openGauss supports both full and incremental backup modes. ### Flashback Restoration The flashback function is used to restore dropped tables from the recycle bin. Like in a Window OS, dropped table information is stored in the recycle bin of databases. The MVCC mechanism is used to restore data to a specified point in time or system change number (SCN). ### Ultimate RTO After the ultimate RTO function is enabled, multi-level pipelines are established for Xlog log playback to improve the concurrency and log playback speed. When the service load is heavy, the playback speed of the standby node cannot catch up with that of the primary node. After the system runs for a long time, logs are accumulated on the standby node. If a host is faulty, data restoration takes a long time and the database is unavailable, which severely affects system availability. The ultimate recovery time object (RTO) is enabled to reduce the data recovery time after a host fault occurs and improve availability. ### Logical Replication openGauss provides the logical decoding function to reversely parse physical logs into logical logs. Logical replication tools such as DRS convert logical logs to SQL statements and replay the SQL statements in the peer database. In this way, data can be synchronized between heterogeneous databases. Currently, unidirectional and bidirectional logical replication between the openGauss database and the MySQL or Oracle database is supported. DNs reversely parse physical logs to logical logs. Logical replication tools such as DRS extract logical logs from DNs, convert the logs to SQL statements, and replay the SQL statements in MySQL. Logical replication tools also extract logical logs from a MySQL database, reversely parse the logs to SQL statements, and replay the SQL statements in openGauss. In this way, data can be synchronized between heterogeneous databases. ### Point-In-Time Recovery (PITR) PITR uses basic hot backup, WALs, and WAL archive logs for backup and recovery. When replaying a WAL record, you can stop at any point in time, so that there is a snapshot of the consistent database at any point in time. That is, you can restore the database to the state at any time since the backup starts. During recovery, openGauss supports specifying the recovery stop point as TID, time, and LSN. ### High Availability Based on the Paxos Protocol (DCF) After DCF is enabled, DNs support Paxos-based replication and quorum, achieving high availability and disaster recovery. DNs support automatic primary node selection and log replication. The replication process supports compression and stream control to prevent high bandwidth usage. Node types based on Paxos roles are provided and can be adjusted. ### Two-City Three-DC DR Two-city three-DC indicates that the three DCs (production center, intra-city DR center, and remote DR center) are deployed in two cities. In recent years, natural disasters have occurred frequently at home and abroad. The two-city three-DC DR solution comes into being with the combination of two intra-city DCs and remote DR DCs. This solution features high availability and disaster backup capabilities. The two intra-city DCs are two data centers that can carry critical applications independently. They have similar data processing capabilities and can synchronize data in real time through high-speed links. Under normal circumstances, the two DCs manage services and system operation together and can be switched over. When disaster occurs, services can be switched over to the DR DC with almost no data loss, ensuring service continuity. Compared with the remote DR DC, two intra-city DCs have lower investment cost, faster building speed, easier operation and maintenance, and higher reliability. A remote DR DC is deployed in a different city and is used to back up data of the two DCs. When faults occur in the two DCs, the remote DR DC can recover services from backup data. Specifications * Streaming replication-based remote DR solution: * The network latency within the primary or DR database instance must be less than or equal to 10 ms, and the network latency between the primary and standby database instances must be less than or equal to 100 ms. The DR can run normally within the range of the required network latency. Otherwise, the primary and standby nodes will be disconnected. * The following table lists the log generation speeds in the primary database instance supported by different hardware specifications when the network bandwidth is not a bottleneck and the parallel playback function is enabled in the DR database instance. The RPO and RTO can be ensured only under the log generation speed. **Table 1** Log generation speed supported by different hardware specifications * A certain amount of data can be lost when the DR database instance is promoted to primary, and the RPO is less than or equal to 10 seconds. When the DR database instance is normal, the RTO for promoting the DR database instance to primary is less than or equal to 10 minutes. When the DR database instance is degraded, the RTO for promoting the DR database instance to primary is within 20 minutes. * Practice: Planned primary/standby database instance switchover, no data loss, RPO = 0, RTO ≤ 20 minutes (including the processes of demoting the primary database instance to the DR instance and promoting the DR database instance to the primary database instance) > \[!TIP]NOTICE > Tests show that the maximum write rate of SATA SSDs is about 240 MB/s, that of SAS SSDs is over 500 MB/s, and that of NVMe SSDs is even better. Currently, only the performance metric under the SATA SSD hardware specifications is provided. If the hardware conditions do not meet the preceding specifications, the single-shard log generation speed in the primary database instance must be reduced to ensure the RPO and RTO. > > Resources such as file handles and memory are used up in the primary and standby database instances. As a result, the RPO and RTO cannot be ensured. ## Maintainability ### Workload Diagnosis Report The workload diagnosis report (WDR) generates a performance report between two different time points based on the system performance snapshot data at two different time points. The report is used to diagnose database kernel performance faults. WDR depends on the following two components: * SNAPSHOT: The performance snapshot can be configured to collect a certain amount of performance data from the kernel at a specified interval and store the data in the user tablespace. Any snapshot can be used as a performance baseline for comparison with other snapshots. * WDR Reporter: This tool analyzes the overall system performance based on two snapshots, calculates the changes of more specific performance indicators between the two time periods, and generates summarized and detailed performance data. For details, see [Table 1](#en-us_concept_0238164494_table14895120191613) and [Table 2](#en-us_concept_0238164494_table23331848193120). **Table 1** Summarized diagnosis report **Table 2** Detailed diagnosis report Benefits: * WDR is the main method for diagnosing long-term performance problems. Based on the performance baseline of a snapshot, performance analysis is performed from multiple dimensions, helping DBAs understand the system load, performance of each component, and performance bottlenecks. * Snapshots are also an important data source for subsequent performance problem self-diagnosis and self-optimization suggestions. ### Slow SQL Diagnosis Slow SQL records information about all jobs whose execution time exceeds the threshold. Historical slow SQL provides table-based and function-based query interfaces. You can query the execution plan, start time, end time, query statement, row activity, kernel time, CPU time, execution time, parsing time, compilation time, query rewriting time, plan generation time, network time, I/O time, network overhead, lock overhead, and wait event. All information is anonymized. Slow SQL provides detailed information required for slow SQL diagnosis. You can diagnose performance problems of specific slow SQL statements offline without reproducing the problem. The table-based and function-based APIs help users collect statistics on slow SQL indicators and connect to third-party platforms. Both primary and standby nodes support slow SQL diagnosis. ## Database Security ### Access Control Access control is to manage users' database access control permissions, including database system permissions and object permissions. Role-based access control is supported. Roles and permissions are associated. Permissions are assigned to roles and then roles are assigned to users, implementing user access control permission management. The login access control is implemented by using the user ID and authentication technology. The object access control is implemented by checking the object permission based on the user permission on the object. You can assign the minimum permissions required for completing tasks to related database users to minimize database usage risks. An access control model based on separation of permissions is supported. Database roles are classified into system administrator, security administrator, and audit administrator. The security administrator creates and manages users, the system administrator grants and revokes user permissions, and the audit administrator audits all user behaviors. By default, the role-based access control model is used. You can set parameters to determine whether to enable the access control model based on separation of permissions. ### Separation of Control and Access Permissions For the system administrator, the control and access permissions on table objects are separated to improve data security of common users and restrict the object access permissions of administrators. This feature applies to the following scenarios: An enterprise has multiple business departments using different database users to perform service operations. Database maintenance departments at the same level use the database administrator to perform O\&M operations. The business departments require that administrators can only perform control operations (DROP, ALTER, and TRUNCATE) on data of each department and cannot perform access operations (INSERT, DELETE, UPDATE, SELECT, and COPY) without authorization. That is, the control permissions of database administrators for tables need to be isolated from their access permissions to improve the data security of common users. The system administrators can specify the **INDEPENDENT** attribute when creating a user, indicating that the user is a private user. Database administrators (including initial users and other administrators) can control (**DROP**, **ALTER**, and **TRUNCATE**) objects of private users but cannot access (**INSERT**, **DELETE**, **UPDATE**, **SELECT**, **COPY**, **GRANT**, **REVOKE**, and **ALTER OWNER**) the objects without authorization. ### Built-in Database Role Permission Management openGauss provides a group of default roles whose names start with **gs\_role\_**. These roles are provided to access to specific, typically high-privileged operations. You can grant these roles to other users or roles within the database so that they can use specific functions. These roles should be given with great care to ensure that they are used where they are needed. [Table 1](#table2118117460) describes the permissions of built-in roles. **Table 1** Built-in role permissions ### Database Encryption Authentication The password encryption method based on the RFC5802 mechanism is used for authentication. The unidirectional, irreversible Hash encryption algorithm PBKDF2 is used for encryption and authentication, effectively defending against rainbow attacks. The password of the created user is encrypted and stored in the system catalog. During the entire authentication process, passwords are encrypted for storage and transmission. The hash value is calculated and compared with the value stored on the server to verify the correctness. The message processing flow in the unified encryption and authentication process effectively prevents attackers from cracking the username or password by capturing packets. ### Database Audit Audit logs record user operations performed on database startup and stopping, connection, and DDL, DML, and DCL operations. The audit log mechanism enhances the database capability of tracing illegal operations and collecting evidence. You can set parameters to specify the statements or operations for which audit logs are recorded. Audit logs record the event time, type, execution result, username, database, connection information, database object, database instance name, port number, and details. You can query audit logs by start time and end time and filter audit logs by recorded field. 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. ### Network Communication Security SSL can be used to encrypt communication data between the client and server, ensuring communication security between the client and server. The TLS 1.2 protocol and a highly secure encryption algorithm suite are adopted. [Table 2](#table13251121491017) lists the supported encryption algorithm suites. **Table 2** Encryption algorithm suites ### Row-Level Security The row-level security (RLS) feature enables database access control to be accurate to each row of data tables. When different users perform the same SQL query operation, the read results may be different according to the RLS policy. You can create an RLS policy for a data table. The policy defines an expression that takes effect only for specific database users and SQL operations. When a database user accesses the data table, if a SQL statement meets the specified RLS policy of the data table, the expressions that meet the specified condition will be combined by using **AND** or **OR** based on the attribute type (**PERMISSIVE** | **RESTRICTIVE**) and applied to the execution plan in the query optimization phase. RLS is used to control the visibility of row-level data in tables. By predefining filters for data tables, the expressions that meet the specified condition can be applied to execution plans in the query optimization phase, which will affect the final execution result. Currently, RLS supports the following SQL statements: SELECT, UPDATE, and DELETE. ### Resource Labels The resource label feature classifies database resources based on user-defined rules to implement resource classification and management. Administrators can configure resource labels to configure security policies, such as auditing or data masking, for a group of database resources. Resource labels can be used to group database resources based on features and application scenarios. You can manage all database resources with specified labels, which greatly reduces policy configuration complexity and information redundancy and improves management efficiency. Currently, resource labels support the following database resource types: schema, table, column, view, and function. ### Dynamic Data Masking To prevent unauthorized users from sniffing privacy data, the dynamic data masking feature can be used to protect user privacy data. When an unauthorized user accesses the data for which a dynamic data masking policy is configured, the database returns the anonymized data to protect privacy data. Administrators can create dynamic data masking policies on data columns. The policies specify the data masking methods for specific user scenarios. After the dynamic data masking function is enabled, the system matches user identity information (such as the access IP address, client tool, and username) with the masking policy when a user accesses data in the sensitive column. After the matching is successful, the system masks the sensitive data in the query result of the column based on the masking policy. The purpose of dynamic data masking is to flexibly protect privacy data by configuring the filter, and specifying sensitive column labels and corresponding masking functions in the masking policy without changing the source data. ### Unified Auditing Unified auditing allows administrators to configure audit policies for database resources or resource labels to simplify management, generate audit logs, reduce redundant audit logs, and improve management efficiency. Administrators can customize audit policies for configuring operation behaviors or database resources. The policies are used to audit specific user scenarios, user behaviors, or database resources. After the unified auditing function is enabled, when a user accesses the database, the system matches the corresponding unified audit policy based on the user identity information, such as the access IP address, client tool, and username. Then, the system classifies the user behaviors based on the access resource label and user operation type (DML or DDL) in the policy to perform unified auditing. The purpose of unified auditing is to change the existing traditional audit behavior into specific tracking audit behavior and exclude other behaviors from the audit, thereby simplifying management and improving the security of audit data generated by the database. ### Password Strength Verification To harden the security of customer accounts and data, do not set weak passwords. You need to specify a password when initializing the database, creating a user, or modifying a user. The password must meet the strength requirements. Otherwise, the system prompts you to enter the password again. The account password complexity policy restricts the minimum number of uppercase letters, lowercase letters, digits, and special characters in a password, the maximum and minimum length of a password, the password cannot be the same as the username or the reverse of the username, and the password cannot be a weak password. This policy enhances user account security. Weak passwords are easy to crack. The definition of weak passwords may vary with users or user groups. Users can define their own weak passwords. The **password\_policy** parameter specifies whether to enable the password strength verification mechanism. The default value is **1**, indicating that the password strength verification mechanism is enabled. ### Data Encryption and Storage Imported data is encrypted before stored. This feature provides data encryption and decryption APIs for users and uses encryption functions to encrypt sensitive information columns identified by users, so that data can be stored in tables after being encrypted. If you need to encrypt the entire table, you need to write an encryption function for each column. Different attribute columns can use different input parameters. If a user with the required permission wants to view specific data, the user can decrypt required columns using the decryption function API. ### Ledger Database To prevent database O\&M personnel from stealing, tampering with, and erasing traces of the database, you can use the ledger database feature to perform comprehensive audit and trace the history. When a tamper-proof user table is modified, the database records the modification behavior to the history table where only data can be appended. In this way, the operation history can be recorded and the operation source can be traced. The ledger database stores and verifies historical operations by generating data hash digests. Ledgers refer to user history tables and global blockchain tables. For table-level data modification operations, the system records the operation information and hash digest in a global blockchain table. In addition, each tamper-proof user table corresponds to a user history table to record the hash digest of row-level data changes. You can determine whether the user table is tampered by recalculating the hash digest and verifying the hash digest consistency. Each record in the ledger represents a given operation fact that has occurred. The content of the record can only be appended and cannot be modified. The consistency between the tamper-proof user table and the corresponding history table can be checked to identify and track the tampering behavior. In addition, the ledger database provides an API for checking the tamper-proof user table consistency and an API for restoring and archiving history tables to meet the requirements of tampering identification, data expansion and mitigation, and historical data restoration and archiving. ## AI Capabilities ### AI4DB AI4DB includes intelligent parameter tuning and diagnosis, slow SQL discovery, index recommendation, time sequence prediction, and exception detection. It provides users with more convenient O\&M operations and performance improvement, and implements functions such as self-tuning, self-monitoring, and self-diagnosis. ### DB4AI DB4AI is compatible with the MADlib ecosystem, supports more than 70 algorithms, and delivers performance several times higher than that of MADlib on PostgreSQL. Advanced and common algorithm suites such as XGBoost, prophet, and GBDT are added to supplement the shortcomings of the MADlib ecosystem. The technology stack from SQL to machine learning is unified to implement one-click driving of SQL statements from data management to model training. The fenced UDF and native DB4AI algorithm capabilities are provided, including the execution plan, operators, and SQL syntax in the database. ### ABO Optimizer The ABO optimizer features that openGauss uses lightweight machine learning to optimize query plans. The current version provides two functions: intelligent cardinality estimation and adaptive plan selection. * Intelligent cardinality estimation uses the Bayesian network algorithm in the database to improve the cardinality estimation accuracy of multi-column equality query on data with strong correlation between columns by several times, and significantly improves the end-to-end execution efficiency. * Adaptive plan selection uses linear expansion of query selection rate to explore cache plans, and uses query selection rate range to match and select cache plans. This compensates for the defect that the execution plan cannot adapt to a single general cache plan, and avoids the cost caused by frequent calling of query optimization. In typical scenarios, the performance can be improved by several times. --- --- url: /en/docs/latest-lite/database_om_guide/core_fault_locating.md --- # Core Fault Locating ## Core Dump Occurs due to Full Disk Space ### Symptom When TPC-C is running, the disk space is full during injection. As a result, a core dump occurs on the GaussDB process, as shown in the following figure. ![](figures/en-us_image_0289900420.png) ### Cause Analysis When the disk is full, Xlog logs cannot be written. The program exits through the panic log. ### Procedure Externally monitor the disk usage and periodically clean up the disk. ## Core Dump Occurs Due to Incorrect Settings of GUC Parameter log\_directory ### Symptom After the database process is started, a core dump occurs and no log is recorded. ### Cause Analysis The directory specified by GUC parameter **log\_directory** cannot be read or you do not have permissions to access this directory. As a result, the verification fails during the database startup, and the program exits through the panic log. ### Procedure Set **log\_directory** to a valid directory. For details, see [log\_destination](../database_reference/logging_destination.md#en-us_topic_0283136719_en-us_topic_0237124721_en-us_topic_0059778787_sb6c9884f69bd4765a60f80810c94f194). ## Core Dump Occurs when RemoveIPC Is Enabled ### Symptom The **RemoveIPC** parameter in the OS configuration is set to **yes**. The database breaks down during running, and the following log information is displayed: ``` FATAL: semctl(1463124609, 3, SETVAL, 0) failed: Invalid argument ``` ### Cause Analysis If **RemoveIPC** is set to **yes**, the OS deletes the IPC resources (shared memory and semaphore) when the corresponding user exits. As a result, the IPC resources used by the openGauss server are cleared, causing the database to break down. ### Procedure Set **RemoveIPC** to **no**. For details, see **Preparing for Installation** > **Preparing the Software and Hardware Installation Environment** > **Modifying OS Configuration** in *Installation Guide*. --- --- url: /en/docs/latest/resource_pooling/core_fault_locating.md --- # Core Fault Locating ## Core Dump Occurs due to Full Disk Space ### Symptom When TPC-C is running, the disk space is full during injection. As a result, a core dump occurs on the GaussDB process, as shown in the following figure. ![](figures/en-us_image_0289900420.png) ### Cause Analysis When the disk is full, Xlog logs cannot be written. The program exits through the panic log. ### Procedure Externally monitor the disk usage and periodically clean up the disk. ## Core Dump Occurs Due to Incorrect Settings of GUC Parameter log\_directory ### Symptom After the database process is started, a core dump occurs and no log is recorded. ### Cause Analysis The directory specified by GUC parameter **log\_directory** cannot be read or you do not have permissions to access this directory. As a result, the verification fails during the database startup, and the program exits through the panic log. ### Procedure Set **log\_directory** to a valid directory. For details, see [log\_directory](https://docs.opengauss.org/en/docs/latest/database_reference/logging_destination.html#en-us_topic_0283136719_en-us_topic_0237124721_en-us_topic_0059778787_sfbedf09fcf1a4223a4538679f80f12a9). ## Core Dump Occurs when RemoveIPC Is Enabled ### Symptom The **RemoveIPC** parameter in the OS configuration is set to **yes**. The database breaks down during running, and the following log information is displayed: ``` FATAL: semctl(1463124609, 3, SETVAL, 0) failed: Invalid argument ``` ### Cause Analysis If **RemoveIPC** is set to **yes**, the OS deletes the IPC resources (shared memory and semaphore) when the corresponding user exits. As a result, the IPC resources used by the openGauss server are cleared, causing the database to break down. ### Procedure Set **RemoveIPC** to **no**. For details, see **Preparing for Installation** > **Preparing the Software and Hardware Installation Environment** > **Modifying OS Configuration** in the *Installation Guide*. --- --- url: /zh/docs/latest-lite/database_om_guide/core_fault_locating.md --- # core问题定位 ## 磁盘满故障引起的core问题 ### 问题现象 TPCC运行时,注入磁盘满故障,数据库进程gaussdb core掉,如下图所示。 ![](figures/zh-cn_image_0289900420.png) ### 原因分析 数据库本身机制,在磁盘满时,Xlog日志无法进行写入,通过panic日志退出程序。 ### 处理办法 外部监控磁盘使用状况,定时进行清理磁盘。 ## GUC参数log\_directory设置不正确引起的core问题 ### 问题现象 数据库进程拉起后出现coredump,日志无内容。 ### 原因分析 GUC参数log\_directory设置的路径不可读取或无访问权限,数据库在启动过程中进行校验失败,通过panic日志退出程序。 ### 处理办法 GUC参数log\_directory设置为合法路径,具体请参考[log\_directory](../database_reference/logging_destination.md#zh-cn_topic_0283136719_zh-cn_topic_0237124721_zh-cn_topic_0059778787_sfbedf09fcf1a4223a4538679f80f12a9)。 ## 开启RemoveIPC引起的core问题 ### 问题现象 操作系统配置中RemoveIPC参数设置为yes,数据库运行过程中出现宕机,并显示如下日志消息。 ``` FATAL: semctl(1463124609, 3, SETVAL, 0) failed: Invalid argument ``` ### 原因分析 当RemoveIPC参数设置为yes时,操作系统会在对应用户退出时删除IPC资源(共享内存和信号量),从而使得openGauss服务器使用的IPC资源被清理,引发数据库宕机。 ### 处理分析 设置RemoveIPC参数为no。设置方法请参考《安装指南》中“安装准备>准备软硬件安装环境>修改操作系统配置”章节。 --- --- url: /zh/docs/latest/resource_pooling/core_fault_locating.md --- # core问题定位 ## 磁盘满故障引起的core问题 ### 问题现象 TPCC运行时,注入磁盘满故障,数据库进程gaussdb core掉,如下图所示。 ![](figures/zh_image_0289900420.png) ### 原因分析 数据库本身机制,在磁盘满时,Xlog日志无法进行写入,通过panic日志退出程序。 ### 处理办法 外部监控磁盘使用状况,定时进行清理磁盘。 ## GUC参数log\_directory设置不正确引起的core问题 ### 问题现象 数据库进程拉起后出现coredump,日志无内容。 ### 原因分析 GUC参数log\_directory设置的路径不可读取或无访问权限,数据库在启动过程中进行校验失败,通过panic日志退出程序。 ### 处理办法 GUC参数log\_directory设置为合法路径,具体请参考[log\_directory](https://docs.opengauss.org/zh/docs/latest/database_reference/logging_destination.html#zh-cn_topic_0283136719_zh-cn_topic_0237124721_zh-cn_topic_0059778787_sfbedf09fcf1a4223a4538679f80f12a9)。 ## 开启RemoveIPC引起的core问题 ### 问题现象 操作系统配置中RemoveIPC参数设置为yes,数据库运行过程中出现宕机,并显示如下日志消息。 ``` FATAL: semctl(1463124609, 3, SETVAL, 0) failed: Invalid argument ``` ### 原因分析 当RemoveIPC参数设置为yes时,操作系统会在对应用户退出时删除IPC资源(共享内存和信号量),从而使得openGauss服务器使用的IPC资源被清理,引发数据库宕机。 ### 处理分析 设置RemoveIPC参数为no。设置方法请参考《安装指南》中“安装准备>准备软硬件安装环境>修改操作系统配置”章节。 --- --- url: /en/docs/latest-lite/database_reference/cost_based_vacuum_delay.md --- # Cost-based Vacuum Delay This feature allows administrators to reduce the I/O impact of the **VACUUM** and **ANALYZE** statements on concurrent database activities. It is often more important to prevent maintenance statements, such as **VACUUM** and **ANALYZE**, from affecting other database operations than to run them quickly. Cost-based vacuum delay provides a way for administrators to achieve this purpose. > \[!TIP]NOTICE > > Certain vacuum operations hold critical locks and should be complete as quickly as possible. In openGauss, cost-based vacuum delays do not take effect during such operations. To avoid uselessly long delays in such cases, the actual delay is the larger of the two calculated values: > > * **vacuum\_cost\_delay** x **accumulated\_balance**/**vacuum\_cost\_limit** > * **vacuum\_cost\_delay** x 4 ## Background During the execution of the [ANALYZE | ANALYSE](../sql_reference/analyze_analyse.md) and [VACUUM](../sql_reference/vacuum.md) statements, the system maintains an internal counter that keeps track of the estimated cost of the various I/O operations that are performed. When the accumulated cost reaches a limit (specified by **vacuum\_cost\_limit**), the process performing the operation will sleep for a short period of time (specified by **vacuum\_cost\_delay**). Then, the counter resets and the operation continues. By default, this feature is disabled. To enable this feature, set **vacuum\_cost\_delay** to a non-zero value. ## vacuum\_cost\_delay **Parameter description**: Specifies the length of time that a process will sleep when **vacuum\_cost\_limit** has been exceeded. On many systems, the effective resolution of the sleep length is 10 milliseconds. Therefore, setting this parameter to a value that is not a multiple of 10 has the same effect as setting it to the next higher multiple of 10. This parameter is usually set to a small value, such as 10 or 20 milliseconds. Adjusting vacuum's resource consumption is best done by changing other vacuum cost parameters. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 100. A positive number enables cost-based vacuum delay and **0** disables cost-based vacuum delay. **Default value**: **0** ## vacuum\_cost\_page\_hit **Parameter description**: Specifies the estimated cost for vacuuming a buffer found in the shared buffer. It represents the cost to lock the buffer pool, look up the shared hash table, and scan the content of the page. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 10000 **Default value**: **1** ## vacuum\_cost\_page\_miss **Parameter description**: Specifies the estimated cost for vacuuming a buffer read from the disk. It represents the cost to lock the buffer pool, look up the shared hash table, read the desired block from the disk, and scan the block. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 10000 **Default value:** **10** ## vacuum\_cost\_page\_dirty **Parameter description**: Specifies the estimated cost charged when vacuum modifies a block that was previously clean. It represents the extra cost required to update the dirty block out to the disk again. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 10000 **Default value:** **20** ## vacuum\_cost\_limit **Parameter description**: Specifies the cost limit. The vacuuming process will sleep if this limit is exceeded. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to 10000 **Default value**: **200** --- --- url: /en/docs/latest/database_reference/cost_based_vacuum_delay.md --- # Cost-based Vacuum Delay This feature allows administrators to reduce the I/O impact of the **VACUUM** and **ANALYZE** statements on concurrent database activities. It is often more important to prevent maintenance statements, such as **VACUUM** and **ANALYZE**, from affecting other database operations than to run them quickly. Cost-based vacuum delay provides a way for administrators to achieve this purpose. > \[!TIP]NOTICE > Certain vacuum operations hold critical locks and should be complete as quickly as possible. In openGauss, cost-based vacuum delays do not take effect during such operations. To avoid uselessly long delays in such cases, the actual delay is the larger of the two calculated values: > > * **vacuum\_cost\_delay** x **accumulated\_balance**/**vacuum\_cost\_limit** > * **vacuum\_cost\_delay** x 4 ## Background During the execution of the [ANALYZE | ANALYSE](../sql_reference/analyze_analyse.md) and [VACUUM](../sql_reference/vacuum.md) statements, the system maintains an internal counter that keeps track of the estimated cost of the various I/O operations that are performed. When the accumulated cost reaches a limit (specified by **vacuum\_cost\_limit**), the process performing the operation will sleep for a short period of time (specified by **vacuum\_cost\_delay**). Then, the counter resets and the operation continues. By default, this feature is disabled. To enable this feature, set **vacuum\_cost\_delay** to a non-zero value. ## vacuum\_cost\_delay **Parameter description**: Specifies the length of time that a process will sleep when **vacuum\_cost\_limit** has been exceeded. On many systems, the effective resolution of the sleep length is 10 milliseconds. Therefore, setting this parameter to a value that is not a multiple of 10 has the same effect as setting it to the next higher multiple of 10. This parameter is usually set to a small value, such as 10 or 20 milliseconds. Adjusting vacuum's resource consumption is best done by changing other vacuum cost parameters. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 100. A positive number enables cost-based vacuum delay and **0** disables cost-based vacuum delay. **Default value**: 0 ## vacuum\_cost\_page\_hit **Parameter description**: Specifies the estimated cost for vacuuming a buffer found in the shared buffer. It represents the cost to lock the buffer pool, look up the shared hash table, and scan the content of the page. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 10000 **Default value**: **1** ## vacuum\_cost\_page\_miss **Parameter description**: Specifies the estimated cost for vacuuming a buffer read from the disk. It represents the cost to lock the buffer pool, look up the shared hash table, read the desired block from the disk, and scan the block. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 10000 **Default value:** **10** ## vacuum\_cost\_page\_dirty **Parameter description**: Specifies the estimated cost charged when vacuum modifies a block that was previously clean. It represents the extra cost required to update the dirty block out to the disk again. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 0 to 10000 **Default value:** **20** ## vacuum\_cost\_limit **Parameter description**: Specifies the cost limit. The vacuuming process will sleep if this limit is exceeded. This parameter is a USERSET parameter. Set it based on instructions provided in [Table 1](../database_administration_guide/reset_parameters.md#en-us_topic_0283137176_en-us_topic_0237121562_en-us_topic_0059777490_t91a6f212010f4503b24d7943aed6d846). **Value range**: an integer ranging from 1 to 10000 **Default value**: 200 --- --- url: /zh/docs/latest-lite/sql_reference/coverage_proc_coverage.md --- # coverage.proc\_coverage proc\_coverage表记录存储过程覆盖率信息。只能在系统库中查询到结果,在用户库中无法查询。 **表 1** proc\_coverage表属性 |名称|类型|描述| |--|--|--| |coverage\_id|bigint|覆盖率信息序号| |pro\_oid|oid|存储过程oid| |pro\_name|text|存储过程名称| |db\_name|text|存储过程所在数据库名称| |pro\_querys|text|存储过程源语句| |pro\_canbreak|boolean\[]|布尔数组,下标对应源语句行号,当前行是否支持断点(可执行)| |coverage|integer\[]|int数组,下标对应源语句行号,当前行执行次数| > \[!NOTE]说明 > > 1. 该表为unlogged表,当数据库未正常退出时,其中的数据会丢失。 > > 2. 该表为unlogged表,发生主备切换时,新主机上只存在表结构,无数据。 --- --- url: /zh/docs/latest/sql_reference/coverage_proc_coverage.md --- # coverage.proc\_coverage proc\_coverage表记录存储过程覆盖率信息。只能在系统库中查询到结果,在用户库中无法查询。 **表 1** proc\_coverage表属性 |名称|类型|描述| |--|--|--| |coverage\_id|bigint|覆盖率信息序号| |pro\_oid|oid|存储过程oid| |pro\_name|text|存储过程名称| |db\_name|text|存储过程所在数据库名称| |pro\_querys|text|存储过程源语句| |pro\_canbreak|boolean\[]|布尔数组,下标对应源语句行号,当前行是否支持断点(可执行)| |coverage|integer\[]|int数组,下标对应源语句行号,当前行执行次数| > \[!NOTE]说明 > > 1. 该表为unlogged表,当数据库未正常退出时,其中的数据会丢失。 > > 2. 该表为unlogged表,发生主备切换时,新主机上只存在表结构,无数据。 --- --- url: /en/docs/latest-lite/performance_tuning_guide/cpu.md --- # CPU You can run the **top** command to check the CPU usage of each node in openGauss and analyze whether performance bottleneck caused by heavy CPU load exists. The **top** command is used to monitor the Linux OS status. It is a common performance analysis tool and can display the resource usage of each process in the system in real time. Parameter description: -**-d**: number of seconds, indicating the interval for updating the page displayed by running the **top** command. The default value is 5 seconds. **-b**: executes the **top** command in batches. **-n**: This parameter is used together with **-b** to indicate the number of times that the **top** command is executed. **-p**: specifies a PID for observation. ## Checking CPU Usage You can query the CPU usage of the server in the following ways: On each storage node, run the **top** command to check the CPU usage. Then, press **1** to view the usage of each CPU core. ``` top - 17:05:04 up 32 days, 20:34, 5 users, load average: 0.02, 0.02, 0.00 Tasks: 124 total, 1 running, 123 sleeping, 0 stopped, 0 zombie Cpu0 : 0.0%us, 0.3%sy, 0.0%ni, 69.7%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu1 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu2 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu3 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 8038844k total, 7165272k used, 873572k free, 530444k buffers Swap: 4192924k total, 4920k used, 4188004k free, 4742904k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 35184 omm 20 0 822m 421m 128m S 0 5.4 5:28.15 gaussdb 1 root 20 0 13592 820 784 S 0 0.0 1:16.62 init ``` In the command output, focus on the CPU usage occupied by each process. **us** indicates the CPU percentage occupied by the user space, **sy** indicates the CPU percentage occupied by the kernel space, and **id** indicates the idle CPU percentage. If **id** is less than 10%, the CPU load is high. In this case, you can reduce the CPU load by reducing the number of tasks on nodes. ## Analyzing Performance Parameters 1. Run the **top-H** command to check the CPU usage. The following is displayed: ``` 14 root 20 0 0 0 0 S 0 0.0 0:16.41 events/3 top - 14:22:49 up 5 days, 21:51, 2 users, load average: 0.08, 0.08, 0.06 Tasks: 312 total, 1 running, 311 sleeping, 0 stopped, 0 zombie Cpu(s): 1.3%us, 0.7%sy, 0.0%ni, 95.0%id, 2.4%wa, 0.5%hi, 0.2%si, 0.0%st Mem: 8038844k total, 5317668k used, 2721176k free, 180268k buffers Swap: 4192924k total, 0k used, 4192924k free, 2886860k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 3105 root 20 0 50492 11m 2708 S 3 0.1 22:22.56 acc-snf 4015 gdm 20 0 232m 23m 11m S 0 0.3 11:34.70 gdm-simple-gree 51001 omm 20 0 12140 1484 948 R 0 0.0 0:00.94 top 54885 omm 20 0 615m 396m 116m S 0 5.1 0:09.44 gaussdb 1 root 20 0 13592 944 792 S 0 0.0 0:08.54 init ``` 2. In the query result for **Cpu(s)**, check whether the system CPU (**sy**) or user CPU (**us**) usage is high. * If the system CPU usage is too high, you need to identify the abnormal system processes and handle them. * If the CPU usage of the openGauss process whose **USER** is **omm** is too high, optimize the service-related SQL statements based on the running services queries. Based on the features of the currently running service, perform the following operations to check whether this process containing infinite loop logics. 1. Run the **top -H -p pid** command to identify the threads that use much CPU in the process. ``` top -H -p 54952 ``` The threads causing high CPU usage are displayed in the **top** column of the command output. In this section, thread **54775** is used as an example for analyzing the causes of the high CPU usage. ``` top - 14:23:27 up 5 days, 21:52, 2 users, load average: 0.04, 0.07, 0.05 Tasks: 13 total, 0 running, 13 sleeping, 0 stopped, 0 zombie Cpu(s): 0.9%us, 0.4%sy, 0.0%ni, 97.3%id, 1.1%wa, 0.2%hi, 0.1%si, 0.0%st Mem: 8038844k total, 5322180k used, 2716664k free, 180316k buffers Swap: 4192924k total, 0k used, 4192924k free, 2889860k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 54775 omm 20 0 684m 424m 131m S 0 5.4 0:00.32 gaussdb 54951 omm 20 0 684m 424m 131m S 0 5.4 0:00.84 gaussdb 54732 omm 20 0 684m 424m 131m S 0 5.4 0:00.24 gaussdb 54758 omm 20 0 684m 424m 131m S 0 5.4 0:00.00 gaussdb 54759 omm 20 0 684m 424m 131m S 0 5.4 0:00.02 gaussdb 54773 omm 20 0 684m 424m 131m S 0 5.4 0:02.79 gaussdb 54780 omm 20 0 684m 424m 131m S 0 5.4 0:00.04 gaussdb 54781 omm 20 0 684m 424m 131m S 0 5.4 0:00.21 gaussdb 54782 omm 20 0 684m 424m 131m S 0 5.4 0:00.02 gaussdb 54798 omm 20 0 684m 424m 131m S 0 5.4 0:16.70 gaussdb 54952 omm 20 0 684m 424m 131m S 0 5.4 0:07.51 gaussdb 54953 omm 20 0 684m 424m 131m S 0 5.4 0:00.81 gaussdb 54954 omm 20 0 684m 424m 131m S 0 5.4 0:06.54 gaussdb ``` 2. Run the following command to view the function invocation stack for each thread in the process. Check the ID of the thread that occupies high CPU usage in the previous step. If the **gstack** command does not exist in the OS by default, you can install it. ``` gstack 54954 ``` The query result is as follows. The thread number for the thread ID **54775** is **10**. ``` 192.168.0.11:~ # gstack 54954 Thread 10 (Thread 0x7f95a5fff710 (LWP 54775)): #0 0x00007f95c41d63c6 in poll () from /lib64/libc.so.6 #1 0x0000000000d3d2d3 in WaitLatchOrSocket(Latch volatile*, int, int, long) () #2 0x000000000095ed25 in XLogPageRead(XLogRecPtr*, int, bool, bool) () #3 0x000000000095f6dd in ReadRecord(XLogRecPtr*, int, bool) () #4 0x000000000096aef0 in StartupXLOG() () #5 0x0000000000d5607a in StartupProcessMain() () #6 0x00000000009e19f9 in AuxiliaryProcessMain(int, char**) () #7 0x0000000000d50135 in SubPostmasterMain(int, char**) () #8 0x0000000000d504ec in MainStarterThreadFunc(void*) () #9 0x00007f95c79b85f0 in start_thread () from /lib64/libpthread.so.0 #10 0x00007f95c41df84d in clone () from /lib64/libc.so.6 #11 0x0000000000000000 in ?? () ``` --- --- url: /en/docs/latest/performance_tuning_guide/cpu.md --- # CPU You can run the **top** command to check the CPU usage of each node in openGauss and analyze whether performance bottleneck caused by heavy CPU load exists. The **top** command is used to monitor the Linux OS status. It is a common performance analysis tool and can display the resource usage of each process in the system in real time. Description * **-d**: number of seconds, indicating the interval for updating the page displayed by running the **top** command. The default value is 5 seconds. * **-b**: executes the **top** command in batches. * **-n**: This parameter is used together with **-b** to indicate the number of times that the **top** command is executed. * **-p**: specifies a PID for observation. ## Checking CPU Usage You can query the CPU usage of the server in the following ways: On each storage node, run the **top** command to check the CPU usage. Then, press **1** to view the usage of each CPU core. ``` top - 17:05:04 up 32 days, 20:34, 5 users, load average: 0.02, 0.02, 0.00 Tasks: 124 total, 1 running, 123 sleeping, 0 stopped, 0 zombie Cpu0 : 0.0%us, 0.3%sy, 0.0%ni, 69.7%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu1 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu2 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu3 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 8038844k total, 7165272k used, 873572k free, 530444k buffers Swap: 4192924k total, 4920k used, 4188004k free, 4742904k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 35184 omm 20 0 822m 421m 128m S 0 5.4 5:28.15 gaussdb 1 root 20 0 13592 820 784 S 0 0.0 1:16.62 init ``` In the command output, focus on the CPU usage occupied by each process. **us** indicates the CPU percentage occupied by the user space, **sy** indicates the CPU percentage occupied by the kernel space, and **id** indicates the idle CPU percentage. If **id** is less than 10%, the CPU load is high. In this case, you can reduce the CPU load by reducing the number of tasks on nodes. ## Analyzing Performance Parameters 1. Run the **top-H** command to check the CPU usage. The following is displayed: ``` 14 root 20 0 0 0 0 S 0 0.0 0:16.41 events/3 top - 14:22:49 up 5 days, 21:51, 2 users, load average: 0.08, 0.08, 0.06 Tasks: 312 total, 1 running, 311 sleeping, 0 stopped, 0 zombie Cpu(s): 1.3%us, 0.7%sy, 0.0%ni, 95.0%id, 2.4%wa, 0.5%hi, 0.2%si, 0.0%st Mem: 8038844k total, 5317668k used, 2721176k free, 180268k buffers Swap: 4192924k total, 0k used, 4192924k free, 2886860k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 3105 root 20 0 50492 11m 2708 S 3 0.1 22:22.56 acc-snf 4015 gdm 20 0 232m 23m 11m S 0 0.3 11:34.70 gdm-simple-gree 51001 omm 20 0 12140 1484 948 R 0 0.0 0:00.94 top 54885 omm 20 0 615m 396m 116m S 0 5.1 0:09.44 gaussdb 1 root 20 0 13592 944 792 S 0 0.0 0:08.54 init ``` 2. In the query result for **Cpu(s)**, check whether the system CPU (**sy**) or user CPU (**us**) usage is high. * If the system CPU usage is too high, you need to identify the abnormal system processes and handle them. * If the CPU usage of the openGauss process whose **USER** is **omm** is too high, optimize the service-related SQL statements based on the running services queries. Based on the features of the currently running service, perform the following operations to check whether this process containing infinite loop logics. 1. Run the **top -H -p pid** command to identify the threads that use much CPU in the process. ``` top -H -p 54952 ``` The threads causing high CPU usage are displayed in the **top** column of the command output. In this section, thread **54775** is used as an example for analyzing the causes of the high CPU usage. ``` top - 14:23:27 up 5 days, 21:52, 2 users, load average: 0.04, 0.07, 0.05 Tasks: 13 total, 0 running, 13 sleeping, 0 stopped, 0 zombie Cpu(s): 0.9%us, 0.4%sy, 0.0%ni, 97.3%id, 1.1%wa, 0.2%hi, 0.1%si, 0.0%st Mem: 8038844k total, 5322180k used, 2716664k free, 180316k buffers Swap: 4192924k total, 0k used, 4192924k free, 2889860k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 54775 omm 20 0 684m 424m 131m S 0 5.4 0:00.32 gaussdb 54951 omm 20 0 684m 424m 131m S 0 5.4 0:00.84 gaussdb 54732 omm 20 0 684m 424m 131m S 0 5.4 0:00.24 gaussdb 54758 omm 20 0 684m 424m 131m S 0 5.4 0:00.00 gaussdb 54759 omm 20 0 684m 424m 131m S 0 5.4 0:00.02 gaussdb 54773 omm 20 0 684m 424m 131m S 0 5.4 0:02.79 gaussdb 54780 omm 20 0 684m 424m 131m S 0 5.4 0:00.04 gaussdb 54781 omm 20 0 684m 424m 131m S 0 5.4 0:00.21 gaussdb 54782 omm 20 0 684m 424m 131m S 0 5.4 0:00.02 gaussdb 54798 omm 20 0 684m 424m 131m S 0 5.4 0:16.70 gaussdb 54952 omm 20 0 684m 424m 131m S 0 5.4 0:07.51 gaussdb 54953 omm 20 0 684m 424m 131m S 0 5.4 0:00.81 gaussdb 54954 omm 20 0 684m 424m 131m S 0 5.4 0:06.54 gaussdb ``` 2. Run the following command to view the function invocation stack for each thread in the process. Check the thread number for the ID of the thread that occupies high CPU usage in the last step. ``` gstack 54954 ``` The query result is as follows. The thread number for the thread ID **54775** is **10**. ``` 192.168.0.11:~ # gstack 54954 Thread 10 (Thread 0x7f95a5fff710 (LWP 54775)): #0 0x00007f95c41d63c6 in poll () from /lib64/libc.so.6 #1 0x0000000000d3d2d3 in WaitLatchOrSocket(Latch volatile*, int, int, long) () #2 0x000000000095ed25 in XLogPageRead(XLogRecPtr*, int, bool, bool) () #3 0x000000000095f6dd in ReadRecord(XLogRecPtr*, int, bool) () #4 0x000000000096aef0 in StartupXLOG() () #5 0x0000000000d5607a in StartupProcessMain() () #6 0x00000000009e19f9 in AuxiliaryProcessMain(int, char**) () #7 0x0000000000d50135 in SubPostmasterMain(int, char**) () #8 0x0000000000d504ec in MainStarterThreadFunc(void*) () #9 0x00007f95c79b85f0 in start_thread () from /lib64/libpthread.so.0 #10 0x00007f95c41df84d in clone () from /lib64/libc.so.6 #11 0x0000000000000000 in ?? () ``` --- --- url: /zh/docs/latest-lite/performance_tuning_guide/CPU.md --- # CPU 通过top命令查看openGauss内节点CPU使用情况,分析是否存在由于CPU负载过高导致的性能瓶颈。 top命令经常用来监控linux的系统状况,是常用的性能分析工具,能够实时显示系统中各个进程的资源占用情况。 参数解释: -d:number代表秒数,表示top命令显示的页面更新一次的间隔。默认是5秒。 -b:以批次的方式执行top。 -n:与-b配合使用,表示需要进行几次top命令的输出结果。 -p:指定特定的pid进程号进行观察。 ## 查看CPU状况 查询服务器CPU的使用情况主要通过以下方式: 在所有存储节点,逐一执行**top**命令,查看CPU占用情况。执行该命令后,按“1”键,可查看每个CPU核的使用率。 ``` top - 17:05:04 up 32 days, 20:34, 5 users, load average: 0.02, 0.02, 0.00 Tasks: 124 total, 1 running, 123 sleeping, 0 stopped, 0 zombie Cpu0 : 0.0%us, 0.3%sy, 0.0%ni, 69.7%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu1 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu2 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu3 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 8038844k total, 7165272k used, 873572k free, 530444k buffers Swap: 4192924k total, 4920k used, 4188004k free, 4742904k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 35184 omm 20 0 822m 421m 128m S 0 5.4 5:28.15 gaussdb 1 root 20 0 13592 820 784 S 0 0.0 1:16.62 init ``` 分析时,请主要关注进程占用的CPU利用率。 其中,统计信息中“us”表示用户空间占用CPU百分比,“sy”表示内核空间占用CPU百分比,“id”表示空闲CPU百分比。如果“id”低于10%,即表明CPU负载较高,可尝试通过降低本节点任务量等手段降低CPU负载。 ## 性能参数分析 1. 使用“top -H”命令查看CPU,显示内容如下所示。 ``` 14 root 20 0 0 0 0 S 0 0.0 0:16.41 events/3 top - 14:22:49 up 5 days, 21:51, 2 users, load average: 0.08, 0.08, 0.06 Tasks: 312 total, 1 running, 311 sleeping, 0 stopped, 0 zombie Cpu(s): 1.3%us, 0.7%sy, 0.0%ni, 95.0%id, 2.4%wa, 0.5%hi, 0.2%si, 0.0%st Mem: 8038844k total, 5317668k used, 2721176k free, 180268k buffers Swap: 4192924k total, 0k used, 4192924k free, 2886860k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 3105 root 20 0 50492 11m 2708 S 3 0.1 22:22.56 acc-snf 4015 gdm 20 0 232m 23m 11m S 0 0.3 11:34.70 gdm-simple-gree 51001 omm 20 0 12140 1484 948 R 0 0.0 0:00.94 top 54885 omm 20 0 615m 396m 116m S 0 5.1 0:09.44 gaussdb 1 root 20 0 13592 944 792 S 0 0.0 0:08.54 init ``` 2. 根据查询结果中“Cpu(s)”分析是系统CPU(sy)还是用户CPU(us)占用过高。 * 如果是系统CPU占用过高,需要查找异常系统进程进行处理。 * 如果是“USER”为omm的openGauss进程CPU占用过高,请根据目前运行的业务查询内容,对业务SQL进行优化。请根据以下步骤,并结合当前正在运行的业务特征进行分析,是否该程序处于死循环逻辑。 1. 使用“top -H -p pid”查找进程内占用的CPU百分比较高的线程,进行分析。 ``` top -H -p 54952 ``` 查询结果如下所示,top中可以看到占用CPU很高的线程,下面以线程54775为主,分析其为何占用CPU过高。 ``` top - 14:23:27 up 5 days, 21:52, 2 users, load average: 0.04, 0.07, 0.05 Tasks: 13 total, 0 running, 13 sleeping, 0 stopped, 0 zombie Cpu(s): 0.9%us, 0.4%sy, 0.0%ni, 97.3%id, 1.1%wa, 0.2%hi, 0.1%si, 0.0%st Mem: 8038844k total, 5322180k used, 2716664k free, 180316k buffers Swap: 4192924k total, 0k used, 4192924k free, 2889860k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 54775 omm 20 0 684m 424m 131m S 0 5.4 0:00.32 gaussdb 54951 omm 20 0 684m 424m 131m S 0 5.4 0:00.84 gaussdb 54732 omm 20 0 684m 424m 131m S 0 5.4 0:00.24 gaussdb 54758 omm 20 0 684m 424m 131m S 0 5.4 0:00.00 gaussdb 54759 omm 20 0 684m 424m 131m S 0 5.4 0:00.02 gaussdb 54773 omm 20 0 684m 424m 131m S 0 5.4 0:02.79 gaussdb 54780 omm 20 0 684m 424m 131m S 0 5.4 0:00.04 gaussdb 54781 omm 20 0 684m 424m 131m S 0 5.4 0:00.21 gaussdb 54782 omm 20 0 684m 424m 131m S 0 5.4 0:00.02 gaussdb 54798 omm 20 0 684m 424m 131m S 0 5.4 0:16.70 gaussdb 54952 omm 20 0 684m 424m 131m S 0 5.4 0:07.51 gaussdb 54953 omm 20 0 684m 424m 131m S 0 5.4 0:00.81 gaussdb 54954 omm 20 0 684m 424m 131m S 0 5.4 0:06.54 gaussdb ``` 2. 使用“gstack ”查看进程内各线程的函数调用栈。查找上一步骤中占用CPU较高的线程ID对应的线程号。操作系统中若默认无gstack命令,使用时可自行安装。 ``` gstack 54954 ``` 查询结果如下所示,其中线程ID54775对应线程号是10。 ``` 192.168.0.11:~ # gstack 54954 Thread 10 (Thread 0x7f95a5fff710 (LWP 54775)): #0 0x00007f95c41d63c6 in poll () from /lib64/libc.so.6 #1 0x0000000000d3d2d3 in WaitLatchOrSocket(Latch volatile*, int, int, long) () #2 0x000000000095ed25 in XLogPageRead(XLogRecPtr*, int, bool, bool) () #3 0x000000000095f6dd in ReadRecord(XLogRecPtr*, int, bool) () #4 0x000000000096aef0 in StartupXLOG() () #5 0x0000000000d5607a in StartupProcessMain() () #6 0x00000000009e19f9 in AuxiliaryProcessMain(int, char**) () #7 0x0000000000d50135 in SubPostmasterMain(int, char**) () #8 0x0000000000d504ec in MainStarterThreadFunc(void*) () #9 0x00007f95c79b85f0 in start_thread () from /lib64/libpthread.so.0 #10 0x00007f95c41df84d in clone () from /lib64/libc.so.6 #11 0x0000000000000000 in ?? () ``` --- --- url: /zh/docs/latest/performance_tuning_guide/cpu.md --- # CPU 通过top命令查看openGauss内节点CPU使用情况,分析是否存在由于CPU负载过高导致的性能瓶颈。 top命令经常用来监控linux的系统状况,是常用的性能分析工具,能够实时显示系统中各个进程的资源占用情况。 参数解释: * d:number代表秒数,表示top命令显示的页面更新一次的间隔。默认是5秒。 * b:以批次的方式执行top。 * n:与b配合使用,表示需要进行几次top命令的输出结果。 * p:指定特定的pid进程号进行观察。 ## 查看CPU状况 查询服务器CPU的使用情况主要通过以下方式: 在所有存储节点,逐一执行**top**命令,查看CPU占用情况。执行该命令后,按“1”键,可查看每个CPU核的使用率。 ``` top - 17:05:04 up 32 days, 20:34, 5 users, load average: 0.02, 0.02, 0.00 Tasks: 124 total, 1 running, 123 sleeping, 0 stopped, 0 zombie Cpu0 : 0.0%us, 0.3%sy, 0.0%ni, 69.7%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu1 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu2 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Cpu3 : 0.3%us, 0.3%sy, 0.0%ni, 69.3%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 8038844k total, 7165272k used, 873572k free, 530444k buffers Swap: 4192924k total, 4920k used, 4188004k free, 4742904k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 35184 omm 20 0 822m 421m 128m S 0 5.4 5:28.15 gaussdb 1 root 20 0 13592 820 784 S 0 0.0 1:16.62 init ``` 分析时,请主要关注进程占用的CPU利用率。 其中,统计信息中“us”表示用户空间占用CPU百分比,“sy”表示内核空间占用CPU百分比,“id”表示空闲CPU百分比。如果“id”低于10%,即表明CPU负载较高,可尝试通过降低本节点任务量等手段降低CPU负载。 ## 性能参数分析 1. 使用“top -H”命令查看CPU,显示内容如下所示。 ``` 14 root 20 0 0 0 0 S 0 0.0 0:16.41 events/3 top - 14:22:49 up 5 days, 21:51, 2 users, load average: 0.08, 0.08, 0.06 Tasks: 312 total, 1 running, 311 sleeping, 0 stopped, 0 zombie Cpu(s): 1.3%us, 0.7%sy, 0.0%ni, 95.0%id, 2.4%wa, 0.5%hi, 0.2%si, 0.0%st Mem: 8038844k total, 5317668k used, 2721176k free, 180268k buffers Swap: 4192924k total, 0k used, 4192924k free, 2886860k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 3105 root 20 0 50492 11m 2708 S 3 0.1 22:22.56 acc-snf 4015 gdm 20 0 232m 23m 11m S 0 0.3 11:34.70 gdm-simple-gree 51001 omm 20 0 12140 1484 948 R 0 0.0 0:00.94 top 54885 omm 20 0 615m 396m 116m S 0 5.1 0:09.44 gaussdb 1 root 20 0 13592 944 792 S 0 0.0 0:08.54 init ``` 2. 根据查询结果中“Cpu(s)”分析是系统CPU(sy)还是用户CPU(us)占用过高。 * 如果是系统CPU占用过高,需要查找异常系统进程进行处理。 * 如果是“USER”为omm的openGauss进程CPU占用过高,请根据目前运行的业务查询内容,对业务SQL进行优化。请根据以下步骤,并结合当前正在运行的业务特征进行分析,是否该程序处于死循环逻辑。 a. 使用“top -H -p pid”查找进程内占用的CPU百分比较高的线程,进行分析。 ``` top -H -p 54952 ``` 查询结果如下所示,top中可以看到占用CPU很高的线程,下面以线程54775为主,分析其为何占用CPU过高。 ``` top - 14:23:27 up 5 days, 21:52, 2 users, load average: 0.04, 0.07, 0.05 Tasks: 13 total, 0 running, 13 sleeping, 0 stopped, 0 zombie Cpu(s): 0.9%us, 0.4%sy, 0.0%ni, 97.3%id, 1.1%wa, 0.2%hi, 0.1%si, 0.0%st Mem: 8038844k total, 5322180k used, 2716664k free, 180316k buffers Swap: 4192924k total, 0k used, 4192924k free, 2889860k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 54775 omm 20 0 684m 424m 131m S 0 5.4 0:00.32 gaussdb 54951 omm 20 0 684m 424m 131m S 0 5.4 0:00.84 gaussdb 54732 omm 20 0 684m 424m 131m S 0 5.4 0:00.24 gaussdb 54758 omm 20 0 684m 424m 131m S 0 5.4 0:00.00 gaussdb 54759 omm 20 0 684m 424m 131m S 0 5.4 0:00.02 gaussdb 54773 omm 20 0 684m 424m 131m S 0 5.4 0:02.79 gaussdb 54780 omm 20 0 684m 424m 131m S 0 5.4 0:00.04 gaussdb 54781 omm 20 0 684m 424m 131m S 0 5.4 0:00.21 gaussdb 54782 omm 20 0 684m 424m 131m S 0 5.4 0:00.02 gaussdb 54798 omm 20 0 684m 424m 131m S 0 5.4 0:16.70 gaussdb 54952 omm 20 0 684m 424m 131m S 0 5.4 0:07.51 gaussdb 54953 omm 20 0 684m 424m 131m S 0 5.4 0:00.81 gaussdb 54954 omm 20 0 684m 424m 131m S 0 5.4 0:06.54 gaussdb ``` b. 使用“gstack ”查看进程内各线程的函数调用栈。查找上一步骤中占用CPU较高的线程ID对应的线程号。 ``` gstack 54954 ``` 查询结果如下所示,其中线程ID54775对应线程号是10。 ``` 192.168.0.11:~ # gstack 54954 Thread 10 (Thread 0x7f95a5fff710 (LWP 54775)): #0 0x00007f95c41d63c6 in poll () from /lib64/libc.so.6 #1 0x0000000000d3d2d3 in WaitLatchOrSocket(Latch volatile*, int, int, long) () #2 0x000000000095ed25 in XLogPageRead(XLogRecPtr*, int, bool, bool) () #3 0x000000000095f6dd in ReadRecord(XLogRecPtr*, int, bool) () #4 0x000000000096aef0 in StartupXLOG() () #5 0x0000000000d5607a in StartupProcessMain() () #6 0x00000000009e19f9 in AuxiliaryProcessMain(int, char**) () #7 0x0000000000d50135 in SubPostmasterMain(int, char**) () #8 0x0000000000d504ec in MainStarterThreadFunc(void*) () #9 0x00007f95c79b85f0 in start_thread () from /lib64/libpthread.so.0 #10 0x00007f95c41df84d in clone () from /lib64/libc.so.6 #11 0x0000000000000000 in ?? () ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_access_method.md --- # CREATE ACCESS METHOD ## 功能描述 在当前数据库中创建一种新的访问方法,访问方法名称在数据库中必须唯一,只有超级用户可以定义新的访问方法。 ## 注意事项 * 访问方法当前仅支持INDEX类型。 * 一个索引访问方法的处理器函数必须被声明为接受单一的类型为internal类型的参数并且返回伪类型index\_am\_handler。该参数只是被用来防止从 SQL 命令直接调用处理器函数。该函数的结果必须是一个已经 palloc 过的IndexAmRoutine类型结构,它包含核心代码使用该索引访问方法所需的所有信息。IndexAmRoutine结构(也被称为访问方法的API 结构)中的域指定了该访问方法的各种固定性质,例如它是否支持多列索引。同时,它包含用于该访问方法的支持函数的指针,这些函数会完成真正访问索引的工作(支持函数是纯 C 函数)。 * 新增自定义的访问方法,需要参考内置访问方法,到index.h和transformIndexStmt中增加方法支持(故不建议用户SQL命令中执行)。 ## 语法格式 创建自定义访问方法。 ``` CREATE ACCESS METHOD name TYPE INDEX HANDLER handler_function ``` ## 参数说明 * **name** 新创建的访问方法的名称。 * **handler\_function** handler\_function是一个之前已注册的函数的名称(可能被模式限定),该函数表示要创建的访问方法。处理器函数必须被声明为接收一个单一的internal类型的参数,并且它的返回类型取决于访问方法的类型(INDEX访问方法,它必须是index\_am\_handler)。 处理器函数必须实现的 C 级别 API 取决于访问方法的类型。 ## 示例 ``` - 用处理器函数ivfflathandler创建一种索引访问方法ivfflat: CREATE ACCESS METHOD ivfflat TYPE INDEX HANDLER ivfflathandler; ``` ## 相关链接 [DROP ACCESS METHOD](drop_access_method.md) --- --- url: /zh/docs/latest/sql_reference/create_access_method.md --- # CREATE ACCESS METHOD ## 功能描述 在当前数据库中创建一种新的访问方法,访问方法名称在数据库中必须唯一,只有超级用户可以定义新的访问方法。 ## 注意事项 * 访问方法当前仅支持INDEX类型。 * 一个索引访问方法的处理器函数必须被声明为接受单一的类型为internal类型的参数并且返回伪类型index\_am\_handler。该参数只是被用来防止从 SQL 命令直接调用处理器函数。该函数的结果必须是一个已经 palloc 过的IndexAmRoutine类型结构,它包含核心代码使用该索引访问方法所需的所有信息。IndexAmRoutine结构(也被称为访问方法的API 结构)中的域指定了该访问方法的各种固定性质,例如它是否支持多列索引。同时,它包含用于该访问方法的支持函数的指针,这些函数会完成真正访问索引的工作(支持函数是纯 C 函数)。 * 新增自定义的访问方法,需要参考内置访问方法,到index.h和transformIndexStmt中增加方法支持(故不建议用户SQL命令中执行)。 ## 语法格式 创建自定义访问方法。 ``` CREATE ACCESS METHOD name TYPE INDEX HANDLER handler_function ``` ## 参数说明 * **name** 新创建的访问方法的名称。 * **handler\_function** handler\_function是一个之前已注册的函数的名称(可能被模式限定),该函数表示要创建的访问方法。处理器函数必须被声明为接收一个单一的internal类型的参数,并且它的返回类型取决于访问方法的类型(INDEX访问方法,它必须是index\_am\_handler)。 处理器函数必须实现的 C 级别 API 取决于访问方法的类型。 ## 示例 ``` - 用处理器函数ivfflathandler创建一种索引访问方法ivfflat: CREATE ACCESS METHOD ivfflat TYPE INDEX HANDLER ivfflathandler; ``` ## 相关链接 [DROP ACCESS METHOD](drop_access_method.md) --- --- url: /en/docs/latest-lite/sql_reference/create_aggregate.md --- # CREATE AGGREGATE ## Function **CREATE AGGREGATE** defines a new aggregate function. ## Syntax ``` CREATE AGGREGATE name ( input_data_type [ , ... ] ) ( SFUNC = sfunc, STYPE = state_data_type [ , FINALFUNC = ffunc ] [ , INITCOND = initial_condition ] [ , SORTOP = sort_operator ] ) or the old syntax CREATE AGGREGATE name ( BASETYPE = base_type, SFUNC = sfunc, STYPE = state_data_type [ , FINALFUNC = ffunc ] [ , INITCOND = initial_condition ] [ , SORTOP = sort_operator ] ) ``` ## Parameter Description * **name** Name (optionally schema-qualified) of the aggregate function to be created. * **input\_data\_type** Data type of the input to be processed by the aggregate function. To create a zero-parameter aggregate function, you can use an asterisk (\*) instead of a list of input data types. (count(\*) is an instance of this aggregate function.) * **base\_type** In the **CREATE AGGREGATE** syntax, the input data type is specified by the **basetype** parameter instead of following **name**. Note that the previous syntax allows only one input parameter. To create a zero-parameter aggregate function, you can set **basetype** to **ANY** instead of **\***. * **sfunc** Name of the state conversion function that will be called on each input line. For an aggregate function with N parameters, **sfunc** must have more than one parameter. The first parameter is of the **state\_data\_type** type, and the other parameters match the declared input data types. The function must return a value of the **state\_data\_type** type. This function accepts the current state value and the current input data, and returns the next state value. * **state\_data\_type** Data type of the aggregation status value. * **ffunc** Final processing function called after all the input lines have been converted, which calculates the result of aggregation. This function must accept a parameter of **state\_data\_type**. The output data type of the aggregation is defined as the return type of this function. If **ffunc** is not specified, the state value of the aggregation result is used as the aggregation result, and the output type is **state\_data\_type**. * **initial\_condition** Initial setting (value) of a state value. It must be a text constant value acceptable to **state\_data\_type**. If not specified, the initial state value is **NULL**. * **sort\_operator** Sort operator used for MIN or MAX aggregation. This is just an operator name (optionally schema-qualified). This operator assumes that the input data type is the same as that of aggregation. ## Examples ``` openGauss=# CREATE AGGREGATE array_accum (anyelement) ( sfunc = array_append, stype = anyarray, initcond = '{}' ); ``` --- --- url: /en/docs/latest/sql_reference/create_aggregate.md --- # CREATE AGGREGATE ## Function **CREATE AGGREGATE** defines a new aggregate function. ## Syntax ``` CREATE AGGREGATE name ( input_data_type [ , ... ] ) ( SFUNC = sfunc, STYPE = state_data_type [ , FINALFUNC = ffunc ] [ , INITCOND = initial_condition ] [ , SORTOP = sort_operator ] ) or the old syntax CREATE AGGREGATE name ( BASETYPE = base_type, SFUNC = sfunc, STYPE = state_data_type [ , FINALFUNC = ffunc ] [ , INITCOND = initial_condition ] [ , SORTOP = sort_operator ] ) ``` ## Parameter Description * **name** Name (optionally schema-qualified) of the aggregate function to be created. * **input\_data\_type** Data type of the input to be processed by the aggregate function. To create a zero-parameter aggregate function, you can use an asterisk (\*) instead of a list of input data types. (count(\*) is an instance of this aggregate function.) * **base\_type** In the **CREATE AGGREGATE** syntax, the input data type is specified by the **basetype** parameter instead of following **name**. Note that the previous syntax allows only one input parameter. To create a zero-parameter aggregate function, you can set **basetype** to **ANY** instead of **\***. * **sfunc** Name of the state conversion function that will be called on each input line. For an aggregate function with N parameters, **sfunc** must have more than one parameter. The first parameter is of the **state\_data\_type** type, and the other parameters match the declared input data types. The function must return a value of the **state\_data\_type** type. This function accepts the current state value and the current input data, and returns the next state value. * **state\_data\_type** Data type of the aggregation status value. * **ffunc** Final processing function called after all the input lines have been converted, which calculates the result of aggregation. This function must accept a parameter of **state\_data\_type**. The output data type of the aggregation is defined as the return type of this function. If **ffunc** is not specified, the state value of the aggregation result is used as the aggregation result, and the output type is **state\_data\_type**. * **initial\_condition** Initial setting (value) of a state value. It must be a text constant value acceptable to **state\_data\_type**. If not specified, the initial state value is **NULL**. * **sort\_operator** Sort operator used for MIN or MAX aggregation. This is just an operator name (optionally schema-qualified). This operator assumes that the input data type is the same as that of aggregation. ## Examples ``` openGauss=# CREATE AGGREGATE array_accum (anyelement) ( sfunc = array_append, stype = anyarray, initcond = '{}' ); ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_aggregate.md --- # CREATE AGGREGATE ## 功能描述 定义一个新的聚合函数。 ## 语法格式 ``` CREATE AGGREGATE name ( input_data_type [ , ... ] ) ( SFUNC = sfunc, STYPE = state_data_type [ , FINALFUNC = ffunc ] [ , INITCOND = initial_condition ] [ , SORTOP = sort_operator ] ) or the old syntax CREATE AGGREGATE name ( BASETYPE = base_type, SFUNC = sfunc, STYPE = state_data_type [ , FINALFUNC = ffunc ] [ , INITCOND = initial_condition ] [ , SORTOP = sort_operator ] ) ``` ## 参数说明 * **name** 要创建的聚合函数名(可以有模式修饰) 。 * **input\_data\_type** 该聚合函数要处理的输入数据类型。要创建一个零参数聚合函数,可以使用\*代替输入数据类型列表。 (count(\*)就是这种聚合函数的一个实例。 ) * **base\_type** 在以前的CREATE AGGREGATE语法中,输入数据类型是通过basetype参数指定的,而不是写在聚合的名称之后。 需要注意的是这种以前语法仅允许一个输入参数。 要创建一个零参数聚合函数,可以将basetype指定为"ANY"(而不是\*)。 * **sfunc** 将在每一个输入行上调用的状态转换函数的名称。 对于有N个参数的聚合函数,sfunc必须有 +1 个参数,其中的第一个参数类型为state\_data\_type,其余的匹配已声明的输入数据类型。 函数必须返回一个state\_data\_type类型的值。 这个函数接受当前状态值和当前输入数据,并返回下个状态值。 * **state\_data\_type** 聚合的状态值的数据类型。 * **ffunc** 在转换完所有输入行后调用的最终处理函数,它计算聚合的结果。 此函数必须接受一个类型为state\_data\_type的参数。 聚合的输出数据 类型被定义为此函数的返回类型。 如果没有声明ffunc则使用聚合结果的状态值作为聚合的结果,且输出类型为state\_data\_type。 * **initial\_condition** 状态值的初始设置(值)。 它必须是一个state\_data\_type类型可以接受的文本常量值。 如果没有声明,状态值初始为 NULL 。 * **sort\_operator** 用于MIN或MAX类型聚合的排序操作符。 这个只是一个操作符名 (可以有模式修饰)。这个操作符假设接受和聚合一样的输入数据类型。 ## 示例 ``` openGauss=# CREATE AGGREGATE array_accum (anyelement) ( sfunc = array_append, stype = anyarray, initcond = '{}' ); ``` --- --- url: /zh/docs/latest/sql_reference/create_aggregate.md --- # CREATE AGGREGATE ## 功能描述 定义一个新的聚合函数。 ## 语法格式 ``` CREATE AGGREGATE name ( input_data_type [ , ... ] ) ( SFUNC = sfunc, STYPE = state_data_type [ , FINALFUNC = ffunc ] [ , INITCOND = initial_condition ] [ , SORTOP = sort_operator ] ) or the old syntax CREATE AGGREGATE name ( BASETYPE = base_type, SFUNC = sfunc, STYPE = state_data_type [ , FINALFUNC = ffunc ] [ , INITCOND = initial_condition ] [ , SORTOP = sort_operator ] ) ``` ## 参数说明 * **name** 要创建的聚合函数名(可以有模式修饰) 。 * **input\_data\_type** 该聚合函数要处理的输入数据类型。要创建一个零参数聚合函数,可以使用\*代替输入数据类型列表。(count(\*)就是这种聚合函数的一个实例。) * **base\_type** 在以前的CREATE AGGREGATE语法中,输入数据类型是通过basetype参数指定的,而不是写在聚合的名称之后。 需要注意的是这种以前语法仅允许一个输入参数。 要创建一个零参数聚合函数,可以将basetype指定为“ANY”(而不是\*)。 * **sfunc** 将在每一个输入行上调用的状态转换函数的名称。 对于有N个参数的聚合函数,sfunc必须有 +1 个参数,其中的第一个参数类型为state\_data\_type,其余的匹配已声明的输入数据类型。 函数必须返回一个state\_data\_type类型的值。 这个函数接受当前状态值和当前输入数据,并返回下个状态值。 * **state\_data\_type** 聚合的状态值的数据类型。 * **ffunc** 在转换完所有输入行后调用的最终处理函数,它计算聚合的结果。 此函数必须接受一个类型为state\_data\_type的参数。 聚合的输出数据 类型被定义为此函数的返回类型。 如果没有声明ffunc则使用聚合结果的状态值作为聚合的结果,且输出类型为state\_data\_type。 * **initial\_condition** 状态值的初始设置(值)。 它必须是一个state\_data\_type类型可以接受的文本常量值。 如果没有声明,状态值初始为 NULL 。 * **sort\_operator** 用于MIN或MAX类型聚合的排序操作符。 这个只是一个操作符名 (可以有模式修饰)。这个操作符假设接受和聚合一样的输入数据类型。 ## 示例 ``` openGauss=# CREATE AGGREGATE array_accum (anyelement) ( sfunc = array_append, stype = anyarray, initcond = '{}' ); ``` --- --- url: /en/docs/latest-lite/sql_reference/create_audit_policy.md --- # CREATE AUDIT POLICY ## Function **CREATE AUDIT POLICY** creates a unified audit policy. ## Precautions Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. The masking policy takes effect only after the security policy is enabled, that is, **enable\_security\_policy** is set to **on**. ## Syntax ``` CREATE AUDIT POLICY [ IF NOT EXISTS ] policy_name { { privilege_audit_clause | access_audit_clause } [ filter_group_clause ] [ ENABLE | DISABLE ] }; ``` * privilege\_audit\_clause ``` PRIVILEGES { DDL | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] ``` * access\_audit\_clause ``` ACCESS { DML | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] ``` * filter\_group\_clause ``` FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## Parameter Description * **policy\_name** Specifies the audit policy name, which must be unique. Value range: a string. It must comply with the naming convention. * **DDL** Specifies the operations that are audited within the database: **CREATE**, **ALTER**, **DROP**, **ANALYZE**, **COMMENT**, **GRANT**, **REVOKE**, **SET**, **SHOW**, **LOGIN\_ANY**, **LOGIN\_FAILURE**, **LOGIN\_SUCCESS**, and **LOGOUT**. * **ALL** Indicates all operations supported by the specified DDL statements in the database. * **resource\_label\_name** Specifies the resource label name. * **DML** Specifies the operations that are audited within the database: **SELECT**, **COPY**, **DEALLOCATE**, **DELETE**, **EXECUTE**, **INSERT**, **PREPARE**, **REINDEX**, **TRUNCATE**, and **UPDATE**. * **FILTER\_TYPE** Specifies the types of information to be filtered by the audit, including **IP**, **APP**, and **ROLES**. * **filter\_value** Indicates the detailed information to be filtered. * **ENABLE|DISABLE** Enables or disables the unified audit policy. If **ENABLE|DISABLE** is not specified, **ENABLE** is used by default. ## Examples ``` -- Create users dev_audit and bob_audit. openGauss=# CREATE USER dev_audit PASSWORD 'xxxxxx'; CREATE USER bob_audit password 'xxxxxx'; -- Create table tb_for_audit. openGauss=# CREATE TABLE tb_for_audit(col1 text, col2 text, col3 text); -- Create a resource label. openGauss=# CREATE RESOURCE LABEL adt_lb0 add TABLE(tb_for_audit); -- Perform the CREATE operation on the database to create an audit policy. openGauss=# CREATE AUDIT POLICY adt1 PRIVILEGES CREATE; -- Perform the SELECT operation on the database to create an audit policy. openGauss=# CREATE AUDIT POLICY adt2 ACCESS SELECT; -- Create an audit policy to audit only the CREATE operations performed on the adt_lb0 resource by users dev_audit and bob_audit. openGauss=# CREATE AUDIT POLICY adt3 PRIVILEGES CREATE ON LABEL(adt_lb0) FILTER ON ROLES(dev_audit, bob_audit); -- Create an audit policy to audit only the SELECT, INSERT, and DELETE operations performed on the adt_lb0 resource by users dev_audit and bob_audit using client tools psql and gsql on the servers whose IP addresses are 10.20.30.40 and 127.0.0.0/24. openGauss=# CREATE AUDIT POLICY adt4 ACCESS SELECT ON LABEL(adt_lb0), INSERT ON LABEL(adt_lb0), DELETE FILTER ON ROLES(dev_audit, bob_audit), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24'); ``` ## Helpful Links [ALTER AUDIT POLICY](alter_audit_policy.md) and [DROP AUDIT POLICY](drop_audit_policy.md) --- --- url: /en/docs/latest/sql_reference/create_audit_policy.md --- # CREATE AUDIT POLICY ## Function **CREATE AUDIT POLICY** creates a unified audit policy. ## Precautions Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. The masking policy takes effect only after the security policy is enabled, that is, **enable\_security\_policy** is set to **on**. For details, see "Database Configuration > Database Security Management Policies > Unified Auditing" in *Security Hardening Guide*. ## Syntax ``` CREATE AUDIT POLICY [ IF NOT EXISTS ] policy_name { { privilege_audit_clause | access_audit_clause } [ filter_group_clause ] [ ENABLE | DISABLE ] }; ``` * privilege\_audit\_clause ``` PRIVILEGES { DDL | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] ``` * access\_audit\_clause ``` ACCESS { DML | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] ``` * filter\_group\_clause ``` FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## Parameter Description * **policy\_name** Specifies the audit policy name, which must be unique. Value range: a string. It must comply with the naming convention. * **DDL** Specifies the operations that are audited within the database: **CREATE**, **ALTER**, **DROP**, **ANALYZE**, **COMMENT**, **GRANT**, **REVOKE**, **SET**, **SHOW**, **LOGIN\_ANY**, **LOGIN\_FAILURE**, **LOGIN\_SUCCESS**, and **LOGOUT**. * **ALL** Indicates all operations supported by the specified DDL statements in the database. * **resource\_label\_name** Specifies the resource label name. * **DML** Specifies the operations that are audited within the database: **SELECT**, **COPY**, **DEALLOCATE**, **DELETE**, **EXECUTE**, **INSERT**, **PREPARE**, **REINDEX**, **TRUNCATE**, and **UPDATE**. * **FILTER\_TYPE** Specifies the types of information to be filtered by the audit, including **IP**, **APP**, and **ROLES**. * **filter\_value** Indicates the detailed information to be filtered. * **ENABLE|DISABLE** Enables or disables the unified audit policy. If **ENABLE|DISABLE** is not specified, **ENABLE** is used by default. ## Examples ``` -- Create users dev_audit and bob_audit. openGauss=# CREATE USER dev_audit PASSWORD 'xxxxxx'; CREATE USER bob_audit password 'xxxxxx'; -- Create table tb_for_audit. openGauss=# CREATE TABLE tb_for_audit(col1 text, col2 text, col3 text); -- Create a resource label. openGauss=# CREATE RESOURCE LABEL adt_lb0 add TABLE(tb_for_audit); -- Perform the CREATE operation on the database to create an audit policy. openGauss=# CREATE AUDIT POLICY adt1 PRIVILEGES CREATE; -- Perform the SELECT operation on the database to create an audit policy. openGauss=# CREATE AUDIT POLICY adt2 ACCESS SELECT; -- Create an audit policy to audit only the CREATE operations performed on the adt_lb0 resource by users dev_audit and bob_audit. openGauss=# CREATE AUDIT POLICY adt3 PRIVILEGES CREATE ON LABEL(adt_lb0) FILTER ON ROLES(dev_audit, bob_audit); -- Create an audit policy to audit only the SELECT, INSERT, and DELETE operations performed on the adt_lb0 resource by users dev_audit and bob_audit using client tools psql and gsql on the servers whose IP addresses are 10.20.30.40 and 127.0.0.0/24. openGauss=# CREATE AUDIT POLICY adt4 ACCESS SELECT ON LABEL(adt_lb0), INSERT ON LABEL(adt_lb0), DELETE FILTER ON ROLES(dev_audit, bob_audit), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24'); ``` ## Helpful Links [ALTER AUDIT POLICY](alter_audit_policy.md) and [DROP AUDIT POLICY](drop_audit_policy.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_audit_policy.md --- # CREATE AUDIT POLICY ## 功能描述 创建统一审计策略。 ## 注意事项 只有poladmin,sysadmin或初始用户能进行此操作。 需要开启安全策略开关,即设置GUC参数enable\_security\_policy=on,脱敏策略才可以生效。 ## 语法格式 ``` CREATE AUDIT POLICY [ IF NOT EXISTS ] policy_name { { privilege_audit_clause | access_audit_clause } [ filter_group_clause ] [ ENABLE | DISABLE ] }; ``` * privilege\_audit\_clause: ``` PRIVILEGES { DDL | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] ``` * access\_audit\_clause: ``` ACCESS { DML | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] ``` * filter\_group\_clause: ``` FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## 参数说明 * **policy\_name** 审计策略名称,需要唯一,不可重复; 取值范围:字符串,要符合标识符的命名规范。 * **DDL** 指的是针对数据库执行如下操作时进行审计,目前支持:CREATE、ALTER、DROP、ANALYZE、COMMENT、GRANT、REVOKE、SET、SHOW。 * **ALL** 指的是上述DDL支持的所有对数据库的操作。 * **resource\_label\_name** 资源标签名称。 * **DML** 指的是针对数据库执行如下操作时进行审计,目前支持:SELECT、COPY、DEALLOCATE、DELETE、EXECUTE、INSERT、PREPARE、REINDEX、TRUNCATE、UPDATE。 * **FILTER\_TYPE** 描述策略过滤的条件类型,包括IP | APP | ROLES。 * **filter\_value** 指具体过滤信息内容。 * **ENABLE|DISABLE** 可以打开或关闭统一审计策略。若不指定ENABLE|DISABLE,语句默认为ENABLE。 ## 示例 ``` --创建dev_audit和bob_audit用户。 openGauss=# CREATE USER dev_audit PASSWORD 'xxxxxx'; CREATE USER bob_audit password 'xxxxxx'; --创建一个表tb_for_audit openGauss=# CREATE TABLE tb_for_audit(col1 text, col2 text, col3 text); --创建资源标签 openGauss=# CREATE RESOURCE LABEL adt_lb0 add TABLE(tb_for_audit); --对数据库执行create操作创建审计策略 openGauss=# CREATE AUDIT POLICY adt1 PRIVILEGES CREATE; --对数据库执行select操作创建审计策略 openGauss=# CREATE AUDIT POLICY adt2 ACCESS SELECT; --仅审计记录用户dev_audit和bob_audit在执行针对adt_lb0资源进行的create操作数据库创建审计策略 openGauss=# CREATE AUDIT POLICY adt3 PRIVILEGES CREATE ON LABEL(adt_lb0) FILTER ON ROLES(dev_audit, bob_audit); --仅审计记录用户dev_audit和bob_audit,客户端工具为psql和gsql,IP地址为'10.20.30.40', '127.0.0.0/24',在执行针对adt_lb0资源进行的select、insert、delete操作数据库创建审计策略。 openGauss=# CREATE AUDIT POLICY adt4 ACCESS SELECT ON LABEL(adt_lb0), INSERT ON LABEL(adt_lb0), DELETE FILTER ON ROLES(dev_audit, bob_audit), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24'); ``` ## 相关链接 [ALTER AUDIT POLICY](alter_audit_policy.md) [DROP AUDIT POLICY](drop_audit_policy.md)。 --- --- url: /zh/docs/latest/sql_reference/create_audit_policy.md --- # CREATE AUDIT POLICY ## 功能描述 创建统一审计策略。 ## 注意事项 只有poladmin、sysadmin或初始用户能进行此操作。 需要开启安全策略开关,即设置GUC参数enable\_security\_policy=on,审计策略才可以生效。 ## 语法格式 ``` CREATE AUDIT POLICY [ IF NOT EXISTS ] policy_name { { privilege_audit_clause | access_audit_clause } [ filter_group_clause ] [ ENABLE | DISABLE ] }; ``` * privilege\_audit\_clause: ``` PRIVILEGES { DDL | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] ``` * access\_audit\_clause: ``` ACCESS { DML | ALL } [ ON LABEL ( resource_label_name [, ... ] ) ] ``` * filter\_group\_clause: ``` FILTER ON { ( FILTER_TYPE ( filter_value [, ... ] ) ) [, ... ] } ``` ## 参数说明 * **policy\_name** 审计策略名称,需要唯一,不可重复; 取值范围:字符串,要符合标识符的命名规范。 * **DDL** 指的是针对数据库执行如下操作时进行审计,目前支持:CREATE、ALTER、DROP、ANALYZE、COMMENT、GRANT、REVOKE、SET、SHOW。 * **ALL** 指的是上述DDL支持的所有对数据库的操作。 * **resource\_label\_name** 资源标签名称。 * **DML** 指的是针对数据库执行如下操作时进行审计,目前支持:SELECT、COPY、DEALLOCATE、DELETE、EXECUTE、INSERT、PREPARE、REINDEX、TRUNCATE、UPDATE。 * **FILTER\_TYPE** 描述策略过滤的条件类型,包括IP | APP | ROLES。 * **filter\_value** 指具体过滤信息内容。 * **ENABLE|DISABLE** 可以打开或关闭统一审计策略。若不指定ENABLE|DISABLE,语句默认为ENABLE。 ## 示例 ``` --创建dev_audit和bob_audit用户。 openGauss=# CREATE USER dev_audit PASSWORD 'xxxxxx'; CREATE USER bob_audit password 'xxxxxx'; --创建一个表tb_for_audit openGauss=# CREATE TABLE tb_for_audit(col1 text, col2 text, col3 text); --创建资源标签 openGauss=# CREATE RESOURCE LABEL adt_lb0 add TABLE(tb_for_audit); --对数据库执行create操作创建审计策略 openGauss=# CREATE AUDIT POLICY adt1 PRIVILEGES CREATE; --对数据库执行select操作创建审计策略 openGauss=# CREATE AUDIT POLICY adt2 ACCESS SELECT; --仅审计记录用户dev_audit和bob_audit在执行针对adt_lb0资源进行的create操作数据库创建审计策略 openGauss=# CREATE AUDIT POLICY adt3 PRIVILEGES CREATE ON LABEL(adt_lb0) FILTER ON ROLES(dev_audit, bob_audit); --仅审计记录用户dev_audit和bob_audit,客户端工具为psql和gsql,IP地址为'10.20.30.40', '127.0.0.0/24',在执行针对adt_lb0资源进行的select、insert、delete操作数据库创建审计策略。 openGauss=# CREATE AUDIT POLICY adt4 ACCESS SELECT ON LABEL(adt_lb0), INSERT ON LABEL(adt_lb0), DELETE FILTER ON ROLES(dev_audit, bob_audit), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24'); ``` ## 相关链接 [ALTER AUDIT POLICY](alter_audit_policy.md) [DROP AUDIT POLICY](drop_audit_policy.md)。 --- --- url: /en/docs/latest-lite/sql_reference/create_cast.md --- # CREATE CAST ## Function CREATE CAST defines a conversion. ## Syntax ``` CREATE CAST (source_type AS target_type) WITH FUNCTION function_name (argument_type [, ...]) [ AS ASSIGNMENT | AS IMPLICIT ] CREATE CAST (source_type AS target_type) WITHOUT FUNCTION [ AS ASSIGNMENT | AS IMPLICIT ] CREATE CAST (source_type AS target_type) WITH INOUT [ AS ASSIGNMENT | AS IMPLICIT ] ``` ## Parameter Description * **source\_type** Type of the source data to be converted. * **target\_type** Type of the target data to be converted. * **function\_name(argument\_type \[, ...])** Function used for conversion. The function name can be modified with a schema name. If it is not modified with a schema name, the function will be found in the schema search path. The result data type of the function must match the target type of the conversion. Its parameters are discussed below. * **WITHOUT FUNCTION** Indicates that the source type is a binary castable to the target type, so no function is needed to perform this conversion. * **WITH INOUT** Indicates that the conversion is an I/O conversion, which is performed by calling the output function of the source data type and transferring the result to the input function of the target data type. * **AS ASSIGNMENT** Indicates that the conversion can be implicitly called in assignment mode. * **AS IMPLICIT** Indicates that the transformation can be implicitly called in any environment. A conversion implementation function can have one to three parameters. The type of the first parameter must be the same as that of the source type to be converted, or can be forcibly converted from the binary of the source type to be converted. If the second parameter exists, it must be of the integer type. It receives these type modifiers associated with the target type, or **-1** if nothing is present. If the third parameter exists, it must be of the Boolean type. If the conversion is an explicit type conversion, **true** is received. Otherwise, **false** is received. The return type of a conversion function must be the same as the target type of the conversion, or the binary of the target type of the conversion can be forcibly converted. Typically, a transformation must have different source and target data types. However, if there is a conversion implementation function with more than one parameter, it is allowed to declare a conversion with the same source and target types. This is used to represent a length enforcement function of a specific type in the system catalog. The named function is used to force a value of this type to be the type modifier value given by the second parameter. If the source type and target type of a type conversion are different and more than one parameter is received, it indicates that only one step is required to convert one type to another and the length conversion is performed at the same time. If no such item is available, converting to a type that uses a type modifier involves two steps, one to convert between data types, and the other to apply a conversion specified by the modifier. Currently, domain type conversion does not take effect. Transformations are typically targeted to the domain-related data types to which they belong. ## Example To create an assignment mapping from type bigint to type int4, use the int4(bigint) function: ``` CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT; ``` (The conversion has been predefined in the system.) ## Compatibility The CREATE CAST instruction complies with the SQL standard. Except that the SQL does not have extra parameters that can be forcibly converted to binary types or implement functions. --- --- url: /en/docs/latest/sql_reference/create_cast.md --- # CREATE CAST ## Function CREATE CAST defines a conversion. ## Syntax ``` CREATE CAST (source_type AS target_type) WITH FUNCTION function_name (argument_type [, ...]) [ AS ASSIGNMENT | AS IMPLICIT ] CREATE CAST (source_type AS target_type) WITHOUT FUNCTION [ AS ASSIGNMENT | AS IMPLICIT ] CREATE CAST (source_type AS target_type) WITH INOUT [ AS ASSIGNMENT | AS IMPLICIT ] ``` ## Parameter Description * **source\_type** Type of the source data to be converted. * **target\_type** Type of the target data to be converted. * **function\_name(argument\_type \[, ...])** Function used for conversion. The function name can be modified with a schema name. If it is not modified with a schema name, the function will be found in the schema search path. The result data type of the function must match the target type of the conversion. Its parameters are discussed below. * **WITHOUT FUNCTION** Indicates that the source type is a binary castable to the target type, so no function is needed to perform this conversion. * **WITH INOUT** Indicates that the conversion is an I/O conversion, which is performed by calling the output function of the source data type and transferring the result to the input function of the target data type. * **AS ASSIGNMENT** Indicates that the conversion can be implicitly called in assignment mode. * **AS IMPLICIT** Indicates that the transformation can be implicitly called in any environment. A conversion implementation function can have one to three parameters. The type of the first parameter must be the same as that of the source type to be converted, or can be forcibly converted from the binary of the source type to be converted. If the second parameter exists, it must be of the integer type. It receives these type modifiers associated with the target type, or **-1** if nothing is present. If the third parameter exists, it must be of the Boolean type. If the conversion is an explicit type conversion, **true** is received. Otherwise, **false** is received. The return type of a conversion function must be the same as the target type of the conversion, or the binary of the target type of the conversion can be forcibly converted. Typically, a transformation must have different source and target data types. However, if there is a conversion implementation function with more than one parameter, it is allowed to declare a conversion with the same source and target types. This is used to represent a length enforcement function of a specific type in the system catalog. The named function is used to force a value of this type to be the type modifier value given by the second parameter. If the source type and target type of a type conversion are different and more than one parameter is received, it indicates that only one step is required to convert one type to another and the length conversion is performed at the same time. If no such item is available, converting to a type that uses a type modifier involves two steps, one to convert between data types, and the other to apply a conversion specified by the modifier. Currently, domain type conversion does not take effect. Transformations are typically targeted to the domain-related data types to which they belong. ## Example To create an assignment mapping from type bigint to type int4, use the int4(bigint) function: ``` CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT; ``` (The conversion has been predefined in the system.) ## Compatibility The CREATE CAST instruction complies with the SQL standard. Except that the SQL does not have extra parameters that can be forcibly converted to binary types or implement functions. --- --- url: /zh/docs/latest-lite/sql_reference/create_cast.md --- # CREATE CAST ## 功能描述 定义一个用户自定义的转换。 ## 语法格式 ``` CREATE CAST (source_type AS target_type) WITH FUNCTION function_name (argument_type [, ...]) [ AS ASSIGNMENT | AS IMPLICIT ] CREATE CAST (source_type AS target_type) WITHOUT FUNCTION [ AS ASSIGNMENT | AS IMPLICIT ] CREATE CAST (source_type AS target_type) WITH INOUT [ AS ASSIGNMENT | AS IMPLICIT ] ``` ## 参数说明 * **source\_type** 转换的源数据类型。 * **target\_type** 转换的目标数据类型。 * **function\_name(argument\_type \[, ...])** 用于执行转换的函数。 这个函数名可以是用模式名修饰的。 如果它没有用模式名修饰, 那么该函数将从模式搜索路径中找出来。 函数的结果数据类型必须匹配转换的目标类型。 它的参数在下面讨论。 * **WITHOUT FUNCTION** 表明源类型是对目标类型是二进制可强制转换的,所以没有函数需要执行此转换。 * **WITH INOUT** 表明转换是I/O转换,通过调用源数据类型的输出函数来执行,并将结果传给目标数据类型的输入函数。 * **AS ASSIGNMENT** 表示转换可以在赋值模式下隐含调用。 * **AS IMPLICIT** 表示转换可以在任何环境里隐含调用。 转换实现函数可以有一到三个参数。 第一个参数的类型必须与转换的源类型相同的,或可以从转换的源类型二进制可强制转换的。 第二个参数,如果存在,必须是integer类型;它接收这些与目标类型相关联的类型修饰符,或者若什么都没有则是-1。 第三个参数,如果存在,必须是boolean类型;若转换是一个显式类型转换则会收到true,否则是false。 一个转换函数的返回类型必须是与转换的目标类型相同或者对转换的目标类型二进制可强制转换 。 通常,一个转换必须有不同的源和目标数据类型。 然而,若有多于一个参数的转换实现函数,则允许声明一个有相同的源和目标类型的转换。 这用于表示系统目录中的特定类型的长度强制函数。 命名的函数用于强制一个该类型的值为第二个参数给出的类型修饰符值。 如果一个类型转换的源类型和目标类型不同,并且接收多于一个参数,它就表示从一种类型转换成另外一种类型只用一个步骤,并且同时实施长度转换。 如果没有这样的项可用, 那么转换成一个使用了类型修饰词的类型将涉及两个步骤,一个是在数据类型之间转换, 另外一个是施加修饰词指定的转换。 对域类型的转换目前没有作用。转换一般是针对域相关的所属数据类型。 ## 示例 为了从类型bigint到类型int4创建一个指派映射要通过使用函数int4(bigint): ``` CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT; ``` (这个转换在系统中已经预先定义了。) --- --- url: /zh/docs/latest/sql_reference/create_cast.md --- # CREATE CAST ## 功能描述 定义一个用户自定义的转换。 ## 语法格式 ``` CREATE CAST (source_type AS target_type) WITH FUNCTION function_name (argument_type [, ...]) [ AS ASSIGNMENT | AS IMPLICIT ] CREATE CAST (source_type AS target_type) WITHOUT FUNCTION [ AS ASSIGNMENT | AS IMPLICIT ] CREATE CAST (source_type AS target_type) WITH INOUT [ AS ASSIGNMENT | AS IMPLICIT ] ``` ## 参数说明 * **source\_type** 转换的源数据类型。 * **target\_type** 转换的目标数据类型。 * **function\_name(argument\_type \[, ...])** 用于执行转换的函数。这个函数名可以是用模式名修饰的。如果它没有用模式名修饰,那么该函数将从模式搜索路径中找出来。函数的结果数据类型必须匹配转换的目标类型。 它的参数在下面讨论。 * **WITHOUT FUNCTION** 表明源类型是对目标类型是二进制可强制转换的,所以没有函数需要执行此转换。 * **WITH INOUT** 表明转换是I/O转换,通过调用源数据类型的输出函数来执行,并将结果传给目标数据类型的输入函数。 * **AS ASSIGNMENT** 表示转换可以在赋值模式下隐含调用。 * **AS IMPLICIT** 表示转换可以在任何环境里隐含调用。 转换实现函数可以有一到三个参数。第一个参数的类型必须与转换的源类型相同的,或可以从转换的源类型二进制可强制转换的。第二个参数,如果存在,必须是integer类型;它接收这些与目标类型相关联的类型修饰符,或者若什么都没有则是-1。第三个参数,如果存在,必须是boolean类型;若转换是一个显式类型转换则会收到true,否则是false。 一个转换函数的返回类型必须是与转换的目标类型相同或者对转换的目标类型二进制可强制转换 。 通常,一个转换必须有不同的源和目标数据类型。然而,若有多于一个参数的转换实现函数,则允许声明一个有相同的源和目标类型的转换。这用于表示系统目录中的特定类型的长度强制函数。命名的函数用于强制一个该类型的值为第二个参数给出的类型修饰符值。 如果一个类型转换的源类型和目标类型不同,并且接收多于一个参数,它就表示从一种类型转换成另外一种类型只用一个步骤,并且同时实施长度转换。如果没有这样的项可用, 那么转换成一个使用了类型修饰词的类型将涉及两个步骤,一个是在数据类型之间转换, 另外一个是施加修饰词指定的转换。 对域类型的转换目前没有作用。转换一般是针对域相关的所属数据类型。 ## 示例 为了从类型bigint到类型int4创建一个指派映射要通过使用函数int4(bigint): ``` CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT; ``` (这个转换在系统中已经预先定义了。) ## 兼容性 CREATE CAST指令符合SQL标准,除了SQL没有为二进制可强制转换类型或者实现函数的额外参数来实现功能。 --- --- url: /en/docs/latest-lite/sql_reference/create_client_master_key.md --- # CREATE CLIENT MASTER KEY ## Function **CREATE CLIENT MASTER KEY** creates a CMK object that can be used to encrypt a CEK object. ## Precautions This syntax is specific to a fully-encrypted database. When using **gsql** to connect to a database server, you need to use the **-C** parameter to enable the fully-encrypted database. In the CMK object created using this syntax, only the method for reading keys from independent key management tools, services, or components is stored. The key itself is not stored. > \[!NOTE]NOTE > > In the Lite scenario, openGauss provides this syntax, but encrypted database-related functions are unavailable. ## Syntax ``` CREATE CLIENT MASTER KEY client_master_key_name WITH (KEY_STORE = key_store_name, KEY_PATH = "key_path_value", ALGORITHM = algorithm_type) ``` ## Parameter Description * **client\_master\_key\_name** This parameter is used as the name of a key object. In the same namespace, the value of this parameter must be unique. Value range: a string. It must comply with the identifier naming convention. * **KEY\_STORE** Specifies the key tool or component that manages CMKs. Currently, only **localkms** is supported. * **KEY\_PATH** **KEY\_STORE** manages multiple CMKs. The **KEY\_PATH** option is used to uniquely identify a CMK in **KEY\_STORE**. The value is similar to that of **key\_path\_value**. * **ALGORITHM** Type of the encryption algorithm used to encrypt CEKs. Value range: **RSA\_2048**, **RSA\_3072**, and **SM2**. > \[!NOTE]NOTE > > **Key storage path**: By default, **localkms** generates, reads, or deletes a key file in the *$LOCALKMS***\_FILE\_PATH** path. You can manually configure this environment variable. However, you do not need to configure this environment variable separately. When failing to obtain $LOCALKMS\_FILE\_PATH, **localkms** attempts to obtain the *$GAUSSHOME***/etc/localkms/** path. If the path exists, it is used as the key storage path. > **Key-related file name**: When the **CREATE CMK** syntax is used, **localkms** creates four files related to key paths. For example, when **KEY\_PATH** is set to **key\_path\_value**, the names of the four files are **key\_path\_value.pub**, **key\_path\_value.pub.rand**, **key\_path\_value.priv**, and **key\_path\_value.priv.rand**. > Therefore, to successfully create key-related files, ensure that no file with the same name as the key-related files exists in the key path. ## Examples ``` -- (1) Use the common account alice to connect to the fully-encrypted database. [cmd] gsql -U alice -h $host -p $port -d $database -C -r -- (2) Use this syntax to create a CMK object. openGauss=> CREATE CLIENT MASTER KEY a_cmk WITH (KEY_STORE = localkms, KEY_PATH = "key_path_value", ALGORITHM = RSA_2048); openGauss=> CREATE CLIENT MASTER KEY another_cmk WITH (KEY_STORE = localkms, KEY_PATH = "another_path_value", ALGORITHM = SM2); ``` --- --- url: /en/docs/latest/sql_reference/create_client_master_key.md --- # CREATE CLIENT MASTER KEY ## Function **CREATE CLIENT MASTER KEY** creates a CMK object that can be used to encrypt a CEK object. ## Precautions This syntax is specific to a fully-encrypted database. When using **gsql** to connect to a database server, you need to use the **-C** parameter to enable the fully-encrypted database. In the CMK object created using this syntax, only the method for reading keys from independent key management tools, services, or components is stored. The key itself is not stored. ## Syntax ``` CREATE CLIENT MASTER KEY client_master_key_name WITH (KEY_STORE = key_store_name, KEY_PATH = "key_path_value", ALGORITHM = algorithm_type) ``` ## Parameter Description * **client\_master\_key\_name** This parameter is used as the name of a key object. In the same namespace, the value of this parameter must be unique. Value range: a string. It must comply with the identifier naming convention. * **KEY\_STORE** Specifies the key tool or component that manages CMKs. Currently, only **localkms** is supported. * **KEY\_PATH** **KEY\_STORE** manages multiple CMKs. The **KEY\_PATH** option is used to uniquely identify a CMK in **KEY\_STORE**. The value is similar to that of **key\_path\_value**. * **ALGORITHM** Type of the encryption algorithm used to encrypt CEKs. Value range: **RSA\_2048**, **RSA\_3072**, and **SM2**. > \[!NOTE]NOTE > **Key storage path**: By default, **localkms** generates, reads, or deletes a key file in the *$LOCALKMS***\_FILE\_PATH** path. You can manually configure this environment variable. However, you do not need to configure this environment variable separately. When failing to obtain $LOCALKMS\_FILE\_PATH, **localkms** attempts to obtain the *$GAUSSHOME***/etc/localkms/** path. If the path exists, it is used as the key storage path. > **Key-related file name**: When the **CREATE CMK** syntax is used, **localkms** creates four files related to key paths. For example, when **KEY\_PATH** is set to **key\_path\_value**, the names of the four files are **key\_path\_value.pub**, **key\_path\_value.pub.rand**, **key\_path\_value.priv**, and **key\_path\_value.priv.rand**. > Therefore, to successfully create key-related files, ensure that no file with the same name as the key-related files exists in the key path. ## Examples ``` -- (1) Use the common account alice to connect to the fully-encrypted database. [cmd] gsql -U alice -h $host -p $port -d $database -C -r -- (2) Use this syntax to create a CMK object. openGauss=> CREATE CLIENT MASTER KEY a_cmk WITH (KEY_STORE = localkms, KEY_PATH = "key_path_value", ALGORITHM = RSA_2048); openGauss=> CREATE CLIENT MASTER KEY another_cmk WITH (KEY_STORE = localkms, KEY_PATH = "another_path_value", ALGORITHM = SM2); ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_client_master_key.md --- # CREATE CLIENT MASTER KEY ## 功能描述 创建一个客户端主密钥对象,该对象可用于加密Column Encryption Key对象。 ## 注意事项 本语法属于全密态数据库特有语法。 当使用gsql连接数据库服务器时,需使用‘-C’参数,打开全密态数据库的开关,才能使用本语法。 由本语法创建的CMK对象中,仅存储从独立的密钥管理工具/服务/组件中读取密钥的方法,而不存储密钥本身。 > \[!NOTE]说明 > 轻量版场景下,openGauss提供此语法,但密态数据库相关功能不可用。 ## 语法格式 ``` CREATE CLIENT MASTER KEY client_master_key_name WITH (KEY_STORE = key_store_name, KEY_PATH = "key_path_value", ALGORITHM = algorithm_type) ``` ## 参数说明 * **client\_master\_key\_name** 该参数作为密钥对象名,在同一命名空间下,需满足命名唯一性约束。 取值范围:字符串,需符合标识符的命名规范。 * **KEY\_STORE** 指定管理CMK的密钥工具或组件;取值:目前仅支持localkms。 * **KEY\_PATH** KEY\_STORE负责管理多个CMK密钥,KEY\_PATH选项用于在KEY\_STORE中唯一标识CMK。取值类似:“key\_path\_value”。 * **ALGORITHM** 由本语法创建的用于加密COLUMN ENCRYPTION KEY,该参数用于指定加密算法的类型。取值范围:RSA\_2048、RSA\_3072和SM2。 > \[!NOTE]说明 > **密钥存储路径:** 默认情况下,localkms将在$LOCALKMS\_FILE\_PATH路径下生成/读取/删除密钥文件,用户可手动配置该环境变量。但是,用户也可以不用单独配置该环境变量,在尝试获取$LOCALKMS\_FILE\_PATH失败时,localkms会尝试获取$GAUSSHOME/etc/localkms/路径,如果该路径存在,则将其作为密钥存储路径。 > **密钥相关文件名:** 使用CREATE CMK语法时,localkms将会创建四个与存储密钥相关的文件。示例:当KEY\_PATH = "key\_path\_value", 四个文件的名称分别为key\_path\_value.pub、key\_path\_value.pub.rand、 key\_path\_value.priv、 key\_path\_value.priv.rand。 > 所以,为了能够成功创建密钥相关文件,在密钥存储路径下,应该保证没有已存在的与密钥相关文件名同名的文件。 ## 示例 ``` -- (1)使用普通账户alice,连接全密态数据库, [cmd] gsql -U alice -h $host -p $port -d $database -C -r -- (2)使用本语法创建客户端加密主密钥(CMK)对象 openGauss=> CREATE CLIENT MASTER KEY a_cmk WITH (KEY_STORE = localkms, KEY_PATH = "key_path_value", ALGORITHM = RSA_2048); openGauss=> CREATE CLIENT MASTER KEY another_cmk WITH (KEY_STORE = localkms, KEY_PATH = "another_path_value", ALGORITHM = SM2); ``` --- --- url: /zh/docs/latest/sql_reference/create_client_master_key.md --- # CREATE CLIENT MASTER KEY ## 功能描述 创建一个客户端主密钥对象,该对象可用于加密Column Encryption Key对象。 ## 注意事项 本语法属于全密态数据库特有语法。 当使用gsql连接数据库服务器时,需使用‘-C’参数,打开全密态数据库的开关,才能使用本语法。 由本语法创建的CMK对象中,仅存储从独立的密钥管理工具/服务/组件中读取密钥的方法,而不存储密钥本身。 ## 语法格式 ``` CREATE CLIENT MASTER KEY client_master_key_name WITH (KEY_STORE = key_store_name, KEY_PATH = "key_path_value", ALGORITHM = algorithm_type) ``` ## 参数说明 * **client\_master\_key\_name** 该参数作为密钥对象名,在同一命名空间下,需满足命名唯一性约束。 取值范围:字符串,需符合标识符的命名规范。 * **KEY\_STORE** 指定管理CMK的密钥工具或组件;取值:目前仅支持localkms。 * **KEY\_PATH** KEY\_STORE负责管理多个CMK密钥,KEY\_PATH选项用于在KEY\_STORE中唯一标识CMK。取值类似:“key\_path\_value”。 * **ALGORITHM** 由本语法创建的用于加密COLUMN ENCRYPTION KEY,该参数用于指定加密算法的类型。取值范围:RSA\_2048、RSA\_3072和SM2。 > \[!NOTE]说明 > > **密钥存储路径:** 默认情况下,localkms将在$LOCALKMS\_FILE\_PATH路径下生成/读取/删除密钥文件,用户可手动配置该环境变量。但是,用户也可以不用单独配置该环境变量,在尝试获取$LOCALKMS\_FILE\_PATH失败时,localkms会尝试获取$GAUSSHOME/etc/localkms/路径,如果该路径存在,则将其作为密钥存储路径。 > > **密钥相关文件名:** 使用CREATE CMK语法时,localkms将会创建四个与存储密钥相关的文件。示例:当KEY\_PATH = "key\_path\_value", 四个文件的名称分别为key\_path\_value.pub、key\_path\_value.pub.rand、 key\_path\_value.priv、 key\_path\_value.priv.rand。 > 所以,为了能够成功创建密钥相关文件,在密钥存储路径下,应该保证没有已存在的与密钥相关文件名同名的文件。 ## 示例 ``` -- (1)使用普通账户alice,连接全密态数据库, [cmd] gsql -U alice -h $host -p $port -d $database -C -r -- (2)使用本语法创建客户端加密主密钥(CMK)对象 openGauss=> CREATE CLIENT MASTER KEY a_cmk WITH (KEY_STORE = localkms, KEY_PATH = "key_path_value", ALGORITHM = RSA_2048); openGauss=> CREATE CLIENT MASTER KEY another_cmk WITH (KEY_STORE = localkms, KEY_PATH = "another_path_value", ALGORITHM = SM2); ``` --- --- url: /en/docs/latest-lite/sql_reference/create_column_encryption_key.md --- # CREATE COLUMN ENCRYPTION KEY ## Function **CREATE COLUMN ENCRYPTION KEY** creates a CEK that can be used to encrypt a specified column in a table. ## Precautions This syntax is specific to a fully-encrypted database. When using **gsql** to connect to a database server, you need to use the -C parameter to enable the fully-encrypted database. The CEK object created using this syntax can be used for column-level encryption. When defining a column in a table, you can specify a CEK object to encrypt the column. > \[!NOTE]NOTE > > In the Lite scenario, openGauss provides this syntax, but encrypted database-related functions are unavailable. ## Syntax ``` CREATE COLUMN ENCRYPTION KEY column_encryption_key_name WITH VALUES(CLIENT_MASTER_KEY = client_master_key_name, ALGORITHM = algorithm_type, ENCRYPTED_VALUE = encrypted_value); ``` ## Parameter Description * **column\_encryption\_key\_name** This parameter is used as the name of a key object. In the same namespace, the value of this parameter must be unique. Value range: a string. It must comply with the naming convention. * **CLIENT\_MASTER\_KEY** Specifies the CMK used to encrypt the CEK. The value is the CMK object name, which is created using the **CREATE CLIENT MASTER KEY** syntax. * **ALGORITHM** Encryption algorithm to be used by the CEK. The value can be **AEAD\_AES\_256\_CBC\_HMAC\_SHA256**, **AEAD\_AES\_128\_CBC\_HMAC\_SHA256**, or **SM4\_SM3**. * **ENCRYPTED\_VALUE (optional)** A key password specified by a user. The key password length ranges from 28 to 256 characters. The derived 28-character key meets the AES128 security requirements. If the user needs to use AES256, the key password length must be 39 characters. If the user does not specify the key password length, a 256-character key is automatically generated. > \[!TIP]NOTICE > > Chinese National Cryptography Standard (Guomi) constraints: SM2, SM3, and SM4 are Chinese national cryptography standards. To avoid legal risks, these algorithms must be used together. If you specify the SM2 algorithm to encrypt CEKs when creating a CMK, you must specify the SM3 and SM4 algorithms (SM4\_SM3) to encrypt data when creating CEKs. ## Examples ``` -- Create a CEK. openGauss=> CREATE COLUMN ENCRYPTION KEY a_cek WITH VALUES (CLIENT_MASTER_KEY = a_cmk, ALGORITHM = AEAD_AES_256_CBC_HMAC_SHA256); CREATE COLUMN ENCRYPTION KEY openGauss=> CREATE COLUMN ENCRYPTION KEY another_cek WITH VALUES (CLIENT_MASTER_KEY = a_cmk, ALGORITHM = SM4_SM3); CREATE COLUMN ENCRYPTION KEY ``` --- --- url: /en/docs/latest/sql_reference/create_column_encryption_key.md --- # CREATE COLUMN ENCRYPTION KEY ## Function **CREATE COLUMN ENCRYPTION KEY** creates a CEK that can be used to encrypt a specified column in a table. ## Precautions This syntax is specific to a fully-encrypted database. When using **gsql** to connect to a database server, you need to use the -C parameter to enable the fully-encrypted database. The CEK object created using this syntax can be used for column-level encryption. When defining a column in a table, you can specify a CEK object to encrypt the column. ## Syntax ``` CREATE COLUMN ENCRYPTION KEY column_encryption_key_name WITH VALUES(CLIENT_MASTER_KEY = client_master_key_name, ALGORITHM = algorithm_type, ENCRYPTED_VALUE = encrypted_value); ``` ## Parameter Description * **column\_encryption\_key\_name** This parameter is used as the name of a key object. In the same namespace, the value of this parameter must be unique. Value range: a string. It must comply with the naming convention. * **CLIENT\_MASTER\_KEY** Specifies the CMK used to encrypt the CEK. The value is the CMK object name, which is created using the **CREATE CLIENT MASTER KEY** syntax. * **ALGORITHM** Encryption algorithm to be used by the CEK. The value can be **AEAD\_AES\_256\_CBC\_HMAC\_SHA256**, **AEAD\_AES\_128\_CBC\_HMAC\_SHA256**, or **SM4\_SM3**. * **ENCRYPTED\_VALUE (optional)** A key password specified by a user. The key password length ranges from 28 to 256 bits. The derived 28-bit key meets the AES128 security requirements. If the user needs to use AES256, the key password length must be 39 bits. If the user does not specify the key password length, a 256-bit key is automatically generated. > \[!TIP]NOTICE > Chinese National Cryptography Standard (Guomi) constraints: SM2, SM3, and SM4 are Chinese national cryptography standards. To avoid legal risks, these algorithms must be used together. If you specify the SM2 algorithm to encrypt CEKs when creating a CMK, you must specify the SM3 and SM4 algorithms (SM4\_SM3) to encrypt data when creating CEKs. ## Examples ``` -- Create a CEK. openGauss=> CREATE COLUMN ENCRYPTION KEY a_cek WITH VALUES (CLIENT_MASTER_KEY = a_cmk, ALGORITHM = AEAD_AES_256_CBC_HMAC_SHA256); CREATE COLUMN ENCRYPTION KEY openGauss=> CREATE COLUMN ENCRYPTION KEY another_cek WITH VALUES (CLIENT_MASTER_KEY = a_cmk, ALGORITHM = SM4_SM3); CREATE COLUMN ENCRYPTION KEY ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_column_encryption_key.md --- # CREATE COLUMN ENCRYPTION KEY ## 功能描述 创建一个列加密密钥,该密钥可用于加密表中指定列。 ## 注意事项 本语法属于全密态数据库特有语法。 当使用gsql连接数据库服务器时,需使用‘-C’参数,打开全密态数据库的开关,才能使用本语法。 由该语法创建CEK对象可用于列级加密。在定义表中列字段时,可指定一个CEK对象,用于加密该列。 > \[!NOTE]说明 > > 轻量版场景下,openGauss提供此语法,但密态数据库相关功能不可用。 ## 语法格式 ``` CREATE COLUMN ENCRYPTION KEY column_encryption_key_name WITH VALUES(CLIENT_MASTER_KEY = client_master_key_name, ALGORITHM = algorithm_type, ENCRYPTED_VALUE = encrypted_value); ``` ## 参数说明 * **column\_encryption\_key\_name** 该参数作为密钥对象名,在同一命名空间下,需满足命名唯一性约束。 取值范围:字符串,要符合标识符的命名规范。 * **CLIENT\_MASTER\_KEY** 指定用于加密本CEK的CMK,取值为:CMK对象名,该CMK对象由CREATE CLIENT MASTER KEY语法创建。 * **ALGORITHM** 指定该CEK将用于何种加密算法,取值范围为:AEAD\_AES\_256\_CBC\_HMAC\_SHA256、AEAD\_AES\_128\_CBC\_HMAC\_SHA256和SM4\_SM3; * **ENCRYPTED\_VALUE(可选项)** 该值为用户指定的密钥口令,密钥口令长度范围为28 ~ 256个字符,28个字符派生出来的密钥安全强度满足AES128,若用户需要用AES256,密钥口令的长度需要39个字符,如果不指定,则会自动生成256字符的密钥。 > \[!TIP]须知 > > 国密算法约束:由于SM2、SM3、SM4等算法属于中国国家密码标准算法,为规避法律风险,需配套使用。如果创建CMK时指定SM2算法来加密CEK,则创建CEK时必须指定SM4\_SM3算法来加密数据。 ## 示例 ``` --创建列加密密钥(CEK) openGauss=> CREATE COLUMN ENCRYPTION KEY a_cek WITH VALUES (CLIENT_MASTER_KEY = a_cmk, ALGORITHM = AEAD_AES_256_CBC_HMAC_SHA256); CREATE COLUMN ENCRYPTION KEY openGauss=> CREATE COLUMN ENCRYPTION KEY another_cek WITH VALUES (CLIENT_MASTER_KEY = a_cmk, ALGORITHM = SM4_SM3); CREATE COLUMN ENCRYPTION KEY ``` --- --- url: /zh/docs/latest/sql_reference/create_column_encryption_key.md --- # CREATE COLUMN ENCRYPTION KEY ## 功能描述 创建一个列加密密钥,该密钥可用于加密表中指定列。 ## 注意事项 本语法属于全密态数据库特有语法。 当使用gsql连接数据库服务器时,需使用‘-C’参数,打开全密态数据库的开关,才能使用本语法。 由该语法创建CEK对象可用于列级加密。在定义表中列字段时,可指定一个CEK对象,用于加密该列。 ## 语法格式 ``` CREATE COLUMN ENCRYPTION KEY column_encryption_key_name WITH VALUES(CLIENT_MASTER_KEY = client_master_key_name, ALGORITHM = algorithm_type, ENCRYPTED_VALUE = encrypted_value); ``` ## 参数说明 * **column\_encryption\_key\_name** 该参数作为密钥对象名,在同一命名空间下,需满足命名唯一性约束。 取值范围:字符串,要符合标识符的命名规范。 * **CLIENT\_MASTER\_KEY** 指定用于加密本CEK的CMK,取值为:CMK对象名,该CMK对象由CREATE CLIENT MASTER KEY语法创建。 * **ALGORITHM** 指定该CEK将用于何种加密算法,取值范围为:AEAD\_AES\_256\_CBC\_HMAC\_SHA256、AEAD\_AES\_128\_CBC\_HMAC\_SHA256和SM4\_SM3; * **ENCRYPTED\_VALUE(可选项)** 该值为用户指定的密钥口令,密钥口令长度范围为28 ~ 256位,28位派生出来的密钥安全强度满足AES128,若用户需要用AES256,密钥口令的长度需要39位,如果不指定,则会自动生成256字符的密钥。 > \[!TIP]须知 > 国密算法约束:由于SM2、SM3、SM4等算法属于中国国家密码标准算法,为规避法律风险,需配套使用。如果创建CMK时指定SM2算法来加密CEK,则创建CEK时必须指定SM4\_SM3算法来加密数据。 ## 示例 ``` --创建列加密密钥(CEK) openGauss=> CREATE COLUMN ENCRYPTION KEY a_cek WITH VALUES (CLIENT_MASTER_KEY = a_cmk, ALGORITHM = AEAD_AES_256_CBC_HMAC_SHA256); CREATE COLUMN ENCRYPTION KEY openGauss=> CREATE COLUMN ENCRYPTION KEY another_cek WITH VALUES (CLIENT_MASTER_KEY = a_cmk, ALGORITHM = SM4_SM3); CREATE COLUMN ENCRYPTION KEY ``` --- --- url: /en/docs/latest-lite/sql_reference/create_data_source.md --- # CREATE DATA SOURCE ## Function **CREATE DATA SOURCE** creates an external data source, which defines the information about the database that openGauss will connect to. ## Precautions * The data source name must be unique in the database and comply with the identifier naming rules. Its length cannot exceed 63 bytes. Otherwise, it will be truncated. * Only the system administrator or initial user has the permission to create data sources. The user who creates the object is the default owner of the object. * If the **password** option is displayed, ensure that the **datasource.key.cipher** and **datasource.key.rand** files exist in the *$GAUSSHOME***/bin** directory of each node in openGauss. If the two files do not exist, use the **gs\_guc** tool to generate them and use the **gs\_ssh** tool to release them to the *$GAUSSHOME***/bin** directory on each node. > \[!NOTE]NOTE > > In the Lite scenario, openGauss provides this syntax, but the SQL on Anywhere capabilities are unavailable. ## Syntax ``` CREATE DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS (optname 'optvalue' [, ...])]; ``` ## Parameter Description * **src\_name** Specifies the name of the new data source, which must be unique in the database. Value range: a string compliant with the identifier naming convention * **TYPE** Specifies the type of the data source. This parameter can be left empty, and its default value will be used. Value range: an empty string or a non-empty string * **VERSION** Specifies the version number of the new data source. This parameter can be left empty or set to null. Value range: an empty string, a non-empty string, or null * **OPTIONS** Specifies the options of the data source. This parameter can be left empty or specified using the following keywords: * optname Specifies the option name. Value range: **dsn**, **username**, **password**, and **encoding**. The value is case-insensitive. * **dsn** corresponds to the DSN in the ODBC configuration file. * **username**/**password** indicates the username and password for connecting to the destination database. The username and password entered by the user are encrypted in the openGauss background to ensure security. The key file required for encryption must be generated using the **gs\_guc** tool and released to the *$GAUSSHOME***/bin** directory of each node in openGauss using the **gs\_ssh** tool. The username and password cannot contain the prefix "encryptOpt". Otherwise, they are considered as encrypted ciphertext. * **encoding** indicates the character string encoding mode used for interaction with the destination database (including the sent SQL statements and returned data of the character type). Its validity is not checked during object creation. Whether data can be encoded and decoded depends on whether the encoding you specified can be used in the database. * optvalue Specifies the option value. Value range: an empty string or a non-empty string ## Examples ``` -- Create an empty data source that does not contain any information. openGauss=# CREATE DATA SOURCE ds_test1; -- Create a data source with TYPE information and VERSION being null. openGauss=# CREATE DATA SOURCE ds_test2 TYPE 'MPPDB' VERSION NULL; -- Create a data source that contains only OPTIONS. openGauss=# CREATE DATA SOURCE ds_test3 OPTIONS (dsn 'openGauss', encoding 'utf8'); -- Create a data source that contains TYPE, VERSION, and OPTIONS. openGauss=# CREATE DATA SOURCE ds_test4 TYPE 'unknown' VERSION '11.2.3' OPTIONS (dsn 'openGauss', username 'userid', password 'xxxxxx', encoding ''); -- Delete the data source. openGauss=# DROP DATA SOURCE ds_test1; openGauss=# DROP DATA SOURCE ds_test2; openGauss=# DROP DATA SOURCE ds_test3; openGauss=# DROP DATA SOURCE ds_test4; ``` ## Helpful Links [ALTER DATA SOURCE](alter_data_source.md) and [DROP DATA SOURCE](drop_data_source.md) --- --- url: /en/docs/latest/sql_reference/create_data_source.md --- # CREATE DATA SOURCE ## Function **CREATE DATA SOURCE** creates an external data source, which defines the information about the database that openGauss will connect to. ## Precautions * The data source name must be unique in the database and comply with the identifier naming rules. Its length cannot exceed 63 bytes. Otherwise, it will be truncated. * Only the system administrator or initial user has the permission to create data sources. The user who creates the object is the default owner of the object. * If the **password** option is displayed, ensure that the **datasource.key.cipher** and **datasource.key.rand** files exist in the *$GAUSSHOME***/bin** directory of each node in openGauss. If the two files do not exist, use the **gs\_guc** tool to generate them and use the **gs\_ssh** tool to release them to the *$GAUSSHOME***/bin** directory on each node. ## Syntax ``` CREATE DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS (optname 'optvalue' [, ...])]; ``` ## Parameter Description * **src\_name** Specifies the name of the new data source, which must be unique in the database. Value range: a string compliant with the identifier naming convention * **TYPE** Specifies the type of the data source. This parameter can be left empty, and its default value will be used. Value range: an empty string or a non-empty string * **VERSION** Specifies the version number of the new data source. This parameter can be left empty or set to null. Value range: an empty string, a non-empty string, or null * **OPTIONS** Specifies the options of the data source. This parameter can be left empty or specified using the following keywords: * optname Specifies the option name. Value range: **dsn**, **username**, **password**, and **encoding**. The value is case-insensitive. * **dsn** corresponds to the DSN in the ODBC configuration file. * **username**/**password** indicates the username and password for connecting to the destination database. The user name and password entered by the user are encrypted in the openGauss background to ensure security. The key file required for encryption must be generated using the **gs\_guc** tool and released to the *$GAUSSHOME***/bin** directory of each node in openGauss using the **gs\_ssh** tool. The user name and password cannot contain the prefix "encryptOpt". Otherwise, they are considered as encrypted ciphertext. * **encoding** indicates the character string encoding mode used for interaction with the destination database (including the sent SQL statements and returned data of the character type). Its validity is not checked during object creation. Whether data can be encoded and decoded depends on whether the encoding you specified can be used in the database. * optvalue Specifies the option value. Value range: an empty string or a non-empty string ## Examples ``` -- Create an empty data source that does not contain any information. openGauss=# CREATE DATA SOURCE ds_test1; -- Create a data source with TYPE information and VERSION being null. openGauss=# CREATE DATA SOURCE ds_test2 TYPE 'MPPDB' VERSION NULL; -- Create a data source that contains only OPTIONS. openGauss=# CREATE DATA SOURCE ds_test3 OPTIONS (dsn 'openGauss', encoding 'utf8'); -- Create a data source that contains TYPE, VERSION, and OPTIONS. openGauss=# CREATE DATA SOURCE ds_test4 TYPE 'unknown' VERSION '11.2.3' OPTIONS (dsn 'openGauss', username 'userid', password 'xxxxxx', encoding ''); -- Delete the data source. openGauss=# DROP DATA SOURCE ds_test1; openGauss=# DROP DATA SOURCE ds_test2; openGauss=# DROP DATA SOURCE ds_test3; openGauss=# DROP DATA SOURCE ds_test4; ``` ## Helpful Links [ALTER DATA SOURCE](alter_data_source.md) and [DROP DATA SOURCE](drop_data_source.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_data_source.md --- # CREATE DATA SOURCE ## 功能描述 创建一个新的外部数据源对象,该对象用于定义openGauss要连接的目标库信息。 ## 注意事项 * Data Source名称在数据库中需唯一,遵循标识符命名规范,长度限制为63字节,过长则会被截断。 * 只有系统管理员或初始用户才有权限创建Data Source对象。且创建该对象的用户为其默认属主。 * 当在OPTIONS中出现password选项时,需要保证openGauss每个节点的$GAUSSHOME/bin目录下存在datasource.key.cipher和datasource.key.rand文件,如果不存在这两个文件,请使用gs\_guc工具生成并放入到openGauss每个节点的$GAUSSHOME/bin目录下。 > \[!NOTE]说明 > 轻量版场景下,openGauss提供此语法,但SQL on Anywhere不可用。 ## 语法格式 ``` CREATE DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS (optname 'optvalue' [, ...])]; ``` ## 参数说明 * **src\_name** 新建Data Source对象的名称,需在数据库内部唯一。 取值范围:字符串,要符标识符的命名规范。 * **TYPE** 新建Data Source对象的类型,可缺省。 取值范围:空串或非空字符串。 * **VERSION** 新建Data Source对象的版本号,可缺省或NULL值。 取值范围:空串或非空字符串或NULL。 * **OPTIONS** Data Source对象的选项字段,创建时可省略,如若指定,其关键字如下: * optname 选项名称。 取值范围:dsn, username, password, encoding。不区分大小写。 * dsn对应odbc配置文件中的DSN。 * username/password对应连接目标库的用户名和密码。 openGauss在后台会对用户输入的username/password加密以保证安全性。该加密所需密钥文件需要使用gs\_guc工具生成并放入openGauss每个节点的$GAUSSHOME/bin目录下。username/password不应当包含'encryptOpt'前缀,否则会被认为是加密后的密文。 * encoding表示与目标库交互的字符串编码方式(含发送的SQL语句和返回的字符类型数据),此处创建对象时不检查encoding取值的合法性,能否正确编解码取决于用户提供的编码方式是否在数据库本身支持的字符编码范围内。 * optvalue 选项值。 取值范围:空或者非空字符串。 ## 示例 ``` --创建一个空的Data Source对象,不含任何信息。 openGauss=# CREATE DATA SOURCE ds_test1; --创建一个Data Source对象,含TYPE信息,VERSION为NULL。 openGauss=# CREATE DATA SOURCE ds_test2 TYPE 'MPPDB' VERSION NULL; --创建一个Data Source对象,仅含OPTIONS。 openGauss=# CREATE DATA SOURCE ds_test3 OPTIONS (dsn 'openGauss', encoding 'utf8'); --创建一个Data Source对象,含TYPE, VERSION, OPTIONS。 openGauss=# CREATE DATA SOURCE ds_test4 TYPE 'unknown' VERSION '11.2.3' OPTIONS (dsn 'openGauss', username 'userid', password 'xxxxxx', encoding ''); --删除Data Source对象。 openGauss=# DROP DATA SOURCE ds_test1; openGauss=# DROP DATA SOURCE ds_test2; openGauss=# DROP DATA SOURCE ds_test3; openGauss=# DROP DATA SOURCE ds_test4; ``` ## 相关链接 [ALTER DATA SOURCE](alter_data_source.md), [DROP DATA SOURCE](drop_data_source.md) --- --- url: /zh/docs/latest/sql_reference/create_data_source.md --- # CREATE DATA SOURCE ## 功能描述 创建一个新的外部数据源对象,该对象用于定义openGauss要连接的目标库信息。 ## 注意事项 * Data Source名称在数据库中需唯一,遵循标识符命名规范,长度限制为63字节,过长则会被截断。 * 只有系统管理员或初始用户才有权限创建Data Source对象。且创建该对象的用户为其默认属主。 * 当在OPTIONS中出现password选项时,需要保证openGauss每个节点的$GAUSSHOME/bin目录下存在datasource.key.cipher和datasource.key.rand文件,如果不存在这两个文件,请使用gs\_guc工具生成并使用gs\_ssh工具发布到openGauss每个节点的$GAUSSHOME/bin目录下。 ## 语法格式 ``` CREATE DATA SOURCE src_name [TYPE 'type_str'] [VERSION {'version_str' | NULL}] [OPTIONS (optname 'optvalue' [, ...])]; ``` ## 参数说明 * **src\_name** 新建Data Source对象的名称,需在数据库内部唯一。 取值范围:字符串,要符标识符的命名规范。 * **TYPE** 新建Data Source对象的类型,可缺省。 取值范围:空串或非空字符串。 * **VERSION** 新建Data Source对象的版本号,可缺省或NULL值。 取值范围:空串或非空字符串或NULL。 * **OPTIONS** Data Source对象的选项字段,创建时可省略,如若指定,其关键字如下: * optname 选项名称。 取值范围:dsn、 username、 password、 encoding。不区分大小写。 * dsn对应odbc配置文件中的DSN。 * username/password对应连接目标库的用户名和密码。 openGauss在后台会对用户输入的username/password加密以保证安全性。该加密所需密钥文件需要使用gs\_guc工具生成并使用gs\_ssh工具发布到openGauss每个节点的$GAUSSHOME/bin目录下。username/password不应当包含'encryptOpt'前缀,否则会被认为是加密后的密文。 * encoding表示与目标库交互的字符串编码方式(含发送的SQL语句和返回的字符类型数据),此处创建对象时不检查encoding取值的合法性,能否正确编解码取决于用户提供的编码方式是否在数据库本身支持的字符编码范围内。 * optvalue 选项值。 取值范围:空或者非空字符串。 ## 示例 ``` --创建一个空的Data Source对象,不含任何信息。 openGauss=# CREATE DATA SOURCE ds_test1; --创建一个Data Source对象,含TYPE信息,VERSION为NULL。 openGauss=# CREATE DATA SOURCE ds_test2 TYPE 'MPPDB' VERSION NULL; --创建一个Data Source对象,仅含OPTIONS。 openGauss=# CREATE DATA SOURCE ds_test3 OPTIONS (dsn 'openGauss', encoding 'utf8'); --创建一个Data Source对象,含TYPE, VERSION, OPTIONS。 openGauss=# CREATE DATA SOURCE ds_test4 TYPE 'unknown' VERSION '11.2.3' OPTIONS (dsn 'openGauss', username 'userid', password 'pwd@123456', encoding ''); --删除Data Source对象。 openGauss=# DROP DATA SOURCE ds_test1; openGauss=# DROP DATA SOURCE ds_test2; openGauss=# DROP DATA SOURCE ds_test3; openGauss=# DROP DATA SOURCE ds_test4; ``` ## 相关链接 [ALTER DATA SOURCE](alter_data_source.md), [DROP DATA SOURCE](alter_data_source.md) --- --- url: /en/docs/latest-lite/sql_reference/create_database.md --- # CREATE DATABASE ## Function **CREATE DATABASE** is used to create a database. By default, the new database will be created only by cloning the standard system database **template0**. ## Precautions * A user that has the **CREATEDB** permission or a system administrator can create a database. * **CREATE DATABASE** cannot be executed inside a transaction block. * During the database creation, an error message indicating that permission denied is displayed, possibly because the permission on the data directory in the file system is insufficient. If an error message, indicating no space left on device is displayed, the possible cause is that the disk space is used up. ## Syntax ``` CREATE DATABASE database_name [ [ WITH ] { [ OWNER [=] user_name ] | [ TEMPLATE [=] template ] | [ ENCODING [=] encoding ] | [ LC_COLLATE [=] lc_collate ] | [ LC_CTYPE [=] lc_ctype ] | [ DBCOMPATIBILITY [=] compatibilty_type ] | [ TABLESPACE [=] tablespace_name ] | [ CONNECTION LIMIT [=] connlimit ]}[...] ]; ``` ## Parameter Description * **database\_name** Specifies the database name. Value range: a string. It must comply with the identifier naming convention. * **OWNER \[ = ] user\_name** Specifies the owner of the new database. If omitted, the default owner is the current user. Value range: an existing username * **TEMPLATE \[ = ] template** Specifies a template name. That is, the template from which the database is created. openGauss creates a database by copying data from a template database. openGauss has two default template databases **template0** and **template1** and a default user database **postgres**. Value range: **template0** * **ENCODING \[ = ] encoding** Specifies the character encoding used by the database. The value can be a string (for example, **SQL\_ASCII**) or an integer. If this parameter is not specified, the encoding of the template database is used by default. By default, the codes of the template databases **template0** and **template1** are related to the operating system environment. The character encoding of **template1** cannot be changed. To change the encoding, use **template0** to create a database. Common values are **GBK**, **UTF8**, **Latin1**, and **GB10830**. The supported character sets are as follows: **Table 1** openGauss character set > \[!WARNING]CAUTION > > Note that not all client APIs support the preceding character sets. > The SQL\_ASCII setting performs quite differently from other settings. If the character set of the server is SQL\_ASCII, the server interprets the byte values 0 to 127 according to the ASCII standard. The byte values 128 to 255 are regarded as the characters that cannot be parsed. If this parameter is set to SQL\_ASCII, no code conversion occurs. Therefore, this setting is not basically used to declare the specified encoding used, because this declaration ignores the encoding. In most cases, if you use any non-ASCII data, it is unwise to use the SQL\_ASCII setting because openGauss will not be able to help you convert or validate non-ASCII characters. > \[!TIP]NOTICE > > * The character set encoding of the new database must be compatible with the local settings (**LC\_COLLATE** and **LC\_CTYPE**). > * When the specified character encoding set is **GBK**, some uncommon Chinese characters cannot be directly used as object names. This is because the byte encoding overlaps with the ASCII characters @A-Z\[\\]^\_\`a-z{|} when the second byte of the GBK ranges from 0x40 to 0x7E. **@\[\\]^\_'{|}** is an operator in the database. If it is directly used as an object name, a syntax error will be reported. For example, the GBK hexadecimal code is **0x8240**, and the second byte is **0x40**, which is the same as the ASCII character @. Therefore, the character cannot be used as an object name. If you do need to use this function, you can add double quotation marks ("") to avoid this problem when creating and accessing objects. > * If the client code is A and the server code is B, conversion between A and B must exist in the database. For example, when the encoding format on the server is GB18030 and that on the client is GBK, the error message "Conversion between GB18030 and GBK is not supported." will be displayed because the current database does not support the conversion between GB18030 and GBK. For details about conversion between the encoding formats supported by the database, see the **pg\_conversion** system catalog. * **LC\_COLLATE \[ = ] lc\_collate** Specifies the character set used by the new database. For example, set this parameter by using **lc\_collate = 'zh\_CN.gbk'**. The use of this parameter affects the sort order of strings (for example, the order of using **ORDER BY** for execution and the order of using indexes on text columns). By default, the sorting order of the template database is used. Value range: a valid sorting type * **LC\_CTYPE \[ = ] lc\_ctype** Specifies the character class used by the new database. For example, set this parameter by using **lc\_ctype = 'zh\_CN.gbk'**. The use of this parameter affects the classification of characters, such as uppercase letters, lowercase letters, and digits. By default, the character classification of the template database is used. Value range: a valid character type * **DBCOMPATIBILITY \[ = ] compatibility\_type** Specifies the compatible database type. The default compatible database is the **O** database. Value range: **A**, **B**, **C**, and **PG**, indicating Oracle, MySQL, Teradata, and Postgres databases, respectively. > \[!NOTE]NOTE > > * For A compatibility, the database treats empty strings as **NULL** and replaces **DATE** with **TIMESTAMP(0) WITHOUT TIME ZONE**. > * When a character string is converted to an integer, if the input is invalid, the input will be converted to 0 due to B compatibility, and an error will be reported due to other compatibility issues. > * For PG compatibility, CHAR and VARCHAR are counted by character. For other compatibility types, they are counted by byte. For example, for the UTF-8 character set, CHAR(3) can store three Chinese characters in PG compatibility scenarios, but can store only one Chinese character in other compatibility scenarios. * **TABLESPACE \[ = ] tablespace\_name** Specifies the tablespace of the database. Value range: an existing tablespace name * **CONNECTION LIMIT \[ = ] connlimit** Specifies the maximum number of concurrent connections that can be made to the new database. > \[!TIP]NOTICE > > * The system administrator is not restricted by this parameter. > * connlimit is calculated separately for each primary database node. Number of connections of openGauss = connlimit x Number of normal CN primary database nodes. Value range: an integer greater than or equal to -1 The default value is **-1**, indicating that there is no limit. The restrictions on character encoding are as follows: * If the locale is set to **C** (or **POSIX**), all encoding types are allowed. For other locale settings, the character encoding must be the same as that of the locale. * If the character encoding mode is SQL\_ASCII and the modifier is an administrator, the character encoding mode can be different from the locale setting. * The encoding and region settings must match the template database, except that **template0** is used as a template. This is because other databases may contain data that does not match the specified encoding, or may contain indexes whose sorting order is affected by **LC\_COLLATE** and **LC\_CTYPE**. Copying this data will invalidate the indexes in the new database. **template0** does not contain any data or indexes that may be affected. ## Examples ``` -- Create users jim and tom. openGauss=# CREATE USER jim PASSWORD 'xxxxxxxxx'; openGauss=# CREATE USER tom PASSWORD 'xxxxxxxxx'; -- Create database music using GBK (the local encoding type is also GBK). openGauss=# CREATE DATABASE music ENCODING 'GBK' template = template0; -- Create database music2 and specify user jim as its owner. openGauss=# CREATE DATABASE music2 OWNER jim; -- Create database music3 using template template0 and specify user jim as its owner. openGauss=# CREATE DATABASE music3 OWNER jim TEMPLATE template0; -- Set the maximum number of connections to database music to 10. openGauss=# ALTER DATABASE music CONNECTION LIMIT= 10; -- Rename database music to music4. openGauss=# ALTER DATABASE music RENAME TO music4; -- Change the owner of database music2 to user tom. openGauss=# ALTER DATABASE music2 OWNER TO tom; -- Set the tablespace of database music3 to PG_DEFAULT. openGauss=# ALTER DATABASE music3 SET TABLESPACE PG_DEFAULT; -- Disable the default index scan on database music3. openGauss=# ALTER DATABASE music3 SET enable_indexscan TO off; -- Reset the enable_indexscan parameter. openGauss=# ALTER DATABASE music3 RESET enable_indexscan; -- Delete the database. openGauss=# DROP DATABASE music2; openGauss=# DROP DATABASE music3; openGauss=# DROP DATABASE music4; -- Delete the jim and tom users. openGauss=# DROP USER jim; openGauss=# DROP USER tom; -- Create a database compatible with the TD format. openGauss=# CREATE DATABASE td_compatible_db DBCOMPATIBILITY 'C'; -- Create a database compatible with the A format. openGauss=# CREATE DATABASE ora_compatible_db DBCOMPATIBILITY 'A'; -- Delete the databases that are compatible with the TD and A formats. openGauss=# DROP DATABASE td_compatible_db; openGauss=# DROP DATABASE ora_compatible_db; ``` ## Helpful Links [ALTER DATABASE](alter_database.md) and [DROP DATABASE](drop_database.md) ## Suggestions * **create database** Database cannot be created in a transaction. * **ENCODING LC\_COLLATE LC\_CTYPE** If the new database Encoding does not match the template database (SQL\_ASCII) (**'GBK'**, **'UTF8'**, **'LATIN1'**, or **'GB18030'**), **template \[=] template0** must be specified. --- --- url: /en/docs/latest/sql_reference/create_database.md --- # CREATE DATABASE ## Function Creates a database. By default, the new database will be created only by cloning the standard system database **template0**. ## Precautions * Only system administrators or users with the **CREATEDB** permission can create a database. * **CREATE DATABASE** cannot be executed within a transaction block. * During the database creation, an error message indicating that permission denied is displayed, possibly because the permission on the data directory in the file system is insufficient. If an error message, indicating no space left on device is displayed, the possible cause is that the disk space is used up. ## Syntax ``` CREATE DATABASE [IF NOT EXISTS] database_name [ [ WITH ] { [ OWNER [=] user_name ] | [ TEMPLATE [=] template ] | [ ENCODING [=] encoding ] | [ LC_COLLATE [=] lc_collate ] | [ LC_CTYPE [=] lc_ctype ] | [ DBCOMPATIBILITY [=] compatibilty_type ] | [ TABLESPACE [=] tablespace_name ] | [ CONNECTION LIMIT [=] connlimit ]}[...] ]; ``` ## Parameter Description * **database\_name** Database name Value range: String, which must comply with the naming convention. * **OWNER \[ = ] user\_name** Specifies the owner of the new database. By default, the owner of a new database is the current user. Value range: an existing user name. * **TEMPLATE \[ = ] template** Specifies a template name, that is, the template from which the database is created. openGauss creates a database by copying data from a template database. openGauss has two default template databases **template0** and **template1** and a default user database **postgres**. Value range: **template0** * **ENCODING \[ = ] encoding** Specifies the encoding format used by the new database. The value can be a string (for example, **SQL\_ASCII**) or an integer. By default, the encoding format of the template database is used. The encoding formats of the template databases **template0** and **template1** depend on the OS. The encoding format of **template1** cannot be changed. If you need to change the encoding format when creating a database, use **template0**. Common values are **GBK**, **UTF8**, **Latin1**, and **GB10830**. The supported character sets are as follows: **Table 1** openGauss character set > \[!WARNING]CAUTION > Note that not all client APIs support the preceding character sets. > The SQL\_ASCII setting performs quite differently from other settings. If the character set of the server is SQL\_ASCII, the server interprets the byte values 0 to 127 according to the ASCII standard. The byte values 128 to 255 are regarded as the characters that cannot be parsed. If this parameter is set to SQL\_ASCII, no code conversion occurs. Therefore, this setting is not basically used to declare the specified encoding used, because this declaration ignores the encoding. In most cases, if you use any non-ASCII data, it is unwise to use the SQL\_ASCII setting because openGauss will not be able to help you convert or validate non-ASCII characters. > \[!TIP]NOTICE > > * The character set encoding of the new database must be compatible with the local settings (**LC\_COLLATE** and **LC\_CTYPE**). > * When the specified character encoding set is **GBK**, some uncommon Chinese characters cannot be used directly as object names. This is because the byte encoding overlaps with the ASCII characters @A-Z\[\\]^\_\`a-z{|} when the second byte of the GBK ranges from 0x40 to 0x7E. **@\[\\]^\_'{|}** is an operator in the database. If it is used directly as an object name, a syntax error will be reported. For example, the GBK hexadecimal code is **0x8240**, and the second byte is **0x40**, which is the same as the ASCII character @. Therefore, the character cannot be used as an object name. If you do need to use these characters, you can enclose them with double quotation marks ("") when creating and accessing objects to avoid this problem. > * If the client encoding is A and the server encoding is B, the conversion between encoding formats A and B must exist in the database. For example: If the encoding format on the server is gb18030, the error message "Conversion between GB18030 and GBK is not supported." is displayed when you set the encoding format on the client to **gbk** because the current database does not support conversion between gb18030 and gbk. For details about all encoding formats supported by the database, see the pg\_conversion system catalog. * **LC\_COLLATE \[ = ] lc\_collate** Specifies the character set used by the new database. For example, this parameter is set by running **lc\_collate = 'zh\_CN.gbk'**. The use of this parameter affects the sort order of strings (for example, the order of using **ORDER BY** for execution and the order of using indexes on text columns). The default is to use the collation order of the template database. Value range: A valid order type. * **LC\_CTYPE \[ = ] lc\_ctype** Specifies the character class used by the new database. For example, this parameter is set by running **lc\_ctype = 'zh\_CN.gbk'**. The use of this parameter affects the classification of characters, such as uppercase letters, lowercase letters, and digits. The default is to use the character classification of the template database. Value range: a valid character type * **DBCOMPATIBILITY \[ = ] compatibility\_type** Specifies the compatible database type. The default value is **O**. Value range: A, B, C, and PG, indicating **O**, **MY**, **TD** and **POSTGRES** databases, respectively. > \[!NOTE]NOTE > > * For A compatibility, the database treats empty strings as **NULL** and replaces DATE with TIMESTAMP(0) WITHOUT TIME ZONE. > * When a character string is converted to an integer, if the input is invalid, the input will be converted to 0 due to B compatibility, and an error will be reported due to other compatibility issues. > * For PG compatibility, CHAR and VARCHAR are counted by character. For other compatibility types, they are counted by byte. For example, for the UTF-8 character set, CHAR(3) can store three Chinese characters in PG compatibility scenarios, but can store only one Chinese character in other compatibility scenarios. * **TABLESPACE \[ = ] tablespace\_name** Specifies the name of the tablespace that will be associated with the new database. Value range: an existing tablespace name. * **CONNECTION LIMIT \[ = ] connlimit** Specifies the maximum number of concurrent connections that can be made to the new database. > \[!TIP]NOTICE > > * This limit does not apply to sysadmin. > - connlimit is calculated separately for each primary database node. Number of connections of the openGauss = connlimit x Number of normal CN master database nodes. ``` Value range: An integer greater than or equal to **-1**. The default value **-1** means no limit. ``` The restrictions on character encoding are as follows: * If the locale is set to **C** (or **POSIX**), all encoding types are allowed. For other locale settings, the character encoding must be the same as that of the locale. * If the character encoding mode is SQL\_ASCII and the modifier is an administrator, the character encoding mode can be different from the locale setting. * The encoding and region settings must match the template database, except that **template0** is used as a template. This is because other databases might contain data that does not match the specified encoding, or might contain indexes whose sort ordering is affected by **LC\_COLLATE** and **LC\_CTYPE**. Copying such data will invalidate the indexes in the new database. **template0** does not contain any data or indexes that may be affected. ## Examples ``` --Create users jim and tom. openGauss=# CREATE USER jim PASSWORD 'xxxxxxxxx'; openGauss=# CREATE USER tom PASSWORD 'xxxxxxxxx'; --Create database music using GBK (the local encoding type is also GBK). openGauss=# CREATE DATABASE music ENCODING 'GBK' template = template0; --Create database music2 and specify jim as its owner. openGauss=# CREATE DATABASE music2 OWNER jim; --Create database music3 using template template0 and specify jim as its owner. openGauss=# CREATE DATABASE music3 OWNER jim TEMPLATE template0; --Set the maximum number of connections to database music to 10. openGauss=# ALTER DATABASE music CONNECTION LIMIT= 10; --Rename database music to music4. openGauss=# ALTER DATABASE music RENAME TO music4; --Change the owner of database music2 to tom. openGauss=# ALTER DATABASE music2 OWNER TO tom; --Set the tablespace of database music3 to PG_DEFAULT. openGauss=# ALTER DATABASE music3 SET TABLESPACE PG_DEFAULT; --Close the default index scan on database music3. openGauss=# ALTER DATABASE music3 SET enable_indexscan TO off; --Reset parameter enable_indexscan. openGauss=# ALTER DATABASE music3 RESET enable_indexscan; --Delete a database. openGauss=# DROP DATABASE music2; openGauss=# DROP DATABASE music3; openGauss=# DROP DATABASE music4; --Delete users jim and tom. openGauss=# DROP USER jim; openGauss=# DROP USER tom; --Create a database compatible with Teradata. openGauss=# CREATE DATABASE td_compatible_db DBCOMPATIBILITY 'C'; --Create a database compatible with the A format. openGauss=# CREATE DATABASE ora_compatible_db DBCOMPATIBILITY 'A'; --Delete the databases that are compatible with the TD and A formats. openGauss=# DROP DATABASE td_compatible_db; openGauss=# DROP DATABASE ora_compatible_db; ``` ## Helpful Links [ALTER DATABASE](alter_database.md), [DROP DATABASE](drop_database.md) ## Optimization Suggestion * **create database** Database cannot be created in a transaction. * **ENCODING LC\_COLLATE LC\_CTYPE** If the new database Encoding does not match the template database (SQL\_ASCII) (**'GBK'**, **'UTF8'**, **'LATIN1'**, or **'GB18030'**), **template \[=] template0** must be specified. --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CREATE-DATABASE.md --- # CREATE DATABASE ## 功能描述 创建一个新的数据库。缺省情况下新数据库将通过复制标准系统数据库template0来创建,且仅支持使用template0来创建。 创建一个新的模式。可以设定模式的默认字符集和字符序。 ## 注意事项 相比于原始的openGauss,dolphin对于CREATE DATABASE语法的修改为: * 增加可修改项 \[ \[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset ] \[ \[DEFAULT] COLLATE \[ = ] default\_collation ]。 ## 语法格式 ``` CREATE DATABASE [IF NOT EXISTS] database_name [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ]; ``` ## 参数说明 * **database\_name** 数据库名称。 取值范围:字符串,要符合标识符的命名规范。 * **\[ \[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset ]** 指定模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **\[ \[DEFAULT] COLLATE \[ = ] default\_collation ]** 指定模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 \[!NOTE]说明 * B兼容性下,仅在 dolphin.b\_compatibility\_mode 为on时支持该语法。 * 使用该语法时,语法等效于CREATE SCHEMA,实际为创建SCHEMA语法, database\_name 为SCHEMA名称 。 * B兼容性下, dolphin.b\_compatibility\_mode 为on时,不指定 default\_charset 、default\_collation ,而指定其他CREATE DATABASE 语法选项,语法仍为CREATE DATABASE语法。 * B兼容性下, dolphin.b\_compatibility\_mode 为on时,当不指定任何选项,语法等同为CREATE SCHEMA语法;dolphin.b\_compatibility\_mode 为off时,语法等同为CREATE DATABASE 语法。 * B兼容性下,b\_format\_behavior\_compat\_options参数默认配置'default\_c ollation',针对OM方式安装的数据库,Encoding=SQL\_ASCII,Collate=C,Ctype=C,在配置'default\_collation'时,建表指定varchar类型,将实际存储为varbinary类型,因此为兼容MY,建议在创建B库时指定编码为UTF8,即`create database testb with dbcompatibility = 'b' encoding 'UTF8';`。 ## 示例 ``` -- 打开 dolphin.b_compatibility_mode 开关 openGauss=# set dolphin.b_compatibility_mode = on; SET openGauss=# create database test1; CREATE SCHEMA openGauss=# create database test2 charset 'utf8'; CREATE SCHEMA openGauss=# drop database if exists test1; ``` ## 相关链接 [ALTER DATABASE](dolphin-ALTER-DATABASE.md),[DROP DATABASE](dolphin-DROP-DATABASE.md), [CREATE DATABASE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_database.html) --- --- url: /zh/docs/latest-lite/sql_reference/create_database.md --- # CREATE DATABASE ## 功能描述 创建一个新的数据库。缺省情况下新数据库将通过复制标准系统数据库template0来创建,且仅支持使用template0来创建。 ## 注意事项 * 只有拥有CREATEDB权限的用户才可以创建新数据库,系统管理员默认拥有此权限。 * 不能在事务块中执行创建数据库语句。 * 在创建数据库过程中,出现类似“Permission denied”的错误提示,可能是由于文件系统上数据目录的权限不足。出现类似“No space left on device”的错误提示,可能是由于磁盘满引起的。 ## 语法格式 ``` CREATE DATABASE database_name [ [ WITH ] { [ OWNER [=] user_name ] | [ TEMPLATE [=] template ] | [ ENCODING [=] encoding ] | [ LC_COLLATE [=] lc_collate ] | [ LC_CTYPE [=] lc_ctype ] | [ DBCOMPATIBILITY [=] compatibilty_type ] | [ TABLESPACE [=] tablespace_name ] | [ CONNECTION LIMIT [=] connlimit ]}[...] ]; ``` ## 参数说明 * **database\_name** 数据库名称。 取值范围:字符串,要符合标识符的命名规范。 * **OWNER \[ = ] user\_name** 数据库所有者。缺省时,新数据库的所有者是当前用户。 取值范围:已存在的用户名。 * **TEMPLATE \[ = ] template** 模板名。即从哪个模板创建新数据库。openGauss采用从模板数据库复制的方式来创建新的数据库。初始时,openGauss包含两个模板数据库template0、template1,以及一个默认的用户数据库postgres。 取值范围:仅template0。 * **ENCODING \[ = ] encoding** 指定数据库使用的字符编码,可以是字符串(如'SQL\_ASCII')、整数编号。 不指定时,默认使用模版数据库的编码。模板数据库template0和template1的编码默认与操作系统环境相关。template1不允许修改字符编码,因此若要变更编码,请使用template0创建数据库。 * **ENCODING** 当新建数据库Encoding与模板数据库(SQL\_ASCII)不匹配(为'GBK' /'UTF8'/'LATIN1'/'GB18030'/'GB18030\_2022')时,必须指定template \[=] template0。 常用取值:GBK、UTF8、Latin1、GB10830等,具体支持的字符集如下: **表 1** openGauss字符集 > \[!WARNING]注意 > > 需要注意并非所有的客户端API都支持上面列出的字符集。 > SQL\_ASCII设置与其他设置表现得相当不同。如果服务器字符集是SQL\_ASCII,服务器把字节值0-127根据 ASCII标准解释,而字节值128-255则当作无法解析的字符。如果设置为SQL\_ASCII,就不会有编码转换。因此,这个设置基本不是用来声明所使用的指定编码, 因为这个声明会忽略编码。在大多数情况下,如果你使用了任何非ASCII数据,那么使用 SQL\_ASCII设置都是不明智的,因为openGauss将无法帮助你转换或者校验非ASCII字符。 > \[!TIP]须知 > > * 指定新的数据库字符集编码必须与所选择的本地环境中(LC\_COLLATE和LC\_CTYPE)的设置兼容。 > * 当指定的字符编码集为GBK时,部分中文生僻字无法直接作为对象名。这是因为GBK第二个字节的编码范围在0x40-0x7E之间时,字节编码与ASCII字符@A-Z\[\\]^\_\`a-z{|}重叠。其中@\[\\]^\_'{|}是数据库中的操作符,直接作为对象名时,会语法报错。例如“侤”字,GBK16进制编码为0x8240,第二个字节为0x40,与ASCII“@”符号编码相同,因此无法直接作为对象名使用。如果确实要使用,可以在创建和访问对象时,通过增加双引号来规避这个问题。 > * 若客户端编码为A,服务器端编码为B,则需要满足数据库中存在编码格式A与B的转换。数据库能够支持的所有的编码格式转换详见系统表[PG\_CONVERSION](../database_reference/pg_conversion.md)(若无法转换,则建议客户端编码与服务器端编码保持一致,客户端编码可通过GUC参数client\_encoding修改)。 > * 若要指定数据库字符集编码为GB18030\_2022,且客户端编码也要设置为GB18030时,必须确保客户端操作系统支持的GB18030字符集为2022版本,否则由于GB18030字符集自身的各版本间存在不完全兼容,可能导致数据的不一致性。同时,涉及到历史数据切换为GB18030\_2022数据库时应当遵循切库流程,进行数据迁移操作。 * **LC\_COLLATE \[ = ] lc\_collate** 指定新数据库使用的字符集。例如,通过lc\_collate = 'zh\_CN.gbk'设定该参数。 该参数的使用会影响到对字符串的排序顺序(如使用ORDER BY执行,以及在文本列上使用索引的顺序)。默认是使用模板数据库的排序顺序。 取值范围:操作系统支持的字符集。 * **LC\_CTYPE \[ = ] lc\_ctype** 指定新数据库使用的字符分类。例如,通过lc\_ctype = 'zh\_CN.gbk'设定该参数。该参数的使用会影响到字符的分类,如大写、小写和数字。默认是使用模板数据库的字符分类。 取值范围:操作系统支持的字符分类。 > \[!NOTE]说明 > > * 对于lc\_collate和lc\_ctype参数的取值范围,取决于本地环境支持的字符集。 > * 当指定的字符编码集为GB18030\_2022时,其LC\_COLLATE和LC\_CTYPE的取值范围与GB18030保持一致。 > 例如:在Linux操作系统上,可通过locale -a命令获取操作系统支持的字符集列表,在应用lc\_collate和lc\_ctype参数时可从中选择用户需要的字符集和字符分类。 * **DBCOMPATIBILITY \[ = ] compatibility\_type** 指定兼容的数据库的类型,默认兼容O。 取值范围:A、B、C、PG、D。分别表示兼容O、MY、TD、POSTGRES和S数据库。在B兼容性场景下,必须加载dolphin插件才允许被连接。详见[Dolphin限制](https://docs.opengauss.org/zh/docs/latest-lite/extension_reference/dolphin.html)。 > \[!NOTE]说明 > > * A兼容性下,数据库将空字符串作为NULL处理,数据类型DATE会被替换为TIMESTAMP(0) WITHOUT TIME ZONE。 > * 将字符串转换成整数类型时,如果输入不合法,B兼容性会将输入转换为0,而其它兼容性则会报错。 > * B和PG兼容性下,CHAR和VARCHAR以字符为计数单位,其它兼容性以字节为计数单位。例如,对于UTF-8字符集,CHAR(3)在B和PG兼容性下能存放3个中文字符,而在其它兼容性下只能存放1个中文字符。 * **TABLESPACE \[ = ] tablespace\_name** 指定数据库对应的表空间。 取值范围:已存在表空间名。 * **CONNECTION LIMIT \[ = ] connlimit** 数据库可以接受的并发连接数。 > \[!TIP]须知 > > * 系统管理员不受此参数的限制。 > * connlimit数据库主节点单独统计,openGauss整体的连接数 = connlimit \* 当前正常数据库主节点个数。 取值范围:>=-1的整数。默认值为-1,表示没有限制。 有关字符编码的一些限制: * 若区域设置为C(或POSIX),则允许所有的编码类型,但是对于其他的区域设置,字符编码必须和区域设置相同。 * 若字符编码方式是SQL\_ASCII,并且修改者为管理员用户时,则字符编码可以和区域设置不相同。 * 编码和区域设置必须匹配模板数据库,除了将template0当作模板。 因为其他数据库可能会包含不匹配指定编码的数据,或者可能包含排序顺序受LC\_COLLATE和LC\_CTYPE影响的索引。复制这些数据会导致在新数据库中的索引失效。template0是不包含任何会受到影响的数据或者索引。 ## 示例 ``` --创建jim和tom用户。 openGauss=# CREATE USER jim PASSWORD 'xxxxxxxxx'; openGauss=# CREATE USER tom PASSWORD 'xxxxxxxxx'; --创建一个GBK编码的数据库music(本地环境的编码格式必须也为GBK)。 openGauss=# CREATE DATABASE music ENCODING 'GBK' template = template0; --创建数据库music2,并指定所有者为jim。 openGauss=# CREATE DATABASE music2 OWNER jim; --用模板template0创建数据库music3,并指定所有者为jim。 openGauss=# CREATE DATABASE music3 OWNER jim TEMPLATE template0; --设置music数据库的连接数为10。 openGauss=# ALTER DATABASE music CONNECTION LIMIT= 10; --将music名称改为music4。 openGauss=# ALTER DATABASE music RENAME TO music4; --将数据库music2的所属者改为tom。 openGauss=# ALTER DATABASE music2 OWNER TO tom; --设置music3的表空间为PG_DEFAULT。 openGauss=# ALTER DATABASE music3 SET TABLESPACE PG_DEFAULT; --关闭在数据库music3上缺省的索引扫描。 openGauss=# ALTER DATABASE music3 SET enable_indexscan TO off; --重置enable_indexscan参数。 openGauss=# ALTER DATABASE music3 RESET enable_indexscan; --删除数据库。 openGauss=# DROP DATABASE music2; openGauss=# DROP DATABASE music3; openGauss=# DROP DATABASE music4; --删除jim和tom用户。 openGauss=# DROP USER jim; openGauss=# DROP USER tom; --创建兼容TD格式的数据库。 openGauss=# CREATE DATABASE td_compatible_db DBCOMPATIBILITY 'C'; --创建兼容A格式的数据库。 openGauss=# CREATE DATABASE ora_compatible_db DBCOMPATIBILITY 'A'; --删除兼容TD、A格式的数据库。 openGauss=# DROP DATABASE td_compatible_db; openGauss=# DROP DATABASE ora_compatible_db; ``` ## 相关链接 [ALTER DATABASE](alter_database.md),[DROP DATABASE](drop_database.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CREATE-DATABASE.md --- # CREATE DATABASE ## 功能描述 创建一个新的数据库。缺省情况下新数据库将通过复制标准系统数据库template0来创建,且仅支持使用template0来创建。 创建一个新的模式。可以设定模式的默认字符集和字符序。 ## 注意事项 相比于原始的openGauss,dolphin对于CREATE DATABASE语法的修改为: * 增加可修改项 \[ \[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset ] \[ \[DEFAULT] COLLATE \[ = ] default\_collation ]。 ## 语法格式 ``` CREATE DATABASE [IF NOT EXISTS] database_name [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ]; ``` ## 参数说明 * **database\_name** 数据库名称。 取值范围:字符串,要符合标识符的命名规范。 * **\[ \[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset ]** 指定模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **\[ \[DEFAULT] COLLATE \[ = ] default\_collation ]** 指定模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 \[!NOTE]说明 * B兼容性下,仅在 dolphin.b\_compatibility\_mode 为on时支持该语法。 * 使用该语法时,语法等效于CREATE SCHEMA,实际为创建SCHEMA语法, database\_name 为SCHEMA名称 。 * B兼容性下, dolphin.b\_compatibility\_mode 为on时,不指定 default\_charset 、default\_collation ,而指定其他CREATE DATABASE 语法选项,语法仍为CREATE DATABASE语法。 * B兼容性下, dolphin.b\_compatibility\_mode 为on时,当不指定任何选项,语法等同为CREATE SCHEMA语法;dolphin.b\_compatibility\_mode 为off时,语法等同为CREATE DATABASE 语法。 * B兼容性下,b\_format\_behavior\_compat\_options参数默认配置'default\_c ollation',针对OM方式安装的数据库,Encoding=SQL\_ASCII,Collate=C,Ctype=C,在配置'default\_collation'时,建表指定varchar类型,将实际存储为varbinary类型,因此为兼容MY,建议在创建B库时指定编码为UTF8,即`create database testb with dbcompatibility = 'b' encoding 'UTF8';`。 ## 示例 ``` -- 打开 dolphin.b_compatibility_mode 开关 openGauss=# set dolphin.b_compatibility_mode = on; SET openGauss=# create database test1; CREATE SCHEMA openGauss=# create database test2 charset 'utf8'; CREATE SCHEMA openGauss=# drop database if exists test1; ``` ## 相关链接 [ALTER DATABASE](dolphin-ALTER-DATABASE.md),[DROP DATABASE](dolphin-DROP-DATABASE.md), [CREATE DATABASE](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_database.html) --- --- url: /zh/docs/latest/ograc/sql_reference/create_database.md --- # CREATE DATABASE ## 功能描述 创建一个新的数据库。 ## 注意事项 * 只有拥有CREATE DATABASE权限的用户才可以创建新数据库,系统管理员默认拥有此权限。 * 只能在安装数据库过程中自动创建,无需手动创建。 * 若创建失败,需重启数据库再次创建。 ## 语法格式 ```sql CREATE DATABASE CLUSTERED database_name [ { [ CHARACTER SET ] | [ CONTROLFILE('file1','file2','file3',....) ] | [ SYSTEM TABLESPACE DATAFILE ] | [ NOLOGGING TABLESPACE TEMPFILE ] | [ NOLOGGING UNDO TABLESPACE TEMPFILE ] | [ DEFAULT TABLESPACE DATAFILE ] | [ SYSAUX TABLESPACE DATAFILE ] | [ UNDO TABLESPACE DATAFILE ] | [ TEMPORARY TABLESPACE TEMPFILE ] | [ LOGFILE ]}[...] ] [ WITH DBCOMPATIBILITY 'compatibility_type']; ``` ## 参数说明 * **database\_name**: 数据库名称。 取值范围:字符串,要符合标识符的命名规范。 * **character set**: 指定数据库使用的字符编码。 取值范围:仅支持UTF-8和GBK。不指定时,默认编码是UTF-8。 * **controlfile**: 控制文件列表。 取值范围:字符串,文件名称之间用逗号隔开。 * **tablespace**: tablespace相关参数包括:system tablespace datafile、nologging tablespace TEMPFILE、nologging undo tablespace TEMPFILE、default tablespace datafile、sysaux tablespace DATAFILE、undo tablespace datafile、temporary tablespace TEMPFILE。 > **说明:** > > * system tablespace datafile:系统表空间的数据文件,用于存储核心数据,取值范围128M~8T。 > * nologging tablespace TEMPFILE:NOLOGGING表空间,取值范围1M~8T。 > * nologging undo tablespace TEMPFILE:NOLOGGING UNDO表空间,取值范围128M~32G。 > * default tablespace datafile:用于指定用户创建的对象(如表、索引)的默认存储表空间,取值范围1M~8T。 > * sysaux tablespace datafile:用于存储数据字典以外的其他数据库组件和工具数据,以减轻SYSTEM表空间的负担,取值范围128M~8T。 > * undo tablespace datafile:用于存储事务撤销信息,取值范围128M~32G。 > * temporary tablespace TEMPFILE:用于创建和管理临时表空间,临时表空间主要用于存储数据库操作过程中产生的临时数据,比如排序操作、哈希连接等需要大量临时存储空间的操作,取值范围5M~8T。 * **logfile**: 创建数据库日志文件。参数包括:logfile、size、blocksize。 > **说明:** > > * logfile:日志文件。 > * size:日志文件大小,单位包括:K、M、G、T、P、E,默认单位为字节,最少3个log文件,需满足size >= 56M + 16k + log\_buffer\_size。 > * blocksize:设置块的大小,单位为字节,仅支持设置为512或4096两种值。 * **compatibility\_type**: 创建数据库的兼容性,支持A/B/C兼容性,不使用with dbcompatibility指定兼容性时默认为A兼容性库。 ## 示例 ``` create database clustered ograc character set utf8 controlfile('dbfiles1/ctrl1', 'dbfiles1/ctrl2', 'dbfiles1/ctrl3') system tablespace datafile 'dbfiles1/sys.dat' size 128M autoextend on next 32M nologging tablespace TEMPFILE 'dbfiles1/temp2_01' size 160M autoextend on next 32M, 'dbfiles1/temp2_02' size 160M autoextend on next 32M nologging undo tablespace TEMPFILE 'dbfiles1/temp2_undo' size 1G default tablespace datafile 'dbfiles1/user1.dat' size 1G autoextend on next 32M, 'dbfiles1/user2.dat' size 1G autoextend on next 32M sysaux tablespace DATAFILE 'dbfiles1/sysaux' size 160M autoextend on next 32M undo tablespace datafile 'dbfiles1/undo01.dat' size 1G autoextend on next 32M, 'dbfiles1/undo02.dat' size 1G autoextend on next 32M temporary tablespace TEMPFILE 'dbfiles1/temp1_01' size 160M autoextend on next 32M, 'dbfiles1/temp1_02' size 160M autoextend on next 32M nologging undo tablespace TEMPFILE 'dbfiles1/temp2_undo_01' size 128M autoextend on next 32M logfile ('dbfiles1/redo01.dat' size 256M blocksize 512, 'dbfiles1/redo02.dat' size 256M blocksize 4096, 'dbfiles1/redo03.dat' size 256M blocksize 512); ``` --- --- url: /zh/docs/latest/sql_reference/create_database.md --- # CREATE DATABASE ## 功能描述 创建一个新的数据库。缺省情况下新数据库将通过复制标准系统数据库template0来创建,且仅支持使用template0来创建。 ## 注意事项 * 只有拥有CREATEDB权限的用户才可以创建新数据库,系统管理员默认拥有此权限。 * 不能在事务块中执行创建数据库语句。 * 在创建数据库过程中,出现类似“Permission denied”的错误提示,可能是由于文件系统上数据目录的权限不足。出现类似“No space left on device”的错误提示,可能是由于磁盘满引起的。 ## 语法格式 ``` CREATE DATABASE [IF NOT EXISTS] database_name [ [ WITH ] { [ OWNER [=] user_name ] | [ TEMPLATE [=] template ] | [ ENCODING [=] encoding ] | [ LC_COLLATE [=] lc_collate ] | [ LC_CTYPE [=] lc_ctype ] | [ DBCOMPATIBILITY [=] compatibilty_type ] | [ TABLESPACE [=] tablespace_name ] | [ CONNECTION LIMIT [=] connlimit ]}[...] ]; ``` ## 参数说明 * **database\_name** 数据库名称。 取值范围:字符串,要符合标识符的命名规范。 * **OWNER \[ = ] user\_name** 数据库所有者。缺省时,新数据库的所有者是当前用户。 取值范围:已存在的用户名。 * **TEMPLATE \[ = ] template** 模板名。即从哪个模板创建新数据库。openGauss采用从模板数据库复制的方式来创建新的数据库。初始时,openGauss包含两个模板数据库template0、template1,以及一个默认的用户数据库postgres。 取值范围:仅template0。 * **ENCODING \[ = ] encoding** 指定数据库使用的字符编码,可以是字符串(如'SQL\_ASCII')、整数编号。 不指定时,默认使用模版数据库的编码。模板数据库template0和template1的编码默认与操作系统环境相关。template1不允许修改字符编码,因此若要变更编码,请使用template0创建数据库。 常用取值:GBK、UTF8、Latin1、GB10830等,具体支持的字符集如下: **表 1** openGauss字符集 > \[!WARNING]注意 > > 需要注意并非所有的客户端API都支持上面列出的字符集。 > SQL\_ASCII设置与其他设置表现得相当不同。如果服务器字符集是SQL\_ASCII,服务器把字节值0-127根据 ASCII标准解释,而字节值128-255则当作无法解析的字符。如果设置为SQL\_ASCII,就不会有编码转换。因此,这个设置基本不是用来声明所使用的指定编码, 因为这个声明会忽略编码。在大多数情况下,如果你使用了任何非ASCII数据,那么使用 SQL\_ASCII设置都是不明智的,因为openGauss将无法帮助你转换或者校验非ASCII字符。 > \[!TIP]须知 > > * 指定新的数据库字符集编码必须与所选择的本地环境中(LC\_COLLATE和LC\_CTYPE)的设置兼容。 > * 当指定的字符编码集为GBK时,部分中文生僻字无法直接作为对象名。这是因为GBK第二个字节的编码范围在0x40-0x7E之间时,字节编码与ASCII字符@A-Z\[\\]^\_\`a-z{|}重叠。其中@\[\\]^\_'{|}是数据库中的操作符,直接作为对象名时,会语法报错。例如“侤”字,GBK16进制编码为0x8240,第二个字节为0x40,与ASCII“@”符号编码相同,因此无法直接作为对象名使用。如果确实要使用,可以在创建和访问对象时,通过增加双引号来规避这个问题。 > * 若客户端编码为A,服务器端编码为B,则需要满足数据库中存在编码格式A与B的转换。数据库能够支持的所有的编码格式转换详见系统表[PG\_CONVERSION](../database_reference/pg_conversion.md)(若无法转换,则建议客户端编码与服务器端编码保持一致,客户端编码可通过GUC参数client\_encoding修改)。 > * 若要指定数据库字符集编码为GB18030\_2022,且客户端编码也要设置为GB18030时,必须确保客户端操作系统支持的GB18030字符集为2022版本,否则由于GB18030字符集自身的各版本间存在不完全兼容,可能导致数据的不一致性。同时,涉及到历史数据切换为GB18030\_2022数据库时应当遵循切库流程,进行数据迁移操作。 * **LC\_COLLATE \[ = ] lc\_collate** 指定新数据库使用的字符集。例如,通过lc\_collate = 'zh\_CN.gbk'设定该参数。 该参数的使用会影响到对字符串的排序顺序(如使用ORDER BY执行,以及在文本列上使用索引的顺序)。默认是使用模板数据库的排序顺序。 取值范围:操作系统支持的字符集。 * **LC\_CTYPE \[ = ] lc\_ctype** 指定新数据库使用的字符分类。例如,通过lc\_ctype = 'zh\_CN.gbk'设定该参数。该参数的使用会影响到字符的分类,如大写、小写和数字。默认是使用模板数据库的字符分类。 取值范围:操作系统支持的字符分类。 > \[!NOTE]说明 > > * 对于lc\_collate和lc\_ctype参数的取值范围,取决于本地环境支持的字符集。 > * 当指定的字符编码集为GB18030\_2022时,其LC\_COLLATE和LC\_CTYPE的取值范围与GB18030保持一致。 > 例如:在Linux操作系统上,可通过locale -a命令获取操作系统支持的字符集列表,在应用lc\_collate和lc\_ctype参数时可从中选择用户需要的字符集和字符分类。 * **DBCOMPATIBILITY \[ = ] compatibility\_type** 指定兼容的数据库的类型,默认兼容O。 取值范围:A、B、C、PG、D。分别表示兼容O、MY、TD、POSTGRES和S数据库。在B兼容性场景下,必须加载dolphin插件才允许被连接。详见[dolphin限制](https://docs.opengauss.org/zh/docs/latest/extension_reference/dolphin.html)。 > \[!NOTE]说明 > > * A兼容性下,数据库将空字符串作为NULL处理,数据类型DATE会被替换为TIMESTAMP(0) WITHOUT TIME ZONE。 > * 将字符串转换成整数类型时,如果输入不合法,B兼容性会将输入转换为0,而其它兼容性则会报错。 > * B和PG兼容性下,CHAR和VARCHAR以字符为计数单位,其它兼容性以字节为计数单位。例如,对于UTF-8字符集,CHAR(3)在B和PG兼容性下能存放3个中文字符,而在其它兼容性下只能存放1个中文字符。 * **TABLESPACE \[ = ] tablespace\_name** 指定数据库对应的表空间。 取值范围:已存在表空间名。 * **CONNECTION LIMIT \[ = ] connlimit** 数据库可以接受的并发连接数。 > \[!TIP]须知 > > * 系统管理员不受此参数的限制。 > * connlimit数据库主节点单独统计,openGauss整体的连接数 = connlimit \* 当前正常数据库主节点个数。 取值范围:>=-1的整数。默认值为-1,表示没有限制。 有关字符编码的一些限制: * 若区域设置为C(或POSIX),则允许所有的编码类型,但是对于其他的区域设置,字符编码必须和区域设置相同。 * 若字符编码方式是SQL\_ASCII,并且修改者为管理员用户时,则字符编码可以和区域设置不相同。 * 编码和区域设置必须匹配模板数据库,除了将template0当作模板。 因为其他数据库可能会包含不匹配指定编码的数据,或者可能包含排序顺序受LC\_COLLATE和LC\_CTYPE影响的索引。复制这些数据会导致在新数据库中的索引失效。template0是不包含任何会受到影响的数据或者索引。 ## 示例 ``` --创建jim和tom用户。 openGauss=# CREATE USER jim PASSWORD 'xxxxxxxxx'; openGauss=# CREATE USER tom PASSWORD 'xxxxxxxxx'; --创建一个GBK编码的数据库music(本地环境的编码格式必须也为GBK)。 openGauss=# CREATE DATABASE music ENCODING 'GBK' template = template0; --创建数据库music2,并指定所有者为jim。 openGauss=# CREATE DATABASE music2 OWNER jim; --用模板template0创建数据库music3,并指定所有者为jim。 openGauss=# CREATE DATABASE music3 OWNER jim TEMPLATE template0; --设置music数据库的连接数为10。 openGauss=# ALTER DATABASE music CONNECTION LIMIT= 10; --将music名称改为music4。 openGauss=# ALTER DATABASE music RENAME TO music4; --将数据库music2的所属者改为tom。 openGauss=# ALTER DATABASE music2 OWNER TO tom; --设置music3的表空间为PG_DEFAULT。 openGauss=# ALTER DATABASE music3 SET TABLESPACE PG_DEFAULT; --关闭在数据库music3上缺省的索引扫描。 openGauss=# ALTER DATABASE music3 SET enable_indexscan TO off; --重置enable_indexscan参数。 openGauss=# ALTER DATABASE music3 RESET enable_indexscan; --删除数据库。 openGauss=# DROP DATABASE music2; openGauss=# DROP DATABASE music3; openGauss=# DROP DATABASE music4; --删除jim和tom用户。 openGauss=# DROP USER jim; openGauss=# DROP USER tom; --创建兼容TD格式的数据库。 openGauss=# CREATE DATABASE td_compatible_db DBCOMPATIBILITY 'C'; --创建兼容A格式的数据库。 openGauss=# CREATE DATABASE ora_compatible_db DBCOMPATIBILITY 'A'; --删除兼容TD、A格式的数据库。 openGauss=# DROP DATABASE td_compatible_db; openGauss=# DROP DATABASE ora_compatible_db; ``` ## 相关链接 [ALTER DATABASE](alter_database.md),[DROP DATABASE](drop_database.md) --- --- url: /en/docs/latest-lite/sql_reference/create_directory.md --- # CREATE DIRECTORY ## Function **CREATE DIRECTORY** creates a directory. The directory defines an alias for a path in the server file system and is used to store data files used by users. ## Precautions * When **enable\_access\_server\_directory** is set to **off**, only the initial user is allowed to create directory objects. When **enable\_access\_server\_directory** is set to **on**, the user with the SYSADMIN permission and the user who inherits the **gs\_role\_directory\_create** permission of the built-in role can create directory objects. * By default, the user who creates a directory has the read and write permissions on the directory. * The default owner of a directory is the user who creates the directory. * A directory cannot be created for the following paths: * The path contains special characters. * The path is a relative path. * The path is a symbolic link. * The following validity check is performed during directory creation: * Check whether the path exists in the OS. If it does not exist, a message is displayed, indicating the potential risks. * Check whether the database initial user **omm** has the R/W/X permissions for the OS path. If the user does not have all the permissions, a message is displayed, indicating the potential risks. * In openGauss, ensure that the path is the same on all the nodes. Otherwise, the path may fail to be found on some nodes when the directory is used. ## Syntax ``` CREATE [OR REPLACE] DIRECTORY directory_name AS 'path_name'; ``` ## Parameter Description * **directory\_name** Specifies the name of a directory. Value range: a string. It must comply with the identifier naming convention. * **path\_name** Specifies the OS path for which a directory is to be created. Value range: a valid OS path ## Examples ``` -- Create a directory. openGauss=# CREATE OR REPLACE DIRECTORY dir as '/tmp/'; ``` ## Helpful Links [ALTER DIRECTORY](alter_directory.md) and [DROP DIRECTORY](drop_directory.md) --- --- url: /en/docs/latest/sql_reference/create_directory.md --- # CREATE DIRECTORY ## Function **CREATE DIRECTORY** creates a directory. The directory defines an alias for a path in the server file system and is used to store data files used by users. ## Precautions * When enable\_access\_server\_directory=off, only the initial user is allowed to create directory objects; when enable\_access\_server\_directory=on, users with SYSADMIN permissions and users who inherit the built-in role gs\_role\_directory\_create permissions can create directory objects. * By default, the user who creates a directory has the read and write permissions on the directory. * The default owner of a directory is the user who creates the directory. * A directory cannot be created for the following paths: * The path contains special characters. * The path is a relative path. * The path is a symbolic link. * The following validity check is performed during directory creation: * Check whether the path exists in the OS. If it does not exist, a message is displayed, indicating the potential risks. * Check whether the database initial user omm has the R/W/X permissions for the OS path. If the user does not have all the permissions, a message is displayed, indicating the potential risks. * In openGauss, ensure that the path is the same on all the nodes. Otherwise, the path may fail to be found on some nodes when the directory is used. ## Syntax ``` CREATE [OR REPLACE] DIRECTORY directory_name AS 'path_name'; ``` ## Parameter Description * **directory\_name** Specifies the name of a directory. Value range: a string. It must comply with the naming convention. * **path\_name** Specifies the OS path for which a directory is to be created. Value range: a valid OS path ## Examples ``` -- Create a directory. openGauss=# CREATE OR REPLACE DIRECTORY dir as '/tmp/'; ``` ## Helpful Links [ALTER DIRECTORY](alter_directory.md) and [DROP DIRECTORY](drop_directory.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_directory.md --- # CREATE DIRECTORY ## 功能描述 使用CREATE DIRECTORY语句创建一个目录对象,该目录对象定义了服务器文件系统上目录的别名,用于存放用户使用的数据文件。 ## 注意事项 * 当enable\_access\_server\_directory=off时,只允许初始用户创建directory对象;当enable\_access\_server\_directory=on时,具有SYSADMIN权限的用户和继承了内置角色gs\_role\_directory\_create权限的用户可以创建directory对象。 * 创建用户默认拥有此路径的READ和WRITE操作权限。 * 目录的默认owner为创建directory的用户。 * 以下路径禁止创建: * 路径含特殊字符。 * 路径是相对路径。 * 路径是符号连接。 * 创建目录时会进行以下合法性校验: * 创建时会检查添加路径是否为操作系统实际存在路径,如不存在会提示用户使用风险。 * 创建时会校验数据库初始化(omm)用户对于添加路径的权限(即操作系统目录权限,读/写/执行 - R/W/X),如果权限不全,会提示用户使用风险。 * 在openGauss环境下用户指定的路径需要用户保证各节点上路径的一致性,否则在不同节点上执行会产生找不到路径的问题。 ## 语法格式 ``` CREATE [OR REPLACE] DIRECTORY directory_name AS 'path_name'; ``` ## 参数说明 * **directory\_name** 目录名称。 取值范围:字符串,要符合标识符的命名规范。 * **path\_name** 操作系统的路径。 取值范围: 有效的操作系统路径。 ## 示例 ``` --创建目录。 openGauss=# CREATE OR REPLACE DIRECTORY dir as '/tmp/'; ``` ## 相关链接 [ALTER DIRECTORY](alter_directory.md),[DROP DIRECTORY](drop_directory.md) --- --- url: /zh/docs/latest/ograc/sql_reference/create_directory.md --- # CREATE DIRECTORY ## 功能描述 创建一个目录对象。目录对象指向操作系统中的物理目录路径,它提供了一种安全的方式来管理数据库与操作系统文件的交互。在创建表时指定DIRECTORY选项创建外部表,允许用户使用SQL访问外部数据,而不需要将数据实际加载到数据库。 ## 注意事项 * 创建目录对象需要GRANT ANY DIRECTORY权限,只有SYS用户能拥有目录对象,普通用户创建的目录对象归属SYS用户 * 目录对象的路径是数据库程序所在机器的路径, 支持相对路径/绝对路径,相对路径的起始路径是程序的运行路径 * 创建目录对象前需要提前在数据库节点创建目录,目录对象及父目录的属主和属组需要设置和数据库安装用户一致,并修改权限为700 * 由于目录对象只在创建节点有效,所以无法在其他节点访问外部表 ## 语法格式 **stmt:** ```sql CREATE [OR REPLACE] DIRECTORY directory_name AS directory_path ``` ## 参数说明 * **OR REPLACE**: 已存在同名目录对象就替换 * **directory\_name**: 目录对象名字,长度限制最长63 * **directory\_path**: 目录对象所在的路径,需要用单引号括起来,长度限制最长187 ## 示例 ``` -- 创建目录对象 CREATE DIRECTORY data_dir_0 AS '/home/ogracdba/test'; -- 创建或替换目录对象 CREATE OR REPLACE DIRECTORY data_dir_0 AS '/home/ogracdba/test'; -- 创建相对路径的目录对象 CREATE DIRECTORY data_dir_1 AS './dir'; ``` --- --- url: /zh/docs/latest/sql_reference/create_directory.md --- # CREATE DIRECTORY ## 功能描述 使用CREATE DIRECTORY语句创建一个目录对象,该目录对象定义了服务器文件系统上目录的别名,用于存放用户使用的数据文件。 ## 注意事项 * 当enable\_access\_server\_directory=off时,只允许初始用户创建directory对象;当enable\_access\_server\_directory=on时,具有SYSADMIN权限的用户和继承了内置角色gs\_role\_directory\_create权限的用户可以创建directory对象。 * 创建用户默认拥有此路径的READ和WRITE操作权限。 * 目录的默认owner为创建directory的用户。 * 以下路径禁止创建: * 路径含特殊字符。 * 路径是相对路径。 * 路径是符号连接。 * 创建目录时会进行以下合法性校验: * 创建时会检查添加路径是否为操作系统实际存在路径,如不存在会提示用户使用风险。 * 创建时会校验数据库初始化(omm)用户对于添加路径的权限(即操作系统目录权限,读/写/执行 - R/W/X),如果权限不全,会提示用户使用风险。 * 在openGauss环境下用户指定的路径需要用户保证各节点上路径的一致性,否则在不同节点上执行会产生找不到路径的问题。 ## 语法格式 ``` CREATE [OR REPLACE] DIRECTORY directory_name AS 'path_name'; ``` ## 参数说明 * **directory\_name** 目录名称。 取值范围:字符串,要符合标识符的命名规范。 * **path\_name** 操作系统的路径。 取值范围: 有效的操作系统路径。 ## 示例 ``` --创建目录。 openGauss=# CREATE OR REPLACE DIRECTORY dir as '/tmp/'; ``` ## 相关链接 [ALTER DIRECTORY](alter_directory.md),[DROP DIRECTORY](drop_directory.md) --- --- url: /en/docs/latest-lite/sql_reference/create_event.md --- # CREATE EVENT ## Function CREATE EVENT creates a scheduled event. ## Precautions * Operations related to scheduled events are supported only when **sql\_compatibility** is set to **'B'**. * A user without the sysadmin permission must obtain the permission from the user who has the sysadmin permission to create, modify or delete the scheduled event. The operation permissions of the scheduled event are the same as those of creating scheduled events for the advanced package **DBE\_SCHEDULER**. * Currently, the interval expression of a scheduled event is compatible with the syntax of floating-point number, for example, interval 0.5 minutes. However, the floating-point number is rounded up during calculation. Therefore, you are not advised to use the floating-point number for the interval. * Scheduled events with the same name are not supported in the same database. * The statements to be executed in a scheduled event are any SQL statements except security-related operations. However, some statements with restrictions fail to be executed. For example, a database cannot be created by using composite statements. * The security-related operations are as follows. * Use encryption functions. * Create and set users and groups. * Connect to a database. * Encrypt a function. * The definer fails to be specified for a scheduled event in the following scenarios: * The user who operates the scheduled event does not have the sysadmin permission. * If the current user is inconsistent with the specified definer: * An initial user is specified as the definer. * A private user, O\&M administrator, or monitoring administrator is specified as the definer. * The parameter **enableSeparationOfDuty** is set to **on** to enable the separation of duties. ## Syntax ``` CREATE [DEFINER = user] EVENT [IF NOT EXISTS] event_name ON SCHEDULE schedule [ON COMPLETION [NOT] PRESERVE] [ENABLE | DISABLE | DISABLE ON SLAVE] [COMMENT 'string'] DO event_body; schedule: { AT timestamp [+ INTERVAL interval] ... | EVERY interval [STARTS timestamp [+ INTERVAL interval] ...] [ENDS timestamp [+ INTERVAL interval] ...] } interval: quantity {YEAR | MONTH | DAY | HOUR | MINUTE | SECOND | YEAR TO MONTH | DAY TO HOUR | DAY TO MINUTE | DAY TO SECOND | HOUR TO MINUTE | HOUR TO SECOND | MINUTE TO SECOND} ``` ## Parameter Description * definer Specifies the permission for the scheduled event statement to be executed during execution. By default, the permission of the user who creates the scheduled event is used. When definer is specified, the permission of the specified user is used. Only users with the sysadmin permission can specify the definer. * ON COMPLETION \[NOT] PRESERVE Once a transaction is complete, the scheduled event is deleted from the system catalog immediately by default. You can overwrite the default behavior by setting **ON COMPLETION PRESERVE**. * ENABLE | DISABLE | DISABLE ON SLAVE The scheduled event is in the **ENABLE** state by default after it is created. That is, the statement to be executed is executed immediately at the specified time. You can use the keyword **DISABLE** to change the **ENABLE** state. The performance of **DISABLE ON SLAVE** is the same as that of **DISABLE**. * COMMENT 'string' You can add comments to the scheduled event. The comments can be viewed in the **GS\_JOB\_ATTRIBUTE** table. * event\_body Specifies the statement to be executed for a scheduled event. ## Examples ``` openGauss=# CREATE TABLE t_ev(num int); openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE AT sysdate + interval 5 second + interval 33 minute DISABLE DO insert into t_ev values(0); openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE EVERY 1 minute DO insert into t_ev values(1); ``` > \[!TIP]NOTICE > > * If a scheduled event fails to be executed after being created, you can view the failure cause in the **SHOW EVENTS** or **PG\_JOB** table. > * When operations related to user passwords (such as creating weak passwords) are performed in the statements to be executed for a scheduled event, system catalog records the password in plaintext. Therefore, you are not advised to perform operations related to user passwords in the statements to be executed for the scheduled event. --- --- url: /en/docs/latest/sql_reference/create_event.md --- # CREATE EVENT ## Function CREATE EVENT creates a scheduled event. ## Precautions * Operations related to scheduled events are supported only when **sql\_compatibility** is set to **'B'**. * A user without the sysadmin permission must obtain the permission from the user who has the sysadmin permission to create, modify or delete the scheduled event. The operation permissions of the scheduled event are the same as those of creating scheduled events for the advanced package **DBE\_SCHEDULER**. * Currently, the interval expression of a scheduled event is compatible with the syntax of floating-point number, for example, interval 0.5 minutes. However, the floating-point number is rounded up during calculation. Therefore, you are not advised to use the floating-point number for the interval. * Scheduled events with the same name are not supported in the same database. * The statements to be executed in a scheduled event are any SQL statements except security-related operations. However, some statements with restrictions fail to be executed. For example, a database cannot be created by using composite statements. * The security-related operations are as follows. * Use encryption functions. * Create and set users and groups. * Connect to a database. * Encrypt a function. * The definer fails to be specified for a scheduled event in the following scenarios: * The user who operates the scheduled event does not have the sysadmin permission. * If the current user is inconsistent with the specified definer: * An initial user is specified as the definer. * A private user, O\&M administrator, or monitoring administrator is specified as the definer. * The parameter **enableSeparationOfDuty** is set to **on** to enable the separation of duties. ## Syntax ``` CREATE [DEFINER = user] EVENT [IF NOT EXISTS] event_name ON SCHEDULE schedule [ON COMPLETION [NOT] PRESERVE] [ENABLE | DISABLE | DISABLE ON SLAVE] [COMMENT 'string'] DO event_body; schedule: { AT timestamp [+ INTERVAL interval] ... | EVERY interval [STARTS timestamp [+ INTERVAL interval] ...] [ENDS timestamp [+ INTERVAL interval] ...] } interval: quantity {YEAR | MONTH | DAY | HOUR | MINUTE | SECOND | YEAR TO MONTH | DAY TO HOUR | DAY TO MINUTE | DAY TO SECOND | HOUR TO MINUTE | HOUR TO SECOND | MINUTE TO SECOND} ``` ## Parameter Description * definer Specifies the permission for the scheduled event statement to be executed during execution. By default, the permission of the user who creates the scheduled event is used. When definer is specified, the permission of the specified user is used. Only users with the sysadmin permission can specify the definer. * ON COMPLETION \[NOT] PRESERVE Once a transaction is complete, the scheduled event is deleted from the system catalog immediately by default. You can overwrite the default behavior by setting **ON COMPLETION PRESERVE**. * ENABLE | DISABLE | DISABLE ON SLAVE The scheduled event is in the **ENABLE** state by default after it is created. That is, the statement to be executed is executed immediately at the specified time. You can use the keyword **DISABLE** to change the **ENABLE** state. The performance of **DISABLE ON SLAVE** is the same as that of **DISABLE**. * COMMENT 'string' You can add comments to the scheduled event. The comments can be viewed in the **GS\_JOB\_ATTRIBUTE** table. * event\_body Specifies the statement to be executed for a scheduled event. ## Examples ``` openGauss=# CREATE TABLE t_ev(num int); openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE AT sysdate + interval 5 second + interval 33 minute DISABLE DO insert into t_ev values(0); openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE EVERY 1 minute DO insert into t_ev values(1); ``` > \[!TIP]NOTICE > > * If a scheduled event fails to be executed after being created, you can view the failure cause in the **SHOW EVENTS** or **PG\_JOB** table. > * When operations related to user passwords (such as creating weak passwords) are performed in the statements to be executed for a scheduled event, system catalog records the password in plaintext. Therefore, you are not advised to perform operations related to user passwords in the statements to be executed for the scheduled event. --- --- url: /zh/docs/latest-lite/sql_reference/create_event.md --- # CREATE EVENT ## 功能描述 创建一个新的定时任务。 ## 注意事项 * 定时任务相关操作只有sql\_compatibility = 'B'时支持。 * 创建只执行一次的定时任务时,默认情况下,无论执行成功还是失败都会被删除。可以通过使用`ON COMPLETION PRESERVE`覆盖默认行为,执行完成后不删除。 * 用户操作(创建/修改/删除)定时任务时,非sysadmin用户需要被sysadmin用户赋予操作定时任务的权限。 * 用户使用CREATE EVENT创建定时任务时,需要拥有创建定时任务schema的CREATE权限。 * 用户使用ALTER/DROP EVENT修改或删除定时任务时,需要拥有被指定schema的USAGE权限。 * 只有定时任务的属主有权ALTER或DROP定时任务。 * 定时任务的属主与被指定的definer保持一致,若创建定时任务时未指定definer,则默认为当前创建定时任务者。 * 定时任务时间间隔interval表达式目前兼容了浮点数语法,例如interval 0.5 minute,但是计算时会将浮点数取整,所以不建议interval时间间隔使用浮点数形式。 * 同一database下不支持同名定时任务。 * 定时任务中待执行语句范围是除安全相关操作以外任意SQL语句,但对于某些有约束的语句会执行失败。例如:不支持通过复合语句创建database。 * 定时任务待执行语句不支持的安全相关操作范围主要包括: * 使用加密函数。 * 创建、设置用户、group。 * 连接数据库。 * 函数加密等。 * 定时任务指定definer选项在以下场景下会指定失败: * 操作定时任务的用户不具有sysadmin权限。 * 当前用户与被指定definer不一致时: * 指定definer为初始用户。 * 指定definer为私有用户、运维管理员、监控管理员。 * 开启三权分立,enableSeparationOfDuty=on。 ## 语法格式 ``` CREATE [DEFINER = user] EVENT [IF NOT EXISTS] event_name ON SCHEDULE schedule [ON COMPLETION [NOT] PRESERVE] [ENABLE | DISABLE | DISABLE ON SLAVE] [COMMENT 'string'] DO event_body; schedule: { AT timestamp [+ INTERVAL interval] ... | EVERY interval [STARTS timestamp [+ INTERVAL interval] ...] [ENDS timestamp [+ INTERVAL interval] ...] } interval: quantity {YEAR | MONTH | DAY | HOUR | MINUTE | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE | DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND} ``` ## 参数说明 * DEFINER 定时任务待执行语句在执行时使用的权限。默认情况下使用当前创建定时任务者的权限,当definer被指定时,使用被指定用户用户权限。 definer参数只有具有sysadmin权限的用户有权指定。 * ON SCHEDULE 定时任务执行时刻。定时任务可以通过schedule设置为执行一次,也可以设置为执行多次: * AT timestamp \[+ INTERVAL interval] 表示设置定时任务只在timestamp \[+ INTERVAL interval] 时间点执行一次。 * EVERY interval 表示设置定时任务在每隔interval时间后重复执行。 * STARTS timestamp \[+ INTERVAL interval] 用户可以给可重复执行的定时任务指定起始时间,即定时任务从timestamp \[+ INTERVAL interval]时刻开始执行。当此参数为空时默认从当前时刻开始执行。 * ENDS timestamp \[+ INTERVAL interval] 用户可以给可重复执行的定时任务指定结束时间,即定时任务从timestamp \[+ INTERVAL interval]时刻停止执行。当此参数为空时默认为3999-12-31 16:00:00。 * INTERVAL 时间间隔,interval由quantity数字和时间单位组成,例如1 YEAR。 * ON COMPLETION \[NOT] PRESERVE 默认情况下,一旦事务处于完成状态,系统表中就会立刻删除该定时任务。用户可以通过设置ON COMPLETION PRESERVE来覆盖默认行为。 * ENABLE | DISABLE | DISABLE ON SLAVE 创建定时任务后,定时任务默认处于ENABLE状态,即到规定时间立即执行待执行语句。用户可以使用DISABLE关键字,改变定时任务的活动状态。DISABLE ON SLAVE表现与DISABLE一致。 * COMMENT 用户可以给定时任务添加注释,注释内容在GS\_JOB\_ATTRIBUTE表中查看。 * DO 定时任务待执行语句。 ## 示例 ``` openGauss=# CREATE TABLE t_ev(num int); --创建一个执行一次的定时任务 openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE AT sysdate() + interval 5 second + interval 33 minute DISABLE DO insert into t_ev values(0); --创建一个每隔一分钟执行一次的定时任务 openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE EVERY 1 minute DO insert into t_ev values(1); ``` > \[!TIP]须知 > > * 定时任务创建完成后如果执行失败,失败原因可以通过SHOW EVENTS或在PG\_JOB表中查看。 > * 当定时任务的待执行语句中进行涉及用户密码相关操作时(创建弱口令等),系统表及中会记录密码的明文。因此不建议用户在定时任务的待执行语句中进行涉及用户密码的相关操作。 --- --- url: /zh/docs/latest/sql_reference/create_event.md --- # CREATE EVENT ## 功能描述 创建一个新的定时任务。 ## 注意事项 * 定时任务相关操作只有sql\_compatibility = 'B'时支持。 * 创建只执行一次的定时任务时,默认情况下,无论执行成功还是失败都会被删除。可以通过使用`ON COMPLETION PRESERVE`覆盖默认行为,执行完成后不删除。 * 用户操作(创建/修改/删除)定时任务时,非sysadmin用户需要被sysadmin用户赋予操作定时任务的权限。 * 用户使用CREATE EVENT创建定时任务时,需要拥有创建定时任务schema的CREATE权限。 * 用户使用ALTER/DROP EVENT修改或删除定时任务时,需要拥有被指定schema的USAGE权限。 * 只有定时任务的属主有权ALTER或DROP定时任务。 * 定时任务的属主与被指定的definer保持一致,若创建定时任务时未指定definer,则默认为当前创建定时任务者。 * 定时任务时间间隔interval表达式目前兼容了浮点数语法,例如interval 0.5 minute,但是计算时会将浮点数取整,所以不建议interval时间间隔使用浮点数形式。 * 同一database下不支持同名定时任务。 * 定时任务中待执行语句范围是除安全相关操作以外任意SQL语句,但对于某些有约束的语句会执行失败。例如:不支持通过复合语句创建database。 * 定时任务待执行语句不支持的安全相关操作范围主要包括: * 使用加密函数。 * 创建、设置用户、group。 * 连接数据库。 * 函数加密等。 * 定时任务指定definer选项在以下场景下会指定失败: * 操作定时任务的用户不具有sysadmin权限。 * 当前用户与被指定definer不一致时: * 指定definer为初始用户。 * 指定definer为私有用户、运维管理员、监控管理员。 * 开启三权分立,enableSeparationOfDuty=on。 ## 语法格式 ``` CREATE [DEFINER = user] EVENT [IF NOT EXISTS] event_name ON SCHEDULE schedule [ON COMPLETION [NOT] PRESERVE] [ENABLE | DISABLE | DISABLE ON SLAVE] [COMMENT 'string'] DO event_body; schedule: { AT timestamp [+ INTERVAL interval] ... | EVERY interval [STARTS timestamp [+ INTERVAL interval] ...] [ENDS timestamp [+ INTERVAL interval] ...] } interval: quantity {YEAR | MONTH | DAY | HOUR | MINUTE | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE | DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND} ``` ## 参数说明 * DEFINER 定时任务待执行语句在执行时使用的权限。默认情况下使用当前创建定时任务者的权限,当definer被指定时,使用被指定用户用户权限。 definer参数只有具有sysadmin权限的用户有权指定。 * ON SCHEDULE 定时任务执行时刻。定时任务可以通过schedule设置为执行一次,也可以设置为执行多次: * AT timestamp \[+ INTERVAL interval] 表示设置定时任务只在timestamp \[+ INTERVAL interval] 时间点执行一次。 * EVERY interval 表示设置定时任务在每隔interval时间后重复执行。 * STARTS timestamp \[+ INTERVAL interval] 用户可以给可重复执行的定时任务指定起始时间,即定时任务从timestamp \[+ INTERVAL interval]时刻开始执行。当此参数为空时默认从当前时刻开始执行。 * ENDS timestamp \[+ INTERVAL interval] 用户可以给可重复执行的定时任务指定结束时间,即定时任务从timestamp \[+ INTERVAL interval]时刻停止执行。当此参数为空时默认为3999-12-31 16:00:00。 * INTERVAL 时间间隔,interval由quantity数字和时间单位组成,例如1 YEAR。 * ON COMPLETION \[NOT] PRESERVE 默认情况下,一旦事务处于完成状态,系统表中就会立刻删除该定时任务。用户可以通过设置ON COMPLETION PRESERVE来覆盖默认行为。 * ENABLE | DISABLE | DISABLE ON SLAVE 创建定时任务后,定时任务默认处于ENABLE状态,即到规定时间立即执行待执行语句。用户可以使用DISABLE关键字,改变定时任务的活动状态。DISABLE ON SLAVE表现与DISABLE一致。 * COMMENT 用户可以给定时任务添加注释,注释内容在GS\_JOB\_ATTRIBUTE表中查看。 * DO 定时任务待执行语句。 ## 示例 ``` openGauss=# CREATE TABLE t_ev(num int); --创建一个执行一次的定时任务 openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE AT sysdate() + interval 5 second + interval 33 minute DISABLE DO insert into t_ev values(0); --创建一个每隔一分钟执行一次的定时任务 openGauss=# CREATE EVENT IF NOT EXISTS event_e1 ON SCHEDULE EVERY 1 minute DO insert into t_ev values(1); ``` > \[!TIP]须知 > > * 定时任务创建完成后如果执行失败,失败原因可以通过SHOW EVENTS或在PG\_JOB表中查看。 > * 当定时任务的待执行语句中进行涉及用户密码相关操作时(创建弱口令等),系统表及中会记录密码的明文。因此不建议用户在定时任务的待执行语句中进行涉及用户密码的相关操作。 --- --- url: /en/docs/latest-lite/sql_reference/create_event_trigger.md --- # CREATE EVENT TRIGGER ## Function CREATE EVENT TRIGGER creates an event trigger to execute a specified event trigger function when a specified event occurs. ## Precautions * Only the super user or system administrator has the permission to create event triggers. * If multiple event triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name. * Event triggers may affect the performance of DDL operations, depending on the number of event triggers and the complexity of executing the function. ## Syntax ``` CREATE EVENT TRIGGER name ON event [ WHEN filter_variable IN (filter_value [, ... ]) [ AND ... ] ] EXECUTE PROCEDURE function_name() ``` ## Parameter Description * **name** Specifies the event trigger name. * **filter\_variable** Specifies the variable used by the event trigger for filtering. Currently, only TAG is supported. * **event** Specifies the events supported by the event trigger. Currently, ddl\_command\_start, ddl\_command\_end, sql\_drop and table\_rewrite are supported. * **function\_name** Specifies a user-defined function, which must be declared as taking no parameters and returning data of event\_trigger type. This function is executed when an event trigger fires. ## Examples ``` --Create database for testing openGauss=# create database test_event_trigger dbcompatibility='PG'; openGauss=# \c test_event_trigger --Create an event trigger function (for ddl_command_start and ddl_command_end events). test_event_trigger=# create function test_event_trigger() returns event_trigger as $$ BEGIN RAISE NOTICE 'test_event_trigger: % %', tg_event, tg_tag; END $$ language plpgsql; --Create an event trigger function (for the sql_drop event). test_event_trigger=# CREATE OR REPLACE FUNCTION drop_sql_command() RETURNS event_trigger AS $$ BEGIN RAISE NOTICE '% - sql_drop', tg_tag; END; $$ LANGUAGE plpgsql; --Create an event trigger function (for the table_rewrite event). test_event_trigger=# CREATE OR REPLACE FUNCTION test_evtrig_no_rewrite() RETURNS event_trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'rewrites not allowed'; END; $$; --Create an event trigger whose event type is ddl_command_start. test_event_trigger=# create event trigger regress_event_trigger on ddl_command_start execute procedure test_event_trigger(); --Create an event trigger whose event type is ddl_command_end. test_event_trigger=# create event trigger regress_event_trigger_end on ddl_command_end execute procedure test_event_trigger(); --Create an event trigger whose event type is sql_drop. test_event_trigger=# CREATE EVENT TRIGGER sql_drop_command ON sql_drop EXECUTE PROCEDURE drop_sql_command(); --Create an event trigger whose event type is table_rewrite. test_event_trigger=# create event trigger no_rewrite_allowed on table_rewrite when tag in ('alter table') execute procedure test_evtrig_no_rewrite(); --Run the DDL statement to check the event trigger effect (ddl_command_start and ddl_command_end are triggered). test_event_trigger=# create table event_trigger_table (a int); --Run the alter table statement to check the event trigger effect. ddl_command_start and table_rewrite,ddl_command_end are not triggered because rewrite is disabled. test_event_trigger=# alter table event_trigger_table alter column a type numeric; --Run the drop statement to check the event trigger effect (ddl_command_start, sql_drop, and ddl_command_end are triggered). test_event_trigger=# drop table event_trigger_table; --Modify an event trigger. test_event_trigger=# create role regress_evt_user WITH ENCRYPTED PASSWORD 'xxxxxx'; test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger RENAME TO regress_event_trigger_start; --This operation should fail. The owner of the event trigger can only be the super user. test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger_start owner to regress_evt_user; test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger_start disable; test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger_start enable always; --Delete an event trigger. test_event_trigger=# DROP EVENT TRIGGER regress_event_trigger_start; test_event_trigger=# DROP EVENT TRIGGER regress_event_trigger_end; test_event_trigger=# DROP EVENT TRIGGER sql_drop_command; test_event_trigger=# DROP EVENT TRIGGER no_rewrite_allowed; ``` ## Helpful Links [ALTER EVENT TRIGGER](alter_event_trigger.md) and [DROP EVENT TRIGGER](drop_event_trigger.md) --- --- url: /en/docs/latest/sql_reference/create_event_trigger.md --- # CREATE EVENT TRIGGER ## Function CREATE EVENT TRIGGER creates an event trigger to execute a specified event trigger function when a specified event occurs. ## Precautions * Only the super user or system administrator has the permission to create event triggers. * If multiple event triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name. * Event triggers may affect the performance of DDL operations, depending on the number of event triggers and the complexity of executing the function. ## Syntax ``` CREATE EVENT TRIGGER name ON event [ WHEN filter_variable IN (filter_value [, ... ]) [ AND ... ] ] EXECUTE PROCEDURE function_name() ``` ## Parameter Description * **name** Specifies the event trigger name. * **filter\_variable** Specifies the variable used by the event trigger for filtering. Currently, only TAG is supported. * **event** Specifies the events supported by the event trigger. Currently, ddl\_command\_start, ddl\_command\_end, sql\_drop and table\_rewrite are supported. * **function\_name** Specifies a user-defined function, which must be declared as taking no parameters and returning data of event\_trigger type. This function is executed when an event trigger fires. ## Examples ``` --Create database for testing openGauss=# create database test_event_trigger dbcompatibility='PG'; openGauss=# \c test_event_trigger --Create an event trigger function (for ddl_command_start and ddl_command_end events). test_event_trigger=# create function test_event_trigger() returns event_trigger as $$ BEGIN RAISE NOTICE 'test_event_trigger: % %', tg_event, tg_tag; END $$ language plpgsql; --Create an event trigger function (for the sql_drop event). test_event_trigger=# CREATE OR REPLACE FUNCTION drop_sql_command() RETURNS event_trigger AS $$ BEGIN RAISE NOTICE '% - sql_drop', tg_tag; END; $$ LANGUAGE plpgsql; --Create an event trigger function (for the table_rewrite event). test_event_trigger=# CREATE OR REPLACE FUNCTION test_evtrig_no_rewrite() RETURNS event_trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'rewrites not allowed'; END; $$; --Create an event trigger whose event type is ddl_command_start. test_event_trigger=# create event trigger regress_event_trigger on ddl_command_start execute procedure test_event_trigger(); --Create an event trigger whose event type is ddl_command_end. test_event_trigger=# create event trigger regress_event_trigger_end on ddl_command_end execute procedure test_event_trigger(); --Create an event trigger whose event type is sql_drop. test_event_trigger=# CREATE EVENT TRIGGER sql_drop_command ON sql_drop EXECUTE PROCEDURE drop_sql_command(); --Create an event trigger whose event type is table_rewrite. test_event_trigger=# create event trigger no_rewrite_allowed on table_rewrite when tag in ('alter table') execute procedure test_evtrig_no_rewrite(); --Run the DDL statement to check the event trigger effect (ddl_command_start and ddl_command_end are triggered). test_event_trigger=# create table event_trigger_table (a int); --Run the alter table statement to check the event trigger effect. ddl_command_start and table_rewrite,ddl_command_end are not triggered because rewrite is disabled. test_event_trigger=# alter table event_trigger_table alter column a type numeric; --Run the drop statement to check the event trigger effect (ddl_command_start, sql_drop, and ddl_command_end are triggered). test_event_trigger=# drop table event_trigger_table; --Modify an event trigger. test_event_trigger=# create role regress_evt_user WITH ENCRYPTED PASSWORD 'xxxxxx'; test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger RENAME TO regress_event_trigger_start; --This operation should fail. The owner of the event trigger can only be the super user. test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger_start owner to regress_evt_user; test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger_start disable; test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger_start enable always; --Delete an event trigger. test_event_trigger=# DROP EVENT TRIGGER regress_event_trigger_start; test_event_trigger=# DROP EVENT TRIGGER regress_event_trigger_end; test_event_trigger=# DROP EVENT TRIGGER sql_drop_command; test_event_trigger=# DROP EVENT TRIGGER no_rewrite_allowed; ``` ## Helpful Links [ALTER EVENT TRIGGER](alter_event_trigger.md) and [DROP EVENT TRIGGER](drop_event_trigger.md) --- --- url: /zh/docs/latest/sql_reference/create_event_trigger.md --- # CREATE EVENT TRIGGER ## 功能描述 创建一个事件触发器,在指定事件发生发生时执行指定的事件触发器函数。 ## 注意事项 * 只有超级用户或系统管理员才有权限创建事件触发器。 * 如果为同一事件定义了多个相同类型的事件触发器,则按事件触发器的名称字母顺序触发它们。 * 事件触发器会对ddl操作的性能有一定影响。取决于事件触发器的数量还执行函数的复杂程度。 ## 语法格式 ``` CREATE EVENT TRIGGER name ON event [ WHEN filter_variable IN (filter_value [, ... ]) [ AND ... ] ] EXECUTE { PROCEDURE | FUNCTION } function_name() ``` ## 参数说明 * **name** 事件触发器名称。 * **filter\_variable** 事件触发器用来做过滤的变量(目前仅支持TAG)。 * **event** 事件触发器支持的事件,目前支持ddl\_command\_start、ddl\_command\_end、sql\_drop、table\_rewrite。 * **function\_name** 用户定义的函数,必须声明为不带参数并返回类型为event\_trigger,在事件触发器触发时执行。 在`CREATE EVENT TRIGGER`语法中,关键字`PROCEDURE`和`FUNCTION`具有相同的含义与作用。 ## 示例 ``` --创建测试数据库 openGauss=# create database test_event_trigger dbcompatibility='PG'; openGauss=# \c test_event_trigger --创建事件触发器函数(用于ddl_command_start、ddl_command_end事件) test_event_trigger=# create function test_event_trigger() returns event_trigger as $$ BEGIN RAISE NOTICE 'test_event_trigger: % %', tg_event, tg_tag; END $$ language plpgsql; --创建事件触发器函数(用于sql_drop事件) test_event_trigger=# CREATE OR REPLACE FUNCTION drop_sql_command() RETURNS event_trigger AS $$ BEGIN RAISE NOTICE '% - sql_drop', tg_tag; END; $$ LANGUAGE plpgsql; --创建事件触发器函数(用于table_rewrite事件) test_event_trigger=# CREATE OR REPLACE FUNCTION test_evtrig_no_rewrite() RETURNS event_trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'rewrites not allowed'; END; $$; --创建事件类型为ddl_command_start的事件触发器 test_event_trigger=# create event trigger regress_event_trigger on ddl_command_start execute procedure test_event_trigger(); --创建事件类型为ddl_command_end的事件触发器 test_event_trigger=# create event trigger regress_event_trigger_end on ddl_command_end execute procedure test_event_trigger(); --创建事件类型为sql_drop的事件触发器 test_event_trigger=# CREATE EVENT TRIGGER sql_drop_command ON sql_drop EXECUTE PROCEDURE drop_sql_command(); --创建事件类型为table_rewrite的事件触发器 test_event_trigger=# create event trigger no_rewrite_allowed on table_rewrite when tag in ('alter table') execute procedure test_evtrig_no_rewrite(); --执行ddl语句查看事件触发器效果(触发ddl_command_start与ddl_command_end) test_event_trigger=# create table event_trigger_table (a int); --执行alter table语句查看事件触发器效果(触发ddl_command_start与table_rewrite,ddl_command_end由于禁止rewrite报错不触发) test_event_trigger=# alter table event_trigger_table alter column a type numeric; --执行drop语句查看事件触发器效果(触发ddl_command_start、sql_drop与ddl_command_end) test_event_trigger=# drop table event_trigger_table; --修改事件触发器 test_event_trigger=# create role regress_evt_user WITH ENCRYPTED PASSWORD 'EvtUser123'; test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger RENAME TO regress_event_trigger_start; --应该失败,事件触发器的owner只能为超级用户 test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger_start owner to regress_evt_user; test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger_start disable; test_event_trigger=# ALTER EVENT TRIGGER regress_event_trigger_start enable always; --删除事件触发器 test_event_trigger=# DROP EVENT TRIGGER regress_event_trigger_start; test_event_trigger=# DROP EVENT TRIGGER regress_event_trigger_end; test_event_trigger=# DROP EVENT TRIGGER sql_drop_command; test_event_trigger=# DROP EVENT TRIGGER no_rewrite_allowed; ``` ## 相关链接 [ALTER EVENT TRIGGER](alter_event_trigger.md),[DROP EVENT TRIGGER](drop_event_trigger.md) --- --- url: /zh/docs/latest/sql_reference/create_extension.md --- # CREATE Extension ## 功能描述 安装一个扩展。 ## 注意事项 * CREATE Extension命令安装一个新的扩展到一个数据库中,必须保证没有同名的扩展已经被安装。 * 安装一个扩展意味着执行一个扩展的脚本文件,这个脚本会创建一个新的SQL实体,例如函数、数据类型、操作符、和索引支持的方法。 * 安装扩展需要有和创建他的组件对象相同的权限。对于大多数扩展这意味着需要超户或者数据库所有者的权限,对于后续的权限检查和该扩展脚本所创建的实体,运行CREATE Extension命令的角色将变为扩展的所有者。 ## 语法格式 ``` CREATE Extension [ IF NOT EXISTS ] Extension_name [ WITH ] [ SCHEMA schema_name ] [ VERSION version ] [ FROM old_version ]; ``` ## 参数说明 * **IF NOT EXISTS** 如果系统已经存在一个同名的扩展,不会报错。这种情况下会给出一个提示。请注意该参数不保证系统存在的扩展和现在脚本创建的扩展相同。 * **Extension\_name** 将被安装扩展的名字。 * **schema\_name** 扩展的实例被安装在该模式下,扩展的内容可以被重新安装。指定的模式必须已经存在,如果没有指定,扩展的控制文件也不指定一个模式,这样将使用默认模式。 > \[!WARNING]注意 > 扩展不认为它在任何模式里面:扩展在一个数据库范围内的名字是不受限制的,但是一个扩展的实例是属于一个模式的。 * **version** 安装扩展的版本,可以写为一个标识符或者字符串.默认的版本在扩展的控制文件中指定。 * **old\_version** 当你想升级安装“old style” 模块中没有的内容时,你必须指定FROM old\_version。这个选项使CREATE Extension 运行一个安装脚本将新的内容安装到扩展中,而不是创建一个新的实体.注意SCHEMA指定了包括这些已存在实体的模式。 ## 示例 在当前数据库安装hstore扩展: ``` CREATE Extension hstore; ``` --- --- url: /en/docs/latest-lite/sql_reference/create_extension.md --- # CREATE EXTENSION ## Function **CREATE EXTENSION** installs an extension. ## Precautions * The **CREATE EXTENSION** command installs a new extension to a database. Ensure that no extension with the same name has been installed. * Installing an extension means executing an extended script file that creates a SQL entity, such as a function, data type, operator, and index-supported method. * Installing an extension requires the same permissions as creating its component objects. For most extensions, this means that the superuser or database owner's permissions are required. For subsequent permission checks and entities created by the extension script, the role that runs the **CREATE EXTENSION** command becomes the owner of the extension. ## Syntax ``` CREATE EXTENSION [ IF NOT EXISTS ] extension_name [ WITH ] [ SCHEMA schema_name ] [ VERSION version ] [ FROM old_version ] ``` ## Parameter Description * **IF NOT EXISTS** If an extension with the same name exists in the system, no error is reported. However, a message is displayed. Note that this parameter does not ensure that the existing extensions of the system are the same as those created by the script. * **extension\_name** Name of the extension to be installed. * **schema\_name** The extension instance is installed in this schema, and the extended content can be reinstalled. The specified schema must exist. If it is not specified, the extended control file does not specify a schema either. In this case, the default schema is used. > \[!WARNING]CAUTION > > Extensions are not considered to be in any schema (no restriction is posed on the name of extensions within the scope of a database), but an extension instance belongs to a schema. * **version** Version of the extension to be installed, which can be written as an identifier or a string. The default version is specified in the extended control file. * **old\_version** If you want to upgrade the content that is not contained in the **old style** module, you must specify **FROM old\_version**. This option makes **CREATE EXTENSION** run an installation script to install new content into the extension instead of creating an entity. Note that **SCHEMA** specifies the schema that includes these existing entities. ## Examples Install the **hstore** extension in the current database. ``` CREATE EXTENSION hstore; ``` --- --- url: /en/docs/latest/sql_reference/create_extension.md --- # CREATE EXTENSION ## Function **CREATE EXTENSION** installs an extension. ## Precautions * The **CREATE EXTENSION** command installs a new extension to a database. Ensure that no extension with the same name has been installed. * Installing an extension means executing an extended script file that creates a SQL entity, such as a function, data type, operator, and index-supported method. * Installing an extension requires the same permissions as creating its component objects. For most extensions, this means that the superuser or database owner's permissions are required. For subsequent permission checks and entities created by the extension script, the role that runs the **CREATE EXTENSION** command becomes the owner of the extension. ## Syntax ``` CREATE EXTENSION [ IF NOT EXISTS ] extension_name [ WITH ] [ SCHEMA schema_name ] [ VERSION version ] [ FROM old_version ] ``` ## Parameter Description * **IF NOT EXISTS** If an extension with the same name exists in the system, no error is reported. However, a message is displayed. Note that this parameter does not ensure that the existing extensions of the system are the same as those created by the script. * **extension\_name** Name of the extension to be installed. * **schema\_name** The extension instance is installed in this schema, and the extended content can be reinstalled. The specified schema must exist. If it is not specified, the extended control file does not specify a schema either. In this case, the default schema is used. > \[!WARNING]CAUTION > Extensions are not considered to be in any schema (no restriction is posed on the name of extensions within the scope of a database), but an extension instance belongs to a schema. * **version** Version of the extension to be installed, which can be written as an identifier or a string. The default version is specified in the extended control file. * **old\_version** If you want to upgrade the content that is not contained in the **old style** module, you must specify **FROM old\_version**. This option makes **CREATE EXTENSION** run an installation script to install new content into the extension instead of creating an entity. Note that **SCHEMA** specifies the schema that includes these existing entities. ## Examples Install the **hstore** extension in the current database. ``` CREATE EXTENSION hstore; ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_extension.md --- # CREATE EXTENSION ## 功能描述 安装一个扩展。 ## 注意事项 * CREATE EXTENSION命令安装一个新的扩展到一个数据库中,必须保证没有同名的扩展已经被安装。 * 安装一个扩展意味着执行一个扩展的脚本文件,这个脚本会创建一个新的SQL实体,例如函数、数据类型、操作符、和索引支持的方法。 * 安装扩展需要有和创建他的组件对象相同的权限。对于大多数扩展这意味着需要超户或者数据库所有者的权限,对于后续的权限检查和该扩展脚本所创建的实体,运行CREATE EXTENSION命令的角色将变为扩展的所有者。 ## 语法格式 ``` CREATE EXTENSION [ IF NOT EXISTS ] extension_name [ WITH ] [ SCHEMA schema_name ] [ VERSION version ] [ FROM old_version ]; ``` ## 参数说明 * **IF NOT EXISTS** 如果系统已经存在一个同名的扩展,不会报错。这种情况下会给出一个提示。请注意该参数不保证系统存在的扩展和现在脚本创建的扩展相同。 * **extension\_name** 将被安装扩展的名字。 * **schema\_name** 扩展的实例被安装在该模式下,扩展的内容可以被重新安装。指定的模式必须已经存在,如果没有指定,扩展的控制文件也不指定一个模式,这样将使用默认模式。 > \[!WARNING]注意 > > 扩展不认为它在任何模式里面:扩展在一个数据库范围内的名字是不受限制的,但是一个扩展的实例是属于一个模式的。 * **version** 安装扩展的版本,可以写为一个标识符或者字符串.默认的版本在扩展的控制文件中指定。 * **old\_version** 当你想升级安装"old style" 模块中没有的内容时,你必须指定FROM old\_version。这个选项使CREATE EXTENSION 运行一个安装脚本将新的内容安装到扩展中,而不是创建一个新的实体.注意SCHEMA指定了包括这些已存在实体的模式。 ## 示例 在当前数据库安装hstore扩展: ``` CREATE EXTENSION hstore; ``` --- --- url: /en/docs/latest/sql_reference/create_foreign_data_wrapper.md --- # CREATE FOREIGN DATA WRAPPER ## Function Description Defines a new foreign data wrapper (FDW). ## Syntax ``` CREATE FOREIGN DATA WRAPPER name [ HANDLER handler_function | NO HANDLER ] [ VALIDATOR validator_function | NO VALIDATOR ] [ OPTIONS ( option 'value' [,...] ) ] ``` ## Parameter Description * **name** Specifies the name of an FDW to be created. * **HANDLER handler\_function** **handler\_function** is the name of the previously registered function that will be called to retrieve the execution function of the foreign table. The handler function cannot contain any parameter, and its return type must be fdw\_handler. * **VALIDATOR validator\_function** **validator\_function** is the name of the previously registered function that will be called to check the general options of the given FDW, as well as the options for the foreign server and user mapping using the FDW. If no validator function is specified, options are not checked at creation time. (The FDW may ignore or reject invalid option specifications at runtime, depending on the implementation.) The validator function must accept two arguments: one is of type text\[], which will contain an array of options stored in the system directory, and the other is of type oid, which will be the oid of the system directory that contains the options. The return type is ignored. The function should report invalid options using the ereport (ERROR) function. * **OPTIONS (option 'value' \[,...])** Specifies options for the new FDW. The allowed option names and values are specific to each FDW and validated using the FDW validator function. The option name must be unique. ## Examples ``` --Creates a useless FDW named dummy. openGauss=# CREATE FOREIGN DATA WRAPPER dummy; --Use the handler function file_fdw_handler to create an FDW named file. openGauss=# CREATE FOREIGN DATA WRAPPER file HANDLER file_fdw_handler; --Create an FDW named mywrapper. openGauss=# CREATE FOREIGN DATA WRAPPER mywrapper OPTIONS (debug 'true'); ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_foreign_data_wrapper.md --- # CREATE FOREIGN DATA WRAPPER ## 功能描述 定义一个新的外部数据包装器。 ## 语法格式 ``` CREATE FOREIGN DATA WRAPPER name [ HANDLER handler_function | NO HANDLER ] [ VALIDATOR validator_function | NO VALIDATOR ] [ OPTIONS ( option 'value' [,...] ) ] ``` ## 参数说明 * **name** 要创建的外部数据包装器名。 * **HANDLER handler\_function** handler\_function是先前注册的函数的名称,该函数将被调用以检索外部表的执行函数。处理器函数不能带任何参数,其返回类型必须是fdw\_handler。 * **VALIDATOR validator\_function** validator\_function是先前注册的函数的名称,该函数将被调用以检查给定给外部数据包装器的通用选项,以及使用外部数据包装器的外部服务器和用户映射的选项。如果未指定验证器函数或未指定validator,则在创建时不会检查选项。(外部数据包装器可能会在运行时忽略或拒绝无效的选项规范,具体取决于实现。)验证器函数必须接受两个参数:一个类型为text\[],它将包含存储在系统目录中的选项数组,另一个类型是oid,它将是包含选项的系统目录的oid。忽略返回类型;该函数应该使用ereport(ERROR)函数报告无效选项。 * **OPTIONS (option 'value' \[,...])** 该子句指定新外部数据包装器的选项。允许的选项名称和值特定于每个外部数据包装器,并使用外部数据包装器的验证器函数进行验证。选项名称必须唯一。 ## 示例 ``` --创建一个无用的外部数据包装器dummy。 openGauss=# CREATE FOREIGN DATA WRAPPER dummy; --使用处理器函数file_fdw_handler创建外部数据包装器file。 openGauss=# CREATE FOREIGN DATA WRAPPER file HANDLER file_fdw_handler; --创建外部数据包装器mywrapper openGauss=# CREATE FOREIGN DATA WRAPPER mywrapper OPTIONS (debug 'true'); ``` --- --- url: /zh/docs/latest/sql_reference/create_foreign_data_wrapper.md --- # CREATE FOREIGN DATA WRAPPER ## 功能描述 定义一个新的外部数据包装器。 ## 语法格式 ``` CREATE FOREIGN DATA WRAPPER name [ HANDLER handler_function | NO HANDLER ] [ VALIDATOR validator_function | NO VALIDATOR ] [ OPTIONS ( option 'value' [,...] ) ] ``` ## 参数说明 * **name** 要创建的外部数据包装器名。 * **HANDLER handler\_function** handler\_function是先前注册的函数的名称,该函数将被调用以检索外部表的执行函数。处理器函数不能带任何参数,其返回类型必须是fdw\_handler。 * **VALIDATOR validator\_function** validator\_function是先前注册的函数的名称,该函数将被调用以检查给定给外部数据包装器的通用选项,以及使用外部数据包装器的外部服务器和用户映射的选项。如果未指定验证器函数或未指定validator,则在创建时不会检查选项。(外部数据包装器可能会在运行时忽略或拒绝无效的选项规范,具体取决于实现。)验证器函数必须接受两个参数:一个类型为text\[],它将包含存储在系统目录中的选项数组,另一个类型是oid,它将是包含选项的系统目录的oid。忽略返回类型;该函数应该使用ereport(ERROR)函数报告无效选项。 * **OPTIONS (option 'value' \[,...])** 该子句指定新外部数据包装器的选项。允许的选项名称和值特定于每个外部数据包装器,并使用外部数据包装器的验证器函数进行验证。选项名称必须唯一。 ## 示例 ``` --创建一个无用的外部数据包装器dummy。 openGauss=# CREATE FOREIGN DATA WRAPPER dummy; --使用处理器函数file_fdw_handler创建外部数据包装器file。 openGauss=# CREATE FOREIGN DATA WRAPPER file HANDLER file_fdw_handler; --创建外部数据包装器mywrapper openGauss=# CREATE FOREIGN DATA WRAPPER mywrapper OPTIONS (debug 'true'); ``` --- --- url: /en/docs/latest-lite/sql_reference/create_foreign_table.md --- # CREATE FOREIGN TABLE ## Function **CREATE FOREIGN TABLE** creates a foreign table. ## Precautions System columns (such as **tableoid** and **ctid**) cannot be used in foreign tables. Foreign tables in the Private or Shared schema require the initial user permission or the O\&M administrator permission in O\&M mode (operation\_mode). ## Syntax ``` CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( [ column_name type_name [ OPTIONS ( option 'value' [, ... ] ) ] [ COLLATE collation ] [ column_constraint [ ... ] ] [, ... ] ] ) SERVER server_name [ OPTIONS ( option 'value' [, ... ] ) ] The column_constraint can be: [ CONSTRAINT constraint_name ] { NOT NULL | NULL | DEFAULT default_expr } ``` ## Parameter Description * **IF NOT EXISTS** Sends a notice, but does not throw an error, if a table with the same name exists. * **table\_name** Specifies the name of a foreign table. Value range: a string. It must comply with the identifier naming convention. * **column\_name** Specifies the name of a column in the foreign table. Value range: a string. It must comply with the identifier naming convention. * **type\_name** Specifies the data type of the column. * **SERVER server\_name** Specifies the server name of the foreign table. The default value is **mot\_server**. * **OPTIONS ( option 'value' \[, ... ] )** Options are related to the new foreign table or the columns in the foreign table. The allowed option names and values are specified by each foreign data wrapper, and are also verified by the verification function of the foreign data wrapper. The option name must be unique (although table options and table column options can share the same name). * Options supported by **oracle\_fdw** are as follows: * **table** Name of a table on the Oracle server. The value must be the same as the table name recorded in the Oracle system catalog. Generally, the value consists of uppercase letters. * **schema** Schema (or owner) corresponding to the table. The value must be the same as the table name recorded in the Oracle system catalog. Generally, the value consists of uppercase letters. * Options supported by **mysql\_fdw** are as follows: * **dbname** Name of the MySQL database. * **table\_name** Name of a table in the MySQL database. * Options supported by **postgres\_fdw** are as follows: * **schema\_name** Schema name of a remote server. If this option is not specified, the schema name of the foreign table is used as the schema name of the remote server. * **table\_name** Table name of a remote server. If this option is not specified, the name of the foreign table is used as the table name of the remote server. * **column\_name** Column name of a table on a remote server. If this option is not specified, the column name of the foreign table is used as the column name of a table on a remote server. * Options supported by **file\_fdw** are as follows: * filename File to be read. This parameter is mandatory and must be an absolute path. * format File format of the remote server, which is the same as the **FORMAT** option in the **COPY** statement. The value can be **text**, **csv**, **binary**, or **fixed**. * header Specifies whether a specified file has a header, which is the same as the **HEADER** option of the **COPY** statement. * delimiter File delimiter, which is the same as the **DELIMITER** option of the **COPY** statement. * quote Quote character of a file, which is the same as the **QUOTE** option of the **COPY** statement. * escape Escape character of a file, which is the same as the **ESCAPE** option of the **COPY** statement. * null Null string of a file, which is the same as the **NULL** option of the **COPY** statement. * encoding Encoding of a file, which is the same as the **ENCODING** option of the **COPY** statement. * force\_not\_null This is a Boolean option. If it is true, the value of the declared field cannot be an empty string. This option is the same as the **FORCE\_NOT\_NULL** option of the **COPY** statement. > \[!NOTE]NOTE > For details about how to use **file\_fdw**, see [file\_fdw](../database_administration_guide/file_fdw.md). ## Helpful Links [ALTER FOREIGN TABLE](alter_foreign_table.md) and [DROP FOREIGN TABLE](drop_foreign_table.md) --- --- url: /en/docs/latest/sql_reference/create_foreign_table.md --- # CREATE FOREIGN TABLE ## Function **CREATE FOREIGN TABLE** creates a foreign table. ## Precautions System columns (such as **tableoid** and **ctid**) cannot be used in foreign tables, Among them, the appearance of Private and Shares mode requires the initial user and operation and maintenance administrator authority in operation mode (operation\_mode). ## Syntax ``` CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( { column_name type_name POSITION ( offset, length ) [column_constraint ] | LIKE source_table | table_constraint } [, ...] ) SEVER gsmpp_server OPTIONS ( { option_name ' value ' } [, ...] ) [ { WRITE ONLY | READ ONLY }] [ WITH error_table_name | LOG INTO error_table_name ] [ REMOTE LOG 'name' ] [PER NODE REJECT LIMIT 'value'] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ]; CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( { column_name type_name [ { [CONSTRAINT constraint_name] NULL | [CONSTRAINT constraint_name] NOT NULL | column_constraint [...]} ] | table_constraint} [, ...] ) SERVER server_name OPTIONS ( { option_name ' value ' } [, ...] ) DISTRIBUTE BY {ROUNDROBIN | REPLICATION} [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] [ PARTITION BY ( column_name ) [AUTOMAPPED]] ; CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( [ { column_name type_name | LIKE source_table } [, ...] ] ) SERVER server_name OPTIONS ( { option_name ' value ' } [, ...] ) [ READ ONLY ] [ DISTRIBUTE BY {ROUNDROBIN} ] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ]; The column_constraint can be: [ CONSTRAINT constraint_name ] { PRIMARY KEY | UNIQUE } [ NOT ENFORCED [ ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION ] | ENFORCED ] where table_constraint can be: [ CONSTRAINT constraint_name ] { PRIMARY KEY | UNIQUE } ( column_name ) [ NOT ENFORCED [ ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION ] | ENFORCED ] ``` ## Parameter Description * **IF NOT EXISTS** Sends a notice, but does not throw an error, if a table with the same name exists. * **table\_name** Specifies the name of a foreign table. Value range: a string. It must comply with the naming convention. * **column\_name** Specifies the name of a column in the foreign table. Value range: a string. It must comply with the naming convention. * **type\_name** Specifies the data type of the column. * **SERVER server\_name** Specifies the server name of the foreign table. The default value is **mot\_server**. * **OPTIONS ( option 'value' \[, ... ] )** Options are related to the new foreign table or the columns in the foreign table. The allowed option names and values are specified by each foreign data wrapper, and are also verified by the verification function of the foreign data wrapper. The option name must be unique (although table options and table column options can share the same name). * Options supported by **oracle\_fdw** are as follows: * **table** Name of a table on the Oracle server. The value must be the same as the table name recorded in the Oracle system catalog. Generally, the value consists of uppercase letters. * **schema** Schema (or owner) corresponding to the table. The value must be the same as the table name recorded in the Oracle system catalog. Generally, the value consists of uppercase letters. * Options supported by **mysql\_fdw** are as follows: * **dbname** Name of the MySQL database. * **table\_name** Name of a table in the MySQL database. * Options supported by **postgres\_fdw** are as follows: * **schema\_name** Schema name of a remote server. If this option is not specified, the schema name of the foreign table is used as the schema name of the remote server. * **table\_name** Table name of a remote server. If this option is not specified, the name of the foreign table is used as the table name of the remote server. * **column\_name** Column name of a table on a remote server. If this option is not specified, the column name of the foreign table is used as the column name of a table on a remote server. * Options supported by **file\_fdw** are as follows: * filename File to be read. This parameter is mandatory and must be an absolute path. * format File format of the remote server, which is the same as the **FORMAT** option in the **COPY** statement. The value can be **text**, **csv**, **binary**, or **fixed**. * header Specifies whether a specified file has a header, which is the same as the **HEADER** option of the **COPY** statement. * delimiter File delimiter, which is the same as the **DELIMITER** option of the **COPY** statement. * quote Quote character of a file, which is the same as the **QUOTE** option of the **COPY** statement. * escape Escape character of a file, which is the same as the **ESCAPE** option of the **COPY** statement. * null Null string of a file, which is the same as the **NULL** option of the **COPY** statement. * encoding Encoding of a file, which is the same as the **ENCODING** option of the **COPY** statement. * force\_not\_null This is a Boolean option. If it is true, the value of the declared field cannot be an empty string. This option is the same as the **FORCE\_NOT\_NULL** option of the **COPY** statement. > \[!NOTE]NOTE > For details about how to use **file\_fdw**, see [file\_fdw](../database_administration_guide/file_fdw.md). ## Helpful Links [ALTER FOREIGN TABLE](alter_foreign_table.md) and [DROP FOREIGN TABLE](drop_foreign_table.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_foreign_table.md --- # CREATE FOREIGN TABLE ## 功能描述 创建外表。 ## 注意事项 外表中暂不支持使用系统列(如tableoid,ctid等),其中Private和Shared模式的外表,需要初始用户或者运维模式下(operation\_mode)的运维管理员权限。 ## 语法格式 ``` CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( [ column_name type_name [ OPTIONS ( option 'value' [, ... ] ) ] [ COLLATE collation ] [ column_constraint [ ... ] ] [, ... ] ] ) SERVER server_name [ OPTIONS ( option 'value' [, ... ] ) ] 这里column_constraint 可以是: [ CONSTRAINT constraint_name ] { NOT NULL | NULL | DEFAULT default_expr } ``` ## 参数说明 * **IF NOT EXISTS** 如果已经存在相同名称的表,不会抛出一个错误,而会发出一个通知,告知表关系已存在。 * **table\_name** 外表的表名。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 外表中的字段名。 取值范围:字符串,要符合标识符的命名规范。 * **type\_name** 字段的数据类型。 * **SERVER server\_name** 外表的server名称。默认值为mot\_server。 * **OPTIONS ( option 'value' \[, ... ] )** 选项与新外部表或外部表中的字段有关。允许的选项名称和值,是由每一个外部数据封装器指定的。 也是通过外部数据封装器的验证函数来验证。重复的选项名称是不被允许的(尽管表选项和表字段选项可以有相同的名字)。 * oracle\_fdw支持的options包括: * **table** oracle server侧的表名。需要同oracle系统表中记录的表名完全一致,通常是由大写字符组成。 * **schema** 表所对应的schema(或owner)。需要同oracle系统表中记录的表名完全一致,通常是由大写字符组成。 * mysql\_fdw支持的options包括: * **dbname** MySQL的database名称。 * **table\_name** MySQL侧的表名。 * postgres\_fdw支持的options包括: * **schema\_name** 远端server的schema名称。如果不指定的话,将使用外表自身的schema名称作为远端的schema名称。 * **table\_name** 远端server的表名。如果不指定的话,将使用外表自身的表名作为远端的表名。 * **column\_name** 远端server的表的列名。如果不指定的话,将使用外表自身的列名作为远端的的表的列名。 * file\_fdw支持的options包括: * filename 指定要读取的文件,必需的参数,且必须是一个绝对路径名。 * format 远端server的文件格式,支持text/csv/binary/fixed四种格式,和COPY语句的FORMAT选项相同。 * header 指定的文件是否有标题行,与COPY语句的HEADER选项相同。 * delimiter 指定文件的分隔符,与COPY的DELIMITER选项相同。 * quote 指定文件的引用字符,与COPY的QUOTE选项相同。 * escape 指定文件的转义字符,与COPY的ESCAPE选项相同。 * null 指定文件的null字符串,与COPY的NULL选项相同。 * encoding 指定文件的编码,与COPY的ENCODING选项相同。 * force\_not\_null 这是一个布尔选项。如果为真,则声明字段的值不应该匹配空字符串(也就是文件级别null选项)。与COPY的 FORCE\_NOT\_NULL选项里的字段相同。 > \[!NOTE]说明 > file\_fdw更多使用请参见[file\_fdw](../../../docs/zh/database_administration_guide/file_fdw.md)。 ## 相关链接 [ALTER FOREIGN TABLE](alter_foreign_table.md),[DROP FOREIGN TABLE](drop_foreign_table.md) --- --- url: /zh/docs/latest/sql_reference/create_foreign_table.md --- # CREATE FOREIGN TABLE ## 功能描述 创建外表。 ## 注意事项 外表中暂不支持使用系统列(如tableoid、ctid等),其中Private和Shares模式的外表,需要初始用户和运维模式下(operation\_mode)的运维管理员权限。\ 资源池化不支持使用外表执行create table as操作,因为资源池化不支持事务隔离级别为可重复读的特性。 ## 语法格式 ``` CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( { column_name type_name POSITION ( offset, length ) [column_constraint ] | LIKE source_table | table_constraint } [, ...] ) SEVER gsmpp_server OPTIONS ( { option_name ' value ' } [, ...] ) [ { WRITE ONLY | READ ONLY }] [ WITH error_table_name | LOG INTO error_table_name ] [ REMOTE LOG 'name' ] [PER NODE REJECT LIMIT 'value'] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ]; CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( { column_name type_name [ { [CONSTRAINT constraint_name] NULL | [CONSTRAINT constraint_name] NOT NULL | column_constraint [...]} ] | table_constraint} [, ...] ) SERVER server_name OPTIONS ( { option_name ' value ' } [, ...] ) DISTRIBUTE BY {ROUNDROBIN | REPLICATION} [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] [ PARTITION BY ( column_name ) [AUTOMAPPED]] ; CREATE FOREIGN TABLE [ IF NOT EXISTS ] table_name ( [ { column_name type_name | LIKE source_table } [, ...] ] ) SERVER server_name OPTIONS ( { option_name ' value ' } [, ...] ) [ READ ONLY ] [ DISTRIBUTE BY {ROUNDROBIN} ] [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ]; 这里 column_constraint 可以是: [ CONSTRAINT constraint_name ] { PRIMARY KEY | UNIQUE } [ NOT ENFORCED [ ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION ] | ENFORCED ] where table_constraint can be: [ CONSTRAINT constraint_name ] { PRIMARY KEY | UNIQUE } ( column_name ) [ NOT ENFORCED [ ENABLE QUERY OPTIMIZATION | DISABLE QUERY OPTIMIZATION ] | ENFORCED ] ``` ## 参数说明 * **IF NOT EXISTS** 如果已经存在相同名称的表,不会抛出一个错误,而会发出一个通知,告知表关系已存在。 * **table\_name** 外表的表名。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 外表中的字段名。 取值范围:字符串,要符合标识符的命名规范。 * **type\_name** 字段的数据类型。 * **SERVER server\_name** 外表的server名称。默认值为mot\_server。 * **OPTIONS ( option 'value' \[, ... ] )** 选项与新外部表或外部表中的字段有关。允许的选项名称和值,是由每一个外部数据封装器指定的。 也是通过外部数据封装器的验证函数来验证。重复的选项名称是不被允许的(尽管表选项和表字段选项可以有相同的名字)。 * oracle\_fdw支持的options包括: * **table** oracle server侧的表名。需要同oracle系统表中记录的表名完全一致,通常是由大写字符组成。 * **schema** 表所对应的schema(或owner)。需要同oracle系统表中记录的表名完全一致,通常是由大写字符组成。 * mysql\_fdw支持的options包括: * **dbname** MySQL的database名称。 * **table\_name** MySQL侧的表名。 * postgres\_fdw支持的options包括: * **schema\_name** 远端server的schema名称。如果不指定的话,将使用外表自身的schema名称作为远端的schema名称。 * **table\_name** 远端server的表名。如果不指定的话,将使用外表自身的表名作为远端的表名。 * **column\_name** 远端server的表的列名。如果不指定的话,将使用外表自身的列名作为远端的的表的列名。 * file\_fdw支持的options包括: * filename 指定要读取的文件,必需的参数,且必须是一个绝对路径名。 * format 远端server的文件格式,支持text/csv/binary/fixed四种格式,和COPY语句的FORMAT选项相同。 * header 指定的文件是否有标题行,与COPY语句的HEADER选项相同。 * delimiter 指定文件的分隔符,与COPY的DELIMITER选项相同。 * quote 指定文件的引用字符,与COPY的QUOTE选项相同。 * escape 指定文件的转义字符,与COPY的ESCAPE选项相同。 * null 指定文件的null字符串,与COPY的NULL选项相同。 * encoding 指定文件的编码,与COPY的ENCODING选项相同。 * force\_not\_null 这是一个布尔选项。如果为真,则声明字段的值不应该匹配空字符串(也就是,文件级别null选项)。与COPY的 FORCE\_NOT\_NULL选项里的字段相同。 > \[!NOTE]说明 > file\_fdw更多使用请参见[file\_fdw](../database_administration_guide/file_fdw.md)。 ## 相关链接 [ALTER FOREIGN TABLE](alter_foreign_table.md),[DROP FOREIGN TABLE](drop_foreign_table.md) --- --- url: /en/docs/latest-lite/sql_reference/create_function.md --- # CREATE FUNCTION ## Function **CREATE FUNCTION** creates a function. ## Precautions * If the parameters or return values of a function have precision, the precision is not checked. * When creating a function, you are advised to explicitly specify the schemas of tables in the function definition. Otherwise, the function may fail to be executed. * **current\_schema** and **search\_path** specified by **SET** during function creation are invalid. **search\_path** and **current\_schema** before and after function execution should be the same. * If a function has output parameters, the **SELECT** statement uses the default values of the output parameters when calling the function. When the **CALL** statement calls the function, it requires that the output parameters must be specified. When the **CALL** statement calls an overloaded **PACKAGE** function, it can use the default values of the output parameters. For details, see examples in [CALL](call.md). * Only the functions compatible with PostgreSQL or those with the **PACKAGE** attribute can be overloaded. After **REPLACE** is specified, a new function is created instead of replacing a function if the number of parameters, parameter type, or return value is different. * You can use the **SELECT** statement to specify different parameters using identical functions, but cannot use the **CALL** statement to call identical functions without the **PACKAGE** attribute. * When you create a function, you cannot insert other agg functions out of the avg function or other functions. * By default, the permissions to execute new functions are granted to **PUBLIC**. For details, see [GRANT](grant.md). You can revoke the default execution permissions from **PUBLIC** and grant them to other users as needed. To avoid the time window during which new functions can be accessed by all users, create functions in transactions and set function execution permissions. * When functions without parameters are called inside another function, you can omit brackets and call functions using their names directly. * When functions with output parameters are called inside another function which is an assignment expression, you can omit the output parameters of the called functions. * Oracle-compatible functions support viewing, exporting, and importing parameter comments. * Oracle-compatible functions support viewing, exporting, and importing comments between IS/AS and plsql\_body. * Users granted with the **CREATE ANY FUNCTION** permission can create or replace functions in the user schemas. * The default permission on a function is **SECURITY INVOKER**. To change the default permission to **SECURITY DEFINER**, set the GUC parameter **behavior\_compat\_options** to **'plsql\_security\_definer'**. * For PL/pgSQL functions, after **behavior\_compat\_options** is set to **'proc\_outparam\_override'**, the behavior of **out/inout** changes. In the functions, **return** and **out/inout** can be returned at the same time. Before the parameter is enabled, only **return** is returned. For details, see [Examples](#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821). * For PL/pgSQL functions, after **behavior\_compat\_options** is set to **'proc\_outparam\_override'**, the restrictions are as follows: 1. If a function with the **out/inout** parameter already exists in the same schema or package, you cannot create another function with the same name with the **out/inout** parameter. 2. The **out** parameter must be added no matter whether the **SELECT** or **CALL** statement is used to call a stored procedure. 3. In some scenarios, functions cannot be used in expressions (compared with those before the parameter is enabled), for example, left assignment in a stored procedure and **call function**. For details, see [Examples](#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821). 4. Functions without **return** cannot be called. **perform function** can be used to call functions. 5. When a function is called in a stored procedure, **out/inout** cannot be set to a constant. For details, see [Examples](#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821). ## Syntax * Syntax (compatible with PostgreSQL) for creating a customized function: ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) [ RETURNS rettype [ DETERMINISTIC ] | RETURNS TABLE ( { column_name column_type } [, ...] )] LANGUAGE lang_name [ {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | [ NOT ] LEAKPROOF | WINDOW | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AU THID DEFINER | AUTHID CURRENT_USER} | {FENCED | NOT FENCED} | {PACKAGE} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' ] [...] { AS 'definition' | AS 'obj_file', 'link_symbol' } ``` * O syntax of creating a customized function: ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ DETERMINISTIC ] [ {IMMUTABLE | STABLE | VOLATILE } | {SHIPPABLE | NOT SHIPPABLE} | {PACKAGE} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' ][...] { IS | AS } plsql_body / ``` ## Parameter Description * **function\_name** Specifies the name of the function to create (optionally schema-qualified). Value range: a string. It must comply with the identifier naming convention, and can contain a maximum of 63 characters. If the value contains more than 63 characters, the database truncates it and retains the first 63 characters as the function name. * **argname** Specifies the parameter name of the function. Value range: a string. It must comply with the identifier naming convention, and can contain a maximum of 63 characters. If the value contains more than 63 characters, the database truncates it and retains the first 63 characters as the function parameter name. * **argmode** Specifies the parameter mode of the function. Value range: **IN**, **OUT**, **INOUT**, and **VARIADIC**. The default value is **IN**. The parameters of **OUT** and **INOUT** cannot be used in the function definition of **RETURNS TABLE**. > \[!NOTE]NOTE > **VARIADIC** specifies parameters of the array type. * **argtype** Specifies the data type of a function parameter. **%TYPE** or **%ROWTYPE** can be used to indirectly reference a variable or table type. For details, see [Variable Definition Statements](variable_definition_statements.md). * **expression** Specifies the default expression of a parameter. * **rettype** Specifies the return data type. When there is **OUT** or **INOUT** parameter, the **RETURNS** clause can be omitted. If the clause exists, the result type of the clause must be the same as that of the output parameter. If there are multiple output parameters, the result type of the clause is **RECORD**. Otherwise, the result type of the clause is the same as that of a single output parameter. The **SETOF** modifier indicates that the function will return a set of items, rather than a single item. Same as **argtype**, **%TYPE** or **%ROWTYPE** can also be used to indirectly reference types. * **column\_name** Specifies the column name. * **column\_type** Specifies the column type. * **definition** Specifies a string constant defining a function. Its meaning depends on the language. It can be an internal function name, a path pointing to a target file, a SQL query, or text in a procedural language. * **DETERMINISTIC** Specifies an interface compatible with the SQL syntax. You are not advised to use it. * **LANGUAGE lang\_name** Specifies the name of the language that is used to implement the function. It can be **SQL**, **internal**, or the name of a customized process language. To ensure downward compatibility, the name can use single quotation marks. Contents in single quotation marks must be capitalized. * **WINDOW** Indicates that this function is a window function. The **WINDOW** attribute cannot be changed when replacing an existing function definition. > \[!TIP]NOTICE > For a customized window function, the value of **LANGUAGE** can only be **internal**, and the referenced internal function must be a window function. * **IMMUTABLE** Specifies that the function always returns the same result if the parameter values are the same. * **STABLE** Specifies that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same parameter value, but its result varies by SQL statements. * **VOLATILE** Specifies that the function value can change in a single table scan and no optimization is performed. * **SHIPPABLE**|**NOT SHIPPABLE** Specifies whether the function can be pushed down for execution. This port is reserved and is not recommended. * **FENCED**|**NOT FENCED** Specifies whether the user-defined C function is executed in fenced or not-fenced mode. This port is reserved and is not recommended. * **PACKAGE** Specifies whether the function can be overloaded. PostgreSQL-style functions can be overloaded, and this parameter is designed for functions of other styles. * All PACKAGE and non-PACKAGE functions cannot be overloaded or replaced. * PACKAGE functions do not support parameters of the VARIADIC type. * The **PACKAGE** attribute of functions cannot be modified. * **LEAKPROOF** Specifies that the function has no side effects. **LEAKPROOF** can be set only by the system administrator. * **CALLED ON NULL INPUT** Declares that some parameters of the function can be invoked in normal mode if the parameter values are null. This parameter can be omitted. * **RETURNS NULL ON NULL INPUT** **STRICT** Specifies that the function always returns null whenever any of its parameters is null. If this parameter is specified, the function is not executed when there are null parameters; instead a null result is returned automatically. **RETURNS NULL ON NULL INPUT** and **STRICT** have the same functions. * **EXTERNAL** The keyword **EXTERNAL** is allowed for SQL conformance, but it is optional since, unlike in SQL, this feature applies to all functions not only external ones. * **SECURITY INVOKER** **AUTHID CURRENT\_USER** Specifies that the function will be executed with the permissions of the user who invokes it. This parameter can be omitted. **SECURITY INVOKER** and **AUTHID CURRENT\_USER** have the same functions. * **SECURITY DEFINER** **AUTHID DEFINER** Specifies that the function will be executed with the permissions of the user who created it. **AUTHID DEFINER** and **SECURITY DEFINER** have the same functions. * **COST execution\_cost** Estimates the execution cost of a function. The unit of **execution\_cost** is **cpu\_operator\_cost**. Value range: a positive integer * **ROWS result\_rows** Estimates the number of rows returned by the function. This is only allowed when the function is declared to return a set. Value range: a positive number. The default value is **1000**. * **COMMENT 'text'** Comments a function. * **configuration\_parameter** * **value** Sets a specified database session parameter to a specified value. If the value is **DEFAULT** or **RESET**, the default setting is used in the new session. **OFF** closes the setting. Value range: a string * DEFAULT * OFF * RESET Specifies the default value. * **from current** Uses the value of **configuration\_parameter** of the current session. * **plsql\_body** Specifies the PL/SQL stored procedure body. > \[!TIP]NOTICE > When a user is created in the function body, the plaintext password is recorded in the log. You are not advised to do it. ## Examples ``` -- Define a function as SQL query. openGauss=# CREATE FUNCTION func_add_sql(integer, integer) RETURNS integer AS 'select $1 + $2;' LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT; -- Add an integer by parameter name using PL/pgSQL. openGauss=# CREATE OR REPLACE FUNCTION func_increment_plsql(i integer) RETURNS integer AS $$ BEGIN RETURN i + 1; END; $$ LANGUAGE plpgsql; -- Return the RECORD type. openGauss=# CREATE OR REPLACE FUNCTION func_increment_sql(i int, out result_1 bigint, out result_2 bigint) returns SETOF RECORD as $$ begin result_1 = i + 1; result_2 = i * 10; return next; end; $$language plpgsql; -- Return a record containing multiple output parameters. openGauss=# CREATE FUNCTION func_dup_sql(in int, out f1 int, out f2 text) AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ LANGUAGE SQL; openGauss=# SELECT * FROM func_dup_sql(42); -- Compute the sum of two integers and returning the result (if the input is null, the returned result is null): openGauss=# CREATE FUNCTION func_add_sql2(num1 integer, num2 integer) RETURN integer AS BEGIN PAC RETURN num1 + num2; END; / -- Alter the execution rule of function func_add_sql2 to IMMUTABLE (that is, the same result is returned if the parameter remains unchanged). openGauss=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) IMMUTABLE; -- Rename the func_add_sql2 function as add_two_number: openGauss=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) RENAME TO add_two_number; -- Change the owner of function add_two_number to omm. openGauss=# ALTER FUNCTION omm(INTEGER, INTEGER) OWNER TO omm; -- Delete the function. openGauss=# DROP FUNCTION add_two_number; openGauss=# DROP FUNCTION func_increment_sql; openGauss=# DROP FUNCTION func_dup_sql; openGauss=# DROP FUNCTION func_increment_plsql; openGauss=# DROP FUNCTION func_add_sql; -- Set parameters. openGauss=# set behavior_compat_options='proc_outparam_override'; -- Create functions. openGauss=# CREATE or replace FUNCTION func1(in a integer, out b integer) RETURNS int AS $$ DECLARE c int; BEGIN c := 1; b := a + c; return c; END; $$ LANGUAGE 'plpgsql' NOT FENCED; -- Return return and output parameters at the same time. openGauss=# declare result integer; a integer := 2; b integer := NULL; begin result := func1(a => a, b => b); raise info 'b is: %', b; raise info 'result is: %', result; end; / INFO: b is: 3 INFO: result is: 1 ANONYMOUS BLOCK EXECUTE -- Left assignment expressions are not supported. openGauss=# declare result integer; a integer := 2; b integer := NULL; begin result := func1(a => a, b => b) + 1; raise info 'b is: %', b; raise info 'result is: %', result; end; / ERROR: when invoking function func1, maybe input something superfluous. CONTEXT: compilation of PL/pgSQL function "inline_code_block" near line 3 -- out/inout in a stored procedure cannot be set to a constant. openGauss=# declare result integer; a integer := 2; b integer := NULL; begin result := func1(a => a, b => 10); raise info 'b is: %', b; raise info 'result is: %', result; end; / ERROR: when invoking function func1, no destination for argments "b" CONTEXT: compilation of PL/pgSQL function "inline_code_block" near line 3 ``` ## Helpful Links [ALTER FUNCTION](alter_function.md) and [DROP FUNCTION](drop_function.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-create-function.md --- # CREATE FUNCTION ## Function Creates a function. ## Precautions Compared with the original openGauss, Dolphin modifies the CREATE FUNCTION syntax as follows: 1. The default value **plpgsql** of LANGUAGE is added. 2. The syntax compatibility item \[NOT] DETERMINISTIC is added. 3. The syntax compatibility item { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } is added. 4. The syntax compatibility item SQL SECURITY { DEFINER | INVOKER } is added. ## Syntax After Dolphin is loaded, the format of the CREATE FUNCTION syntax is: * Syntax (compatible with PostgreSQL) for creating a user-defined function: ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) [ RETURNS rettype | RETURNS TABLE ( { column_name column_type } [, ...] )] [ {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | [ NOT ] LEAKPROOF | WINDOW | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {[ EXTERNAL| SQL ] SECURITY INVOKER | [ EXTERNAL| SQL ] SECURITY DEFINER | AU THID DEFINER | AUTHID CURRENT_USER} | {FENCED | NOT FENCED} | {PACKAGE} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ] [...] { AS 'definition' | AS 'obj_file', 'link_symbol' } ``` * O syntax of creating a customized function: ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ {IMMUTABLE | STABLE | VOLATILE } | {SHIPPABLE | NOT SHIPPABLE} | {PACKAGE} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL| SQL ] SECURITY INVOKER | [ EXTERNAL| SQL ] SECURITY DEFINER | | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][...] { IS | AS } plsql_body / ``` ## Parameter Description * **LANGUAGE lang\_name** Specifies the name of the language that is used to implement the function. PostgreSQL function default value: **sql**. O-style default value: **plpgsql**. * **SQL SECURITY INVOKER** Indicates that the function is to be executed with the permissions of the user that calls it. This parameter can be omitted. The functions of SQL SECURITY INVOKER and SECURITY INVOKER and AUTHID CURRENT\_USER are the same. * **SQL SECURITY DEFINER** Specifies that the function is to be executed with the privileges of the user that created it. The functions of SQL SECURITY DEFINER and AUTHID DEFINER and SECURITY DEFINER are the same. * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** Syntax compatibility item. ## Examples ``` --Specify CONTAINS SQL. openGauss=# CREATE FUNCTION func_test (s CHAR(20)) RETURNS int CONTAINS SQL AS $$ select 1 $$ ; --Specify DETERMINISTIC. openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL DETERMINISTIC AS $$ select s; $$ ; --Specify LANGUAGE SQL. openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL LANGUAGE SQL AS $$ select s; $$ ; --Specify NO SQL. openGauss=# CREATE FUNCTION func_test (s int) RETURNS int NO SQL AS $$ select s; $$ ; --Specify READS SQL DATA. openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL READS SQL DATA AS $$ select s; $$ ; --Specify MODIFIES SQL DATA. openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL LANGUAGE SQL NO SQL MODIFIES SQL DATA AS $$ select s; $$ ; --Specify SECURITY DEFINER. openGauss=# CREATE FUNCTION func_test (s int) RETURNS int NO SQL SQL SECURITY DEFINER AS $$ select s; $$ ; --Specify SECURITY INVOKER. openGauss=# CREATE FUNCTION func_test (s int) RETURNS int SQL SECURITY INVOKER READS SQL DATA LANGUAGE SQL AS $$ select s; $$ ; ``` ## Helpful Links [CREATE FUNCTION](https://docs.opengauss.org/en/docs/latest/sql_reference/create_function.html) --- --- url: /en/docs/latest/sql_reference/create_function.md --- # CREATE FUNCTION ## Function **CREATE FUNCTION** creates a function. ## Precautions * If the parameters or return values of a function have precision, the precision is not checked. * When creating a function, you are advised to explicitly specify the schemas of tables in the function definition. Otherwise, the function may fail to be executed. * **current\_schema** and **search\_path** specified by **SET** during function creation are invalid. **search\_path** and **current\_schema** before and after function execution should be the same. * If a function has output parameters, the **SELECT** statement uses the default values of the output parameters when calling the function. When the **CALL** statement calls the function, it requires that the output parameters must be specified. When the **CALL** statement calls an overloaded **PACKAGE** function, it can use the default values of the output parameters. For details, see examples in [CALL](call.md). * Only the functions compatible with PostgreSQL or those with the **PACKAGE** attribute can be overloaded. After **REPLACE** is specified, a new function is created instead of replacing a function if the number of parameters, parameter type, or return value is different. * You can use the **SELECT** statement to specify different parameters using identical functions, but cannot use the **CALL** statement to call identical functions without the **PACKAGE** attribute. * When you create a function, you cannot insert other agg functions out of the avg function or other functions. * By default, the permissions to execute new functions are granted to **PUBLIC**. For details, see [GRANT](grant.md). You can revoke the default execution permissions from **PUBLIC** and grant them to other users as needed. To avoid the time window during which new functions can be accessed by all users, create functions in transactions and set function execution permissions. * When functions without parameters are called inside another function, you can omit brackets and call functions using their names directly. * When functions with output parameters are called inside another function which is an assignment expression, you can omit the output parameters of the called functions. * Oracle-compatible functions support viewing, exporting, and importing parameter comments. * Oracle-compatible functions support viewing, exporting, and importing comments between IS/AS and plsql\_body. * Users granted with the **CREATE ANY FUNCTION** permission can create or replace functions in the user schemas. * The default permission on a function is **SECURITY INVOKER**. To change the default permission to **SECURITY DEFINER**, set the GUC parameter **behavior\_compat\_options** to **'plsql\_security\_definer'**. * For PL/pgSQL functions, after **behavior\_compat\_options** is set to **'proc\_outparam\_override'**, the behavior of **out/inout** changes. In the functions, **return** and **out/inout** can be returned at the same time. Before the parameter is enabled, only **return** is returned. For details, see [Examples](#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821). * For PL/pgSQL functions, after **behavior\_compat\_options** is set to **'proc\_outparam\_override'**, the restrictions are as follows: 1. If a function with the **out/inout** parameter already exists in the same schema or package, you cannot create another function with the same name with the **out/inout** parameter. 2. The **out** parameter must be added no matter whether the **SELECT** or **CALL** statement is used to call a stored procedure. 3. In some scenarios, functions cannot be used in expressions (compared with those before the parameter is enabled), for example, left assignment in a stored procedure and **call function**. For details, see [Examples](#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821). 4. Functions without **return** cannot be called. **perform function** can be used to call functions. 5. When a function is called in a stored procedure, **out/inout** cannot be set to a constant. For details, see [Examples](#en-us_topic_0283136560_en-us_topic_0237122104_en-us_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821). ## Syntax * Syntax (compatible with PostgreSQL) for creating a customized function: ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) [ RETURNS rettype [ DETERMINISTIC ] | RETURNS TABLE ( { column_name column_type } [, ...] )] LANGUAGE lang_name [ {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | [ NOT ] LEAKPROOF | WINDOW | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AU THID DEFINER | AUTHID CURRENT_USER} | {FENCED | NOT FENCED} | {PACKAGE} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' ] [...] { AS 'definition' | AS 'obj_file', 'link_symbol' } ``` * O syntax of creating a customized function: ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ DETERMINISTIC ] [ {IMMUTABLE | STABLE | VOLATILE } | {SHIPPABLE | NOT SHIPPABLE} | {PACKAGE} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' ][...] { IS | AS } plsql_body / ``` ## Parameter Description * **function\_name** Specifies the name of the function to create (optionally schema-qualified). Value range: a string. It must comply with the identifier naming convention, and can contain a maximum of 63 characters. If the value contains more than 63 characters, the database truncates it and retains the first 63 characters as the function name. * **argname** Specifies the parameter name of the function. Value range: a string. It must comply with the identifier naming convention, and can contain a maximum of 63 characters. If the value contains more than 63 characters, the database truncates it and retains the first 63 characters as the function parameter name. * **argmode** Specifies the parameter mode of the function. Value range: **IN**, **OUT**, **INOUT**, and **VARIADIC**. The default value is **IN**. The parameters of **OUT** and **INOUT** cannot be used in the function definition of **RETURNS TABLE**. > \[!NOTE]NOTE > **VARIADIC** specifies parameters of the array type. * **argtype** Specifies the data type of a function parameter. **%TYPE** or **%ROWTYPE** can be used to indirectly reference a variable or table type. For details, see [Variable Definition Statements](variable_definition_statements.md). * **expression** Specifies the default expression of a parameter. * **rettype** Specifies the return data type. When there is **OUT** or **INOUT** parameter, the **RETURNS** clause can be omitted. If the clause exists, the result type of the clause must be the same as that of the output parameter. If there are multiple output parameters, the result type of the clause is **RECORD**. Otherwise, the result type of the clause is the same as that of a single output parameter. The **SETOF** modifier indicates that the function will return a set of items, rather than a single item. Same as **argtype**, **%TYPE** or **%ROWTYPE** can also be used to indirectly reference types. * **column\_name** Specifies the column name. * **column\_type** Specifies the column type. * **definition** Specifies a string constant defining a function. Its meaning depends on the language. It can be an internal function name, a path pointing to a target file, a SQL query, or text in a procedural language. * **DETERMINISTIC** Specifies an interface compatible with the SQL syntax. You are not advised to use it. * **LANGUAGE lang\_name** Specifies the name of the language that is used to implement the function. It can be **SQL**, **internal**, or the name of a customized process language. To ensure downward compatibility, the name can use single quotation marks. Contents in single quotation marks must be capitalized. * **WINDOW** Indicates that this function is a window function. The **WINDOW** attribute cannot be changed when replacing an existing function definition. > \[!TIP]NOTICE > For a customized window function, the value of **LANGUAGE** can only be **internal**, and the referenced internal function must be a window function. * **IMMUTABLE** Specifies that the function always returns the same result if the parameter values are the same. * **STABLE** Specifies that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same parameter value, but its result varies by SQL statements. * **VOLATILE** Specifies that the function value can change in a single table scan and no optimization is performed. * **SHIPPABLE**|**NOT SHIPPABLE** Specifies whether the function can be pushed down for execution. This port is reserved and is not recommended. * **FENCED**|**NOT FENCED** Specifies whether the user-defined C function is executed in fenced or not-fenced mode. This port is reserved and is not recommended. * **PACKAGE** Specifies whether the function can be overloaded. PostgreSQL-style functions can be overloaded, and this parameter is designed for functions of other styles. * All PACKAGE and non-PACKAGE functions cannot be overloaded or replaced. * PACKAGE functions do not support parameters of the VARIADIC type. * The **PACKAGE** attribute of functions cannot be modified. * **LEAKPROOF** Specifies that the function has no side effects. **LEAKPROOF** can be set only by the system administrator. * **CALLED ON NULL INPUT** Declares that some parameters of the function can be invoked in normal mode if the parameter values are null. This parameter can be omitted. * **RETURNS NULL ON NULL INPUT** **STRICT** Specifies that the function always returns null whenever any of its parameters is null. If this parameter is specified, the function is not executed when there are null parameters; instead a null result is returned automatically. **RETURNS NULL ON NULL INPUT** and **STRICT** have the same functions. * **EXTERNAL** The keyword **EXTERNAL** is allowed for SQL conformance, but it is optional since, unlike in SQL, this feature applies to all functions not only external ones. * **SECURITY INVOKER** **AUTHID CURRENT\_USER** Specifies that the function will be executed with the permissions of the user who invokes it. This parameter can be omitted. **SECURITY INVOKER** and **AUTHID CURRENT\_USER** have the same functions. * **SECURITY DEFINER** **AUTHID DEFINER** Specifies that the function will be executed with the permissions of the user who created it. **AUTHID DEFINER** and **SECURITY DEFINER** have the same functions. * **COST execution\_cost** Estimates the execution cost of a function. The unit of **execution\_cost** is **cpu\_operator\_cost**. Value range: a positive integer * **ROWS result\_rows** Estimates the number of rows returned by the function. This is only allowed when the function is declared to return a set. Value range: a positive number. The default value is **1000**. * **COMMENT 'text'** Comments a function. * **configuration\_parameter** * **value** Sets a specified database session parameter to a specified value. If the value is **DEFAULT** or **RESET**, the default setting is used in the new session. **OFF** closes the setting. Value range: a string * DEFAULT * OFF * RESET Specifies the default value. * **from current** Uses the value of **configuration\_parameter** of the current session. * **plsql\_body** Specifies the PL/SQL stored procedure body. > \[!TIP]NOTICE > When a user is created in the function body, the plaintext password is recorded in the log. You are not advised to do it. ## Examples ``` -- Define a function as SQL query. openGauss=# CREATE FUNCTION func_add_sql(integer, integer) RETURNS integer AS 'select $1 + $2;' LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT; -- Add an integer by parameter name using PL/pgSQL. openGauss=# CREATE OR REPLACE FUNCTION func_increment_plsql(i integer) RETURNS integer AS $$ BEGIN RETURN i + 1; END; $$ LANGUAGE plpgsql; -- Return the RECORD type. openGauss=# CREATE OR REPLACE FUNCTION func_increment_sql(i int, out result_1 bigint, out result_2 bigint) returns SETOF RECORD as $$ begin result_1 = i + 1; result_2 = i * 10; return next; end; $$language plpgsql; -- Return a record containing multiple output parameters. openGauss=# CREATE FUNCTION func_dup_sql(in int, out f1 int, out f2 text) AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ LANGUAGE SQL; openGauss=# SELECT * FROM func_dup_sql(42); -- Compute the sum of two integers and returning the result (if the input is null, the returned result is null): openGauss=# CREATE FUNCTION func_add_sql2(num1 integer, num2 integer) RETURN integer AS BEGIN PAC RETURN num1 + num2; END; / -- Alter the execution rule of function func_add_sql2 to IMMUTABLE (that is, the same result is returned if the parameter remains unchanged). openGauss=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) IMMUTABLE; -- Rename the func_add_sql2 function as add_two_number: openGauss=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) RENAME TO add_two_number; -- Change the owner of function add_two_number to omm. openGauss=# ALTER FUNCTION omm(INTEGER, INTEGER) OWNER TO omm; -- Delete the function. openGauss=# DROP FUNCTION add_two_number; openGauss=# DROP FUNCTION func_increment_sql; openGauss=# DROP FUNCTION func_dup_sql; openGauss=# DROP FUNCTION func_increment_plsql; openGauss=# DROP FUNCTION func_add_sql; -- Set parameters. openGauss=# set behavior_compat_options='proc_outparam_override'; -- Create functions. openGauss=# CREATE or replace FUNCTION func1(in a integer, out b integer) RETURNS int AS $$ DECLARE c int; BEGIN c := 1; b := a + c; return c; END; $$ LANGUAGE 'plpgsql' NOT FENCED; -- Return return and output parameters at the same time. openGauss=# declare result integer; a integer := 2; b integer := NULL; begin result := func1(a => a, b => b); raise info 'b is: %', b; raise info 'result is: %', result; end; / INFO: b is: 3 INFO: result is: 1 ANONYMOUS BLOCK EXECUTE -- Left assignment expressions are not supported. openGauss=# declare result integer; a integer := 2; b integer := NULL; begin result := func1(a => a, b => b) + 1; raise info 'b is: %', b; raise info 'result is: %', result; end; / ERROR: when invoking function func1, maybe input something superfluous. CONTEXT: compilation of PL/pgSQL function "inline_code_block" near line 3 -- out/inout in a stored procedure cannot be set to a constant. openGauss=# declare result integer; a integer := 2; b integer := NULL; begin result := func1(a => a, b => 10); raise info 'b is: %', b; raise info 'result is: %', result; end; / ERROR: when invoking function func1, no destination for argments "b" CONTEXT: compilation of PL/pgSQL function "inline_code_block" near line 3 ``` ## Helpful Links [ALTER FUNCTION](alter_function.md) and [DROP FUNCTION](drop_function.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CREATE-FUNCTION.md --- # CREATE FUNCTION ## 功能描述 创建一个函数。 ## 注意事项 相比于原始的openGauss,dolphin对于CREATE FUNCTION语法的修改为: 1. 增加 LANGUAGE 默认值 plpgsql。 2. 增加语法兼容项 \[NOT] DETERMINISTIC。 3. 增加语法兼容项 { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } 。 4. 增加语法兼容项 SQL SECURITY { DEFINER | INVOKER }。 5. 增加MySQL风格语法格式。 ## 语法格式 dolphin加载后,CREATE FUNCTION 语法的格式为 * 兼容PostgreSQL风格的创建自定义函数语法。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) [ RETURNS rettype | RETURNS TABLE ( { column_name column_type } [, ...] )] [ {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | [ NOT ] LEAKPROOF | WINDOW | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {[ EXTERNAL| SQL ] SECURITY INVOKER | [ EXTERNAL| SQL ] SECURITY DEFINER | AU THID DEFINER | AUTHID CURRENT_USER} | {FENCED | NOT FENCED} | {PACKAGE} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ] [...] { AS 'definition' | AS 'obj_file', 'link_symbol' } ``` * O风格的创建自定义函数的语法。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ {IMMUTABLE | STABLE | VOLATILE } | {SHIPPABLE | NOT SHIPPABLE} | {PACKAGE} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL| SQL ] SECURITY INVOKER | [ EXTERNAL| SQL ] SECURITY DEFINER | | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][...] { IS | AS } plsql_body / ``` * MySQL风格语法格式。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURNS rettype [ SQL SECURITY { DEFINER | INVOKER } | COMMENT 'text' | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][...] plsql_body ``` ## 参数说明 * **LANGUAGE lang\_name** 用以实现函数的语言的名称。PostgreSQL风格函数默认值 sql, O风格默认值 plpgsql。 MySQL风格语法格式下,LANGUAGE选项仅做语法兼容,可填入其他值,但最终将使用plpgsql作为实现函数的语言。在MySQL风格语法格式下,此选项允许重复。 * **SQL SECURITY INVOKER** 表明该函数将带着调用它的用户的权限执行。该参数可以省略。 SQL SECURITY INVOKER和SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 在MySQL风格语法格式下,此选项允许重复,且与SQL SECURITY DEFINER同类别。该类别的函数选项以最后一个输入为准。 * **SQL SECURITY DEFINER** 声明该函数将以创建它的用户的权限执行。 SQL SECURITY DEFINER和AUTHID DEFINER和SECURITY DEFINER的功能相同。 在MySQL风格语法格式下,此选项允许重复,且与SQL SECURITY INVOKER同类别。该类别的函数选项以最后一个输入为准。 * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** 语法兼容项。此选项允许重复。 ## 示例 ``` --指定 CONTAINS SQL openGauss=# CREATE FUNCTION func_test (s CHAR(20)) RETURNS int CONTAINS SQL AS $$ select 1 $$ ; --指定 DETERMINISTIC openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL DETERMINISTIC AS $$ select s; $$ ; --指定 LANGUAGE SQL openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL LANGUAGE SQL AS $$ select s; $$ ; --指定 NO SQL openGauss=# CREATE FUNCTION func_test (s int) RETURNS int NO SQL AS $$ select s; $$ ; --指定 READS SQL DATA openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL READS SQL DATA AS $$ select s; $$ ; --指定 MODIFIES SQL DATA openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL LANGUAGE SQL NO SQL MODIFIES SQL DATA AS $$ select s; $$ ; --指定 SECURITY DEFINER openGauss=# CREATE FUNCTION func_test (s int) RETURNS int NO SQL SQL SECURITY DEFINER AS $$ select s; $$ ; --指定 SECURITY INVOKER openGauss=# CREATE FUNCTION func_test (s int) RETURNS int SQL SECURITY INVOKER READS SQL DATA LANGUAGE SQL AS $$ select s; $$ ; --MySQL风格语法格式 openGauss=# create function func(n int) returns varchar(50) return (select n+1); CREATE FUNCTION openGauss=# select func(1); func ------ 2 (1 row) openGauss=# delimiter // SET openGauss=# create function func10(b int) returns int openGauss-# begin openGauss-# if b > 0 then return b + 10; openGauss-# else return -1; openGauss-# end if; openGauss-# end// CREATE FUNCTION openGauss=# delimiter ; SET openGauss=# select func10(9); func10 -------- 19 (1 row) ``` ## 相关链接 [CREATE FUNCTION](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_function.html) --- --- url: /zh/docs/latest-lite/sql_reference/create_function.md --- # CREATE FUNCTION ## 功能描述 创建一个函数。 ## 注意事项 * 如果创建函数时参数或返回值带有精度,不进行精度检测。 * 创建函数时,函数定义中对表对象的操作建议都显式指定模式,否则可能会导致函数执行异常。 * 在创建函数时,函数内部通过SET语句设置current\_schema和search\_path无效。执行完函数search\_path和current\_schema与执行函数前的search\_path和current\_schema保持一致。 * 如果函数参数中带有出参,SELECT调用函数必须缺省出参,CALL调用函数必须指定出参,对于调用重载的带有PACKAGE属性的函数,CALL调用函数可以缺省出参,具体信息参见[CALL](call.md)的示例。 * 兼容Postgresql风格的函数或者带有PACKAGE属性的函数支持重载。在指定REPLACE的时候,如果参数个数、类型、返回值有变化,不会替换原有函数,而是会建立新的函数。 * 不能创建仅形参名字不同(函数名和参数列表类型都一样)的重载函数。 * 重载的函数在调用时变量需要明确具体的类型。 * 不能创建与存储过程拥有相同名称和参数列表的函数。 * 不支持形式参数仅在自定义ref cursor类型和sys\_refcursor类型不同的重载。 * 在函数内部使用未声明的变量,函数被调用时会报错。 * SELECT调用可以指定不同参数来进行同名函数调用,由于语法不支持调用不带有PACKAGE属性的同名函数。而对于CALL,则只支持调用具有package属性的重载同名函数。 * 在创建function时,不能在avg函数外面嵌套其他agg函数,或者其他系统函数。 * 新创建的函数默认会给PUBLIC授予执行权限(详见[GRANT](grant.md))。用户可以选择收回PUBLIC默认执行权限,然后根据需要将执行权限授予其他用户,为了避免出现新函数能被所有人访问的时间窗口,应在一个事务中创建函数并且设置函数执行权限。 * 在函数内部调用其它无参数的函数时,可以省略括号,直接使用函数名进行调用。 * 在函数内部调用其他有出参的函数,如果在赋值表达式中调用时,被调函数的出参可以省略,给出了也会被忽略。 * 兼容Oracle风格的函数支持参数注释的查看与导出、导入。 * 兼容Oracle风格的函数支持介于IS/AS与plsql\_body之间的注释的查看与导出、导入。 * 被授予CREATE ANY FUNCTION权限的用户,可以在用户模式下创建/替换函数。 * 函数默认为SECURITY INVOKER权限,如果想将默认行为改为SECURITY DEFINER权限,需要设置guc参数behavior\_compat\_options='plsql\_security\_definer'。 * 对于plpgsql函数,打开参数behavior\_compat\_options='proc\_outparam\_override'后,out/inout的行为会改变,函数中如果return和out/inout,可以同时返回,参数打开前只会返回return,见[示例](#zh-cn_topic_0283136560_zh-cn_topic_0237122104_zh-cn_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821)。 * 对于plpgsql函数,打开参数behavior\_compat\_options='proc\_outparam\_override'后,有以下限制: 1. 如果同一schema和package中已存在带有out/inout参数函数,不能再次创建带有out/inout参数的同名函数。 2. 无论使用select还是call调用存储过程,都必须加上out参数。 3. 部分场景不支持函数参与表达式(与参数打开前相比),如存储过程中左赋值,call function等,见[示例](#zh-cn_topic_0283136560_zh-cn_topic_0237122104_zh-cn_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821)。 4. 不支持调用无return的函数,perform function调用。 5. 存储过程中调用函数,不支持out/inout参数传入常量,见[示例](#zh-cn_topic_0283136560_zh-cn_topic_0237122104_zh-cn_topic_0059778837_scc61c5d3cc3e48c1a1ef323652dda821)。 * 不可与同一模式下已存在的synonym产生命名冲突。 * 当language为internal时,自定义函数的参数类型和返回值类型(void除外)需要与引用的系统函数保持一致,参数个数超出系统函数的部分不做对比校验。当未指定strict时,此选项与系统函数保持一致。 * 通过`CREATE OR REPLACE`语法替换已有的函数时,会一并重建依赖此函数的视图,函数中的参数数据类型变更等情况可能会导致重建视图失败,进而导致替换函数失败。此种情况下,建议先删除依赖的视图,再重建函数,再重新创建视图。 * 允许创建兼容Oracle风格的函数时忽略依赖关系进行创建,并对未定义的类型/存储过程/函数/包变量提供告警功能,需要设置guc参数behavior\_compat\_options='plpgsql\_dependency'。 ## 语法格式 * 兼容PostgreSQL风格的创建自定义函数语法。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) [ RETURNS rettype | RETURNS TABLE ( { column_name column_type } [, ...] )] LANGUAGE lang_name [ {IMMUTABLE | STABLE | VOLATILE | DETERMINISTIC} | {SHIPPABLE | NOT SHIPPABLE} | [ NOT ] LEAKPROOF | WINDOW | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AU THID DEFINER | AUTHID CURRENT_USER} | {FENCED | NOT FENCED} | {PACKAGE} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | {RESULT_CACHE | NOT RESULT_CACHE} ] [...] { AS 'definition' | AS 'obj_file', 'link_symbol' } ``` * O风格的创建自定义函数的语法。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ {IMMUTABLE | STABLE | VOLATILE | DETERMINISTIC} | {SHIPPABLE | NOT SHIPPABLE} | {PACKAGE} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | parallel_enable_clause | {RESULT_CACHE | NOT RESULT_CACHE} ][...] { IS | AS } plsql_body / ``` * 其中并行参数parallel\_enable\_clause为: ``` PARALLEL_ENABLE [ ( PARTITION argument BY { ANY | HASH (column [, column]) } ) ] ``` ## 参数说明 * **function\_name** 要创建的函数名称(可以用模式修饰)。 取值范围:字符串,要符合标识符的命名规范。且最多为63个字符。若超过63个字符,数据库会截断并保留前63个字符当做函数名称。 * **argname** 函数参数的名称。 取值范围:字符串,要符合标识符的命名规范。且最多为63个字符。若超过63个字符,数据库会截断并保留前63个字符当做函数参数名称。 * **argmode** 函数参数的模式。 取值范围:IN,OUT,INOUT或VARIADIC。缺省值是IN。并且OUT和INOUT模式的参数不能用在RETURNS TABLE的函数定义中。 > \[!NOTE]说明 > > VARIADIC用于声明数组类型的参数。 * **argtype** 函数参数的类型。可以使用%TYPE或%ROWTYPE间接引用变量或表的类型,详细可参考存储过程章节[定义变量](define_variables.md)。 * **expression** 参数的默认表达式。 * **rettype** 函数返回值的数据类型。 如果存在OUT或INOUT参数,可以省略RETURNS子句。如果存在,该子句必须和输出参数所表示的结果类型一致:如果有多个输出参数,则为RECORD,否则与单个输出参数的类型相同。 SETOF修饰词表示该函数将返回一个集合,而不是单独一项。 与argtype相同,同样可以使用%TYPE或%ROWTYPE间接引用类型。 * **column\_name** 字段名称。 * **column\_type** 字段类型。 * **definition** 一个定义函数的字符串常量,含义取决于语言。它可以是一个内部函数名称、一个指向某个目标文件的路径、一个SQL查询、一个过程语言文本。 * **DETERMINISTIC** SQL语法兼容接口,未实现功能,不推荐使用。 * **LANGUAGE lang\_name** 用以实现函数的语言的名称。可以是SQL,internal,或者是用户定义的过程语言名称。为了保证向下兼容,该名称可以用单引号(包围)。若采用单引号,则引号内必须为小写。 > \[!NOTE]说明 > > internel函数在定义时,如果AS指定为内部系统函数,则新创建函数的参数类型,参数个数,与返回值类型需要与内部系统函数保持一致,且需要有执行此内部系统函数的权限。 * **WINDOW** 表示该函数是窗口函数。替换函数定义时不能改变WINDOW属性。 > \[!TIP]须知 > > 自定义窗口函数只支持LANGUAGE是internal,并且引用的内部函数必须是窗口函数。 * **IMMUTABLE** 表示该函数在给出同样的参数值时总是返回同样的结果。 * **STABLE** 表示该函数不能修改数据库,对相同参数值,在同一次表扫描里,该函数的返回值不变,但是返回值可能在不同SQL语句之间变化。 * **VOLATILE** 表示该函数值可以在一次表扫描内改变,因此不会做任何优化。 * **SHIPPABLE**|**NOT SHIPPABLE** 表示该函数是否可以下推执行。预留接口,不推荐使用。 * **FENCED**|**NOT FENCED** 声明用户定义的C函数是在保护模式还是非保护模式下执行。预留接口,不推荐使用。 * **RESULT\_CACHE**|**NOT RESULT\_CACHE** 表示用户定义的函数是否支持函数结果缓存。 * **PACKAGE** 表示该函数是否支持重载。PostgreSQL风格的函数本身就支持重载,此参数主要是针对其它风格的函数。 * 不允许package函数和非package函数重载或者替换。 * package函数不支持VARIADIC类型的参数。 * 不允许修改函数的package属性。 * **LEAKPROOF** 指出该函数的参数只包括返回值。LEAKPROOF只能由系统管理员设置。 * **CALLED ON NULL INPUT** 表明该函数的某些参数是NULL的时候可以按照正常的方式调用。该参数可以省略。 * **RETURNS NULL ON NULL INPUT** **STRICT** STRICT用于指定如果函数的某个参数是NULL,此函数总是返回NULL。如果声明了这个参数,当有NULL值参数时该函数不会被执行;而只是自动返回一个NULL结果。 RETURNS NULL ON NULL INPUT和STRICT的功能相同。 * **EXTERNAL** 目的是和SQL兼容,是可选的,这个特性适合于所有函数,而不仅是外部函数。 * **SECURITY INVOKER** **AUTHID CURRENT\_USER** 表明该函数将带着调用它的用户的权限执行。该参数可以省略。 SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SECURITY DEFINER** **AUTHID DEFINER** 声明该函数将以创建它的用户的权限执行。 AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **COST execution\_cost** 用来估计函数的执行成本。 execution\_cost以cpu\_operator\_cost为单位。 取值范围:正数 * **ROWS result\_rows** 估计函数返回的行数。用于函数返回的是一个集合。 取值范围:正数,默认值是1000行。 * **COMMENT 'text'** 函数注释。 * **configuration\_parameter** * **value** 把指定的数据库会话参数值设置为给定的值。如果value是DEFAULT或者RESET,则在新的会话中使用系统的缺省设置。OFF关闭设置。 取值范围:字符串 * DEFAULT * OFF * RESET 指定默认值。 * **from current** 取当前会话中的值设置为configuration\_parameter的值。 * **plsql\_body** PL/SQL存储过程体。用于O风格创建函数时,PL/SQL结尾的end后可以加上tag标签以兼容指定函数名的情况,目前tag标签也可以不与函数名一致。例如: ```sql CREATE OR REPLACE FUNCTION f1 (p int) RETURN int IS begin RETURN 1; END f1; / CREATE OR REPLACE FUNCTION f2 (p int) RETURN int IS begin RETURN 1; END f3; / ``` > \[!TIP]须知 > 当在函数体中创建用户时,日志中会记录密码的明文。因此不建议用户在函数体中创建用户。 * **plpgsql\_body** PL/pgSQL函数体。用于PostgreSQL风格创建函数时,language指定为plpgsql的情况。详见[PL/pgSQL语言函数](pl_pgsql_linguistic_function.md)。 * **parallel\_enable\_clause** 指定函数是否可以并行。其中PARTITION BY子句仅支持函数入参中有游标类型时指定。 参数的详细描述如下所示。 * argument 指定入参中并行的游标名。 * ANY | HASH (column \[,column]) 指定并行游标对数据分布的方式,目前支持ANY和HASH。指定为HASH时需要指定一个或多个列名。 > \[!TIP]须知 > > 1. 函数体内对指定的并行游标的操作仅支持直接FETCH CURSOR,当存在FETCH FIRST/LAST/ABSOLUTE/RELATIVE/BACKWARD/PRIOR CURSOR等操作时会报错。 > 2. 指定了该子句,即默认设置了IMMUTABLE,且不允许同时设置STABLE/VOLATILE。 > 3. 该子句仅在A兼容性的数据库下支持。 > 4. 函数并行仅支持游标表达式作为入参。 > 5. 支持plan hint指定query dop参数使函数并行,但需要游标表达式同样指定query\_dop,仅指定函数的query\_dop hint无法走并行(可见下方示例)。 ## 示例 ``` --定义函数为SQL查询。 openGauss=# CREATE FUNCTION func_add_sql(integer, integer) RETURNS integer AS 'select $1 + $2;' LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT; --利用参数名用 PL/pgSQL 自增一个整数。 openGauss=# CREATE OR REPLACE FUNCTION func_increment_plsql(i integer) RETURNS integer AS $$ BEGIN RETURN i + 1; END; $$ LANGUAGE plpgsql; --返回RECORD类型 openGauss=# CREATE OR REPLACE FUNCTION func_increment_sql(i int, out result_1 bigint, out result_2 bigint) returns SETOF RECORD as $$ begin result_1 = i + 1; result_2 = i * 10; return next; end; $$language plpgsql; --返回一个包含多个输出参数的记录。 openGauss=# CREATE FUNCTION func_dup_sql(in int, out f1 int, out f2 text) AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ LANGUAGE SQL; openGauss=# SELECT * FROM func_dup_sql(42); --计算两个整数的和,并返回结果。如果输入为null,则返回null。 openGauss=# CREATE FUNCTION func_add_sql2(num1 integer, num2 integer) RETURN integer AS BEGIN PAC RETURN num1 + num2; END; / --修改函数func_add_sql2的执行规则为IMMUTABLE,即参数不变时返回相同结果。 openGauss=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) IMMUTABLE; --将函数func_add_sql2的名称修改为add_two_number。 openGauss=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) RENAME TO add_two_number; --将函数add_two_number的属者改为omm。 openGauss=# ALTER FUNCTION omm(INTEGER, INTEGER) OWNER TO omm; --删除函数。 openGauss=# DROP FUNCTION add_two_number; openGauss=# DROP FUNCTION func_increment_sql; openGauss=# DROP FUNCTION func_dup_sql; openGauss=# DROP FUNCTION func_increment_plsql; openGauss=# DROP FUNCTION func_add_sql; --设置参数 openGauss=# set behavior_compat_options='proc_outparam_override'; --创建函数 openGauss=# CREATE or replace FUNCTION func1(in a integer, out b integer) RETURNS int AS $$ DECLARE c int; BEGIN c := 1; b := a + c; return c; END; $$ LANGUAGE 'plpgsql' NOT FENCED; --同时返回return和出参 openGauss=# declare result integer; a integer := 2; b integer := NULL; begin result := func1(a => a, b => b); raise info 'b is: %', b; raise info 'result is: %', result; end; / INFO: b is: 3 INFO: result is: 1 ANONYMOUS BLOCK EXECUTE --不支持左赋值表达式 openGauss=# declare result integer; a integer := 2; b integer := NULL; begin result := func1(a => a, b => b) + 1; raise info 'b is: %', b; raise info 'result is: %', result; end; / ERROR: when invoking function func1, maybe input something superfluous. CONTEXT: compilation of PL/pgSQL function "inline_code_block" near line 3 --存储过程中不支持out/inout传入常量 openGauss=# declare result integer; a integer := 2; b integer := NULL; begin result := func1(a => a, b => 10); raise info 'b is: %', b; raise info 'result is: %', result; end; / ERROR: when invoking function func1, no destination for argments "b" CONTEXT: compilation of PL/pgSQL function "inline_code_block" near line 3 -- 函数支持并行参数示例 openGauss=# create table employees (employee_id number(6), department_id NUMBER); openGauss=# openGauss=# BEGIN FOR i IN 1..999999 LOOP INSERT INTO employees VALUES (i, 60); END LOOP; COMMIT; END; / openGauss=# CREATE TYPE my_outrec_typ AS (employee_id numeric(6,0), department_id numeric); -- 创建函数,指定PARALLEL_ENABLE openGauss=# CREATE OR REPLACE FUNCTION hash_srf (p SYS_REFCURSOR) RETURN setof my_outrec_typ parallel_enable (partition p by hash(employee_id)) IS out_rec my_outrec_typ := my_outrec_typ(NULL, NULL); BEGIN LOOP FETCH p INTO out_rec.employee_id, out_rec.department_id; -- input row EXIT WHEN p%NOTFOUND; return next out_rec; END LOOP; RETURN; END hash_srf; / openGauss=# set query_dop = 4; -- 函数并行 openGauss=# explain (costs off) select * from hash_srf(cursor (select * from employees)); QUERY PLAN ---------------------------------------- Streaming(type: LOCAL GATHER dop: 1/4) -> Function Scan on hash_srf (2 rows) openGauss=# set query_dop = 1; -- 仅支持函数的query_dop hint无法走并行计划 openGauss=# explain (costs off) select /*+ set(query_dop 4) */ * from hash_srf(cursor (select * from employees)); QUERY PLAN --------------------------- Function Scan on hash_srf (1 row) -- 需同时指定游标表达式的query_dop hint openGauss=# explain (costs off) select /*+ set(query_dop 4) */ * from hash_srf(cursor (select /*+ set(query_dop 4) */ * from employees)); QUERY PLAN ---------------------------------------- Streaming(type: LOCAL GATHER dop: 1/4) -> Function Scan on hash_srf (2 rows) ``` ## 相关链接 [ALTER FUNCTION](alter_function.md),[DROP FUNCTION](drop_function.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CREATE-FUNCTION.md --- # CREATE FUNCTION ## 功能描述 创建一个函数。 ## 注意事项 相比于原始的openGauss,dolphin对于CREATE FUNCTION语法的修改为: 1. 增加 LANGUAGE 默认值 plpgsql。 2. 增加语法兼容项 \[NOT] DETERMINISTIC。 3. 增加语法兼容项 { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } 。 4. 增加语法兼容项 SQL SECURITY { DEFINER | INVOKER }。 5. 增加MySQL风格语法格式。 ## 语法格式 dolphin加载后,CREATE FUNCTION 语法的格式为 * 兼容PostgreSQL风格的创建自定义函数语法。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) [ RETURNS rettype | RETURNS TABLE ( { column_name column_type } [, ...] )] [ {IMMUTABLE | STABLE | VOLATILE} | {SHIPPABLE | NOT SHIPPABLE} | [ NOT ] LEAKPROOF | WINDOW | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {[ EXTERNAL| SQL ] SECURITY INVOKER | [ EXTERNAL| SQL ] SECURITY DEFINER | AU THID DEFINER | AUTHID CURRENT_USER} | {FENCED | NOT FENCED} | {PACKAGE} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ] [...] { AS 'definition' | AS 'obj_file', 'link_symbol' } ``` * O风格的创建自定义函数的语法。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ {IMMUTABLE | STABLE | VOLATILE } | {SHIPPABLE | NOT SHIPPABLE} | {PACKAGE} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL| SQL ] SECURITY INVOKER | [ EXTERNAL| SQL ] SECURITY DEFINER | | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][...] { IS | AS } plsql_body / ``` * MySQL风格语法格式。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURNS rettype [ SQL SECURITY { DEFINER | INVOKER } | COMMENT 'text' | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][...] plsql_body ``` ## 参数说明 * **LANGUAGE lang\_name** 用以实现函数的语言的名称。PostgreSQL风格函数默认值 sql, O风格默认值 plpgsql。 MySQL风格语法格式下,LANGUAGE选项仅做语法兼容,可填入其他值,但最终将使用plpgsql作为实现函数的语言。在MySQL风格语法格式下,此选项允许重复。 * **SQL SECURITY INVOKER** 表明该函数将带着调用它的用户的权限执行。该参数可以省略。 SQL SECURITY INVOKER和SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 在MySQL风格语法格式下,此选项允许重复,且与SQL SECURITY DEFINER同类别。该类别的函数选项以最后一个输入为准。 * **SQL SECURITY DEFINER** 声明该函数将以创建它的用户的权限执行。 SQL SECURITY DEFINER和AUTHID DEFINER和SECURITY DEFINER的功能相同。 在MySQL风格语法格式下,此选项允许重复,且与SQL SECURITY INVOKER同类别。该类别的函数选项以最后一个输入为准。 * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** 语法兼容项。此选项允许重复。 ## 示例 ``` --指定 CONTAINS SQL openGauss=# CREATE FUNCTION func_test (s CHAR(20)) RETURNS int CONTAINS SQL AS $$ select 1 $$ ; --指定 DETERMINISTIC openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL DETERMINISTIC AS $$ select s; $$ ; --指定 LANGUAGE SQL openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL LANGUAGE SQL AS $$ select s; $$ ; --指定 NO SQL openGauss=# CREATE FUNCTION func_test (s int) RETURNS int NO SQL AS $$ select s; $$ ; --指定 READS SQL DATA openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL READS SQL DATA AS $$ select s; $$ ; --指定 MODIFIES SQL DATA openGauss=# CREATE FUNCTION func_test (s int) RETURNS int CONTAINS SQL LANGUAGE SQL NO SQL MODIFIES SQL DATA AS $$ select s; $$ ; --指定 SECURITY DEFINER openGauss=# CREATE FUNCTION func_test (s int) RETURNS int NO SQL SQL SECURITY DEFINER AS $$ select s; $$ ; --指定 SECURITY INVOKER openGauss=# CREATE FUNCTION func_test (s int) RETURNS int SQL SECURITY INVOKER READS SQL DATA LANGUAGE SQL AS $$ select s; $$ ; --MySQL风格语法格式 openGauss=# create function func(n int) returns varchar(50) return (select n+1); CREATE FUNCTION openGauss=# select func(1); func ------ 2 (1 row) openGauss=# delimiter // SET openGauss=# create function func10(b int) returns int openGauss-# begin openGauss-# if b > 0 then return b + 10; openGauss-# else return -1; openGauss-# end if; openGauss-# end// CREATE FUNCTION openGauss=# delimiter ; SET openGauss=# select func10(9); func10 -------- 19 (1 row) ``` ## 相关链接 [CREATE FUNCTION](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_function.html) --- --- url: /zh/docs/latest/sql_reference/create_function.md --- # CREATE FUNCTION ## 功能描述 创建一个函数。 ## 注意事项 * 如果创建函数时参数或返回值带有精度,不进行精度检测。 * 创建函数时,函数定义中对表对象的操作建议都显式指定模式,否则可能会导致函数执行异常。 * 在创建函数时,函数内部通过SET语句设置current\_schema和search\_path无效。执行完函数search\_path和current\_schema与执行函数前的search\_path和current\_schema保持一致。 * 如果函数参数中带有出参,SELECT调用函数必须缺省出参,CALL调用函数必须指定出参,对于调用重载的带有PACKAGE属性的函数,CALL调用函数可以缺省出参,具体信息参见[CALL](call.md)的示例。 * 兼容Postgresql风格的函数或者带有PACKAGE属性的函数支持重载。在指定REPLACE的时候,如果参数个数、类型、返回值有变化,不会替换原有函数,而是会建立新的函数。 * 不能创建仅形参名字不同(函数名和参数列表类型都一样)的重载函数。 * 重载的函数在调用时变量需要明确具体的类型。 * 不能创建与存储过程拥有相同名称和参数列表的函数。 * 不支持形式参数仅在自定义ref cursor类型和sys\_refcursor类型不同的重载。 * 在函数内部使用未声明的变量,函数被调用时会报错。 * SELECT调用可以指定不同参数来进行同名函数调用,由于语法不支持调用不带有PACKAGE属性的同名函数。而对于CALL,则只支持调用具有package属性的重载同名函数。 * 在创建function时,不能在avg函数外面嵌套其他agg函数或者其他系统函数。 * 新创建的函数默认会给PUBLIC授予执行权限(详见[GRANT](grant.md))。用户可以选择收回PUBLIC默认执行权限,然后根据需要将执行权限授予其他用户,为了避免出现新函数能被所有人访问的时间窗口,应在一个事务中创建函数并且设置函数执行权限。 * 在函数内部调用其它无参数的函数时,可以省略括号,直接使用函数名进行调用。 * 兼容Oracle风格的函数支持参数注释的查看与导出、导入。 * 兼容Oracle风格的函数支持介于IS/AS与plsql\_body之间的注释的查看与导出、导入。 * 不可与同一模式下已存在的synonym产生命名冲突。 * 当language为internal时,自定义函数的参数类型和返回值类型(void除外)需要与引用的系统函数保持一致,参数个数超出系统函数的部分不做对比校验。当未指定strict时,此选项与系统函数保持一致。 * 通过`CREATE OR REPLACE`语法替换已有的函数时,会一并重建依赖此函数的视图,函数中的参数数据类型变更等情况可能会导致重建视图失败,进而导致替换函数失败。此种情况下,建议先删除依赖的视图,再重建函数,再重新创建视图。 * 允许创建兼容Oracle风格的函数时忽略依赖关系进行创建,并对未定义的类型/存储过程/函数/包变量提供告警功能,需要设置guc参数behavior\_compat\_options='plpgsql\_dependency'。 ## 语法格式 * 兼容PostgreSQL风格的创建自定义函数语法。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) [ RETURNS rettype | RETURNS TABLE ( { column_name column_type } [, ...] )] LANGUAGE lang_name [ {IMMUTABLE | STABLE | VOLATILE | DETERMINISTIC} | {SHIPPABLE | NOT SHIPPABLE} | [ NOT ] LEAKPROOF | WINDOW | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT} | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AU THID DEFINER | AUTHID CURRENT_USER} | {FENCED | NOT FENCED} | {PACKAGE} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | pipelined_clause | {RESULT_CACHE | NOT RESULT_CACHE} ] [...] { AS 'definition' | AS 'obj_file', 'link_symbol' } ``` * O风格的创建自定义函数的语法。 ``` CREATE [ OR REPLACE ] FUNCTION function_name ( [ { argname [ argmode ] argtype [ { DEFAULT | := | = } expression ] } [, ...] ] ) RETURN rettype [ {IMMUTABLE | STABLE | VOLATILE | DETERMINISTIC} | {SHIPPABLE | NOT SHIPPABLE} | {PACKAGE} | [ NOT ] LEAKPROOF | {CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | ROWS result_rows | SET configuration_parameter { {TO | =} value | FROM CURRENT } | COMMENT 'text' | pipelined_clause | parallel_enable_clause | {RESULT_CACHE | NOT RESULT_CACHE} ][...] { IS | AS } plsql_body / ``` * 其中并行参数parallel\_enable\_clause为: ``` PARALLEL_ENABLE [ ( PARTITION argument BY { ANY | HASH (column [, column]) } ) ] ``` ## 参数说明 * **function\_name** 要创建的函数名称(可以用模式修饰)。 取值范围:字符串,要符合标识符的命名规范。且最多为63个字符。若超过63个字符,数据库会截断并保留前63个字符当做函数名称。 * **argname** 函数参数的名称。 取值范围:字符串,要符合标识符的命名规范。且最多为63个字符。若超过63个字符,数据库会截断并保留前63个字符当做函数参数名称。 * **argmode** 函数参数的模式。 取值范围:IN、OUT、INOUT或VARIADIC。缺省值是IN。并且OUT和INOUT模式的参数不能用在RETURNS TABLE的函数定义中。 > \[!NOTE]说明 > VARIADIC用于声明数组类型的参数。 * **argtype** 函数参数的类型。可以使用%TYPE或%ROWTYPE间接引用变量或表的类型,详细可参考存储过程章节[定义变量](variable_definition_statements.md)。 * **expression** 参数的默认表达式。 * **rettype** 函数返回值的数据类型。 如果存在OUT或INOUT参数,可以省略RETURNS子句。如果存在,该子句必须和输出参数所表示的结果类型一致:如果有多个输出参数,则为RECORD,否则与单个输出参数的类型相同。 SETOF修饰词表示该函数将返回一个集合,而不是单独一项。 与argtype相同,同样可以使用%TYPE或%ROWTYPE间接引用类型。 * **column\_name** 字段名称。 * **column\_type** 字段类型。 * **definition** 一个定义函数的字符串常量,含义取决于语言。它可以是一个内部函数名称、一个指向某个目标文件的路径、一个SQL查询、一个过程语言文本。 * **DETERMINISTIC** SQL语法兼容接口,未实现功能,不推荐使用。 * **LANGUAGE lang\_name** 用以实现函数的语言的名称。可以是SQL、internal或者是用户定义的过程语言名称。为了保证向下兼容,该名称可以用单引号(包围)。若采用单引号,则引号内必须为小写。 > \[!NOTE]说明 > internel函数在定义时,如果AS指定为内部系统函数,则新创建函数的参数类型,参数个数,与返回值类型需要与内部系统函数保持一致,且需要有执行此内部系统函数的权限 * **WINDOW** 表示该函数是窗口函数。替换函数定义时不能改变WINDOW属性。 > \[!TIP]须知 > 自定义窗口函数只支持LANGUAGE是internal,并且引用的内部函数必须是窗口函数。 * **IMMUTABLE** 表示该函数在给出同样的参数值时总是返回同样的结果。 * **STABLE** 表示该函数不能修改数据库,对相同参数值,在同一次表扫描里,该函数的返回值不变,但是返回值可能在不同SQL语句之间变化。 * **VOLATILE** 表示该函数值可以在一次表扫描内改变,因此不会做任何优化。 * **SHIPPABLE**|**NOT SHIPPABLE** 表示该函数是否可以下推执行。预留接口,不推荐使用。 * **FENCED**|**NOT FENCED** 声明用户定义的C函数是在保护模式还是非保护模式下执行。预留接口,不推荐使用。 * **RESULT\_CACHE**|**NOT RESULT\_CACHE** 表示用户定义的函数是否支持函数结果缓存。 * **PACKAGE** 表示该函数是否支持重载。PostgreSQL风格的函数本身就支持重载,此参数主要是针对其它风格的函数。 * 不允许package函数和非package函数重载或者替换。 * package函数不支持VARIADIC类型的参数。 * 不允许修改函数的package属性。 * **LEAKPROOF** 指出该函数的参数只包括返回值。LEAKPROOF只能由系统管理员设置。 * **CALLED ON NULL INPUT** 表明该函数的某些参数是NULL的时候可以按照正常的方式调用。该参数可以省略。 * **RETURNS NULL ON NULL INPUT** **STRICT** STRICT用于指定如果函数的某个参数是NULL,此函数总是返回NULL。如果声明了这个参数,当有NULL值参数时该函数不会被执行;而只是自动返回一个NULL结果。 RETURNS NULL ON NULL INPUT和STRICT的功能相同。 * **EXTERNAL** 目的是和SQL兼容,是可选的,这个特性适合于所有函数,而不仅是外部函数。 * **SECURITY INVOKER** **AUTHID CURRENT\_USER** 表明该函数将带着调用它的用户的权限执行。该参数可以省略。 SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SECURITY DEFINER** **AUTHID DEFINER** 声明该函数将以创建它的用户的权限执行。 AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **COST execution\_cost** 用来估计函数的执行成本。 execution\_cost以cpu\_operator\_cost为单位。 取值范围:正数 * **ROWS result\_rows** 估计函数返回的行数。用于函数返回的是一个集合。 取值范围:正数,默认值是1000行。 * **COMMENT 'text'** 函数注释。 * **configuration\_parameter** * **value** 把指定的数据库会话参数值设置为给定的值。如果value是DEFAULT或者RESET,则在新的会话中使用系统的缺省设置。OFF关闭设置。 取值范围:字符串 * DEFAULT * OFF * RESET 指定默认值。 * **from current** 取当前会话中的值设置为configuration\_parameter的值。 * **plsql\_body** PL/SQL存储过程体。用于O风格创建函数时,PL/SQL结尾的end后可以加上tag标签以兼容指定函数名的情况,目前tag标签也可以不与函数名一致。例如: ```sql CREATE OR REPLACE FUNCTION f1 (p int) RETURN int IS begin RETURN 1; END f1; / CREATE OR REPLACE FUNCTION f2 (p int) RETURN int IS begin RETURN 1; END f3; / ``` > \[!TIP]须知 > 当在函数体中创建用户时,日志中会记录密码的明文。因此不建议用户在函数体中创建用户。 * **plpgsql\_body** PL/pgSQL函数体。用于PostgreSQL风格创建函数时,language指定为plpgsql的情况。详见[PL/pgSQL语言函数](pl_pgsql_functions.md)。 * **pipelined\_clause** 指定函数为可以返回行集合(可以是嵌套表或数组)的函数,您可以像查询物理表一样查询函数或者将其赋值给集合变量。 如果函数指定了该选项,可以通过在FROM子句中使用TABLE调用管道函数。(TABLE可以省略)。如果函数不存在入参,省略入参。例如: ```sql SELECT * FROM TABLE(table_function_name(parameter_list)); -- 或者 SELECT * FROM table_function_name(parameter_list); -- 或者(函数不存在入参) SELECT * FROM TABLE(table_function_name); ``` 取值范围:PIPELINED * **parallel\_enable\_clause** 指定函数是否可以并行。其中PARTITION BY子句仅支持函数入参中有游标类型时指定。 参数的详细描述如下所示。 * argument 指定入参中并行的游标名。 * ANY | HASH (column \[,column]) 指定并行游标对数据分布的方式,目前支持ANY和HASH。指定为HASH时需要指定一个或多个列名。 > \[!TIP]须知 > > 1. 函数体内对指定的并行游标的操作仅支持直接FETCH CURSOR,当存在FETCH FIRST/LAST/ABSOLUTE/RELATIVE/BACKWARD/PRIOR CURSOR等操作时会报错。 > 2. 指定了该子句,即默认设置了IMMUTABLE,且不允许同时设置STABLE/VOLATILE。 > 3. 该子句仅在A兼容性的数据库下支持。 > 4. 函数并行仅支持游标表达式作为入参。 > 5. 支持plan hint指定query dop参数使函数并行,但需要游标表达式同样指定query\_dop,仅指定函数的query\_dop hint无法走并行(可见下方示例)。 ## 示例 ``` --定义函数为SQL查询。 openGauss=# CREATE FUNCTION func_add_sql(integer, integer) RETURNS integer AS 'select $1 + $2;' LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT; --利用参数名用 PL/pgSQL 自增一个整数。 openGauss=# CREATE OR REPLACE FUNCTION func_increment_plsql(i integer) RETURNS integer AS $$ BEGIN RETURN i + 1; END; $$ LANGUAGE plpgsql; --返回RECORD类型 openGauss=# CREATE OR REPLACE FUNCTION func_increment_sql(i int, out result_1 bigint, out result_2 bigint) returns SETOF RECORD as $$ begin result_1 = i + 1; result_2 = i * 10; return next; end; $$language plpgsql; --返回一个包含多个输出参数的记录。 openGauss=# CREATE FUNCTION func_dup_sql(in int, out f1 int, out f2 text) AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$ LANGUAGE SQL; openGauss=# SELECT * FROM func_dup_sql(42); --计算两个整数的和,并返回结果。如果输入为null,则返回null。 openGauss=# CREATE FUNCTION func_add_sql2(num1 integer, num2 integer) RETURN integer AS BEGIN RETURN num1 + num2; END; / --修改函数func_add_sql2的执行规则为IMMUTABLE,即参数不变时返回相同结果。 openGauss=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) IMMUTABLE; --将函数func_add_sql2的名称修改为add_two_number。 openGauss=# ALTER FUNCTION func_add_sql2(INTEGER, INTEGER) RENAME TO add_two_number; --将函数add_two_number的属者改为omm。 openGauss=# ALTER FUNCTION add_two_number(INTEGER, INTEGER) OWNER TO omm; --删除函数。 openGauss=# DROP FUNCTION add_two_number; openGauss=# DROP FUNCTION func_increment_sql; openGauss=# DROP FUNCTION func_dup_sql; openGauss=# DROP FUNCTION func_increment_plsql; openGauss=# DROP FUNCTION func_add_sql; -- 函数支持并行参数示例 openGauss=# create table employees (employee_id number(6), department_id NUMBER); openGauss=# openGauss=# BEGIN FOR i IN 1..999999 LOOP INSERT INTO employees VALUES (i, 60); END LOOP; COMMIT; END; / openGauss=# CREATE TYPE my_outrec_typ AS (employee_id numeric(6,0), department_id numeric); -- 创建函数,指定PARALLEL_ENABLE openGauss=# CREATE OR REPLACE FUNCTION hash_srf (p SYS_REFCURSOR) RETURN setof my_outrec_typ parallel_enable (partition p by hash(employee_id)) IS out_rec my_outrec_typ := my_outrec_typ(NULL, NULL); BEGIN LOOP FETCH p INTO out_rec.employee_id, out_rec.department_id; -- input row EXIT WHEN p%NOTFOUND; return next out_rec; END LOOP; RETURN; END hash_srf; / openGauss=# set query_dop = 4; -- 函数并行 openGauss=# explain (costs off) select * from hash_srf(cursor (select * from employees)); QUERY PLAN ---------------------------------------- Streaming(type: LOCAL GATHER dop: 1/4) -> Function Scan on hash_srf (2 rows) openGauss=# set query_dop = 1; -- 仅支持函数的query_dop hint无法走并行计划 openGauss=# explain (costs off) select /*+ set(query_dop 4) */ * from hash_srf(cursor (select * from employees)); QUERY PLAN --------------------------- Function Scan on hash_srf (1 row) -- 需同时指定游标表达式的query_dop hint openGauss=# explain (costs off) select /*+ set(query_dop 4) */ * from hash_srf(cursor (select /*+ set(query_dop 4) */ * from employees)); QUERY PLAN ---------------------------------------- Streaming(type: LOCAL GATHER dop: 1/4) -> Function Scan on hash_srf (2 rows) ``` ## 相关链接 [ALTER FUNCTION](alter_function.md),[DROP FUNCTION](drop_function.md) --- --- url: /en/docs/latest-lite/sql_reference/create_foreign_data_wrapper.md --- # CREATE FUNCTION DATA WRAPPER ## Function Description Defines a new foreign data wrapper (FDW). ## Syntax ``` CREATE FOREIGN DATA WRAPPER name [ HANDLER handler_function | NO HANDLER ] [ VALIDATOR validator_function | NO VALIDATOR ] [ OPTIONS ( option 'value' [,...] ) ] ``` ## Parameter Description * **name** Specifies the name of an FDW to be created. * **HANDLER handler\_function** **handler\_function** is the name of the previously registered function that will be called to retrieve the execution function of the foreign table. The handler function cannot contain any parameter, and its return type must be fdw\_handler. * **VALIDATOR validator\_function** **validator\_function** is the name of the previously registered function that will be called to check the general options of the given FDW, as well as the options for the foreign server and user mapping using the FDW. If no validator function is specified, options are not checked at creation time. (The FDW may ignore or reject invalid option specifications at runtime, depending on the implementation.) The validator function must accept two arguments: one is of type text\[], which will contain an array of options stored in the system directory, and the other is of type oid, which will be the oid of the system directory that contains the options. The return type is ignored. The function should report invalid options using the ereport (ERROR) function. * **OPTIONS (option 'value' \[,...])** Specifies options for the new FDW. The allowed option names and values are specific to each FDW and validated using the FDW validator function. The option name must be unique. ## Examples ``` --Creates a useless FDW named dummy. openGauss=# CREATE FOREIGN DATA WRAPPER dummy; --Use the handler function file_fdw_handler to create an FDW named file. openGauss=# CREATE FOREIGN DATA WRAPPER file HANDLER file_fdw_handler; --Create an FDW named mywrapper. openGauss=# CREATE FOREIGN DATA WRAPPER mywrapper OPTIONS (debug 'true'); ``` --- --- url: /en/docs/latest-lite/sql_reference/create_group.md --- # CREATE GROUP ## Function **CREATE GROUP** creates a user group. ## Precautions **CREATE GROUP** is an alias for **CREATE ROLE**, and it is not a standard SQL syntax and not recommended. Users can use **CREATE ROLE** directly. ## Syntax ``` CREATE GROUP group_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; ``` The syntax of the **option** clause is as follows: ``` {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN rol e_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## Parameter Description See [Parameter Description](create_role.md#en-us_topic_0283136858_en-us_topic_0237122112_en-us_topic_0059778189_s5a43ec5742a742089e2c302063de7fe4) in **CREATE ROLE**. ## Helpful Links [ALTER GROUP](alter_group.md), [DROP GROUP](drop_group.md), and [CREATE ROLE](create_role.md) --- --- url: /en/docs/latest/sql_reference/create_group.md --- # CREATE GROUP ## Function **CREATE GROUP** creates a user group. ## Precautions **CREATE GROUP** is an alias for **CREATE ROLE**, and it is not a standard SQL syntax and not recommended. Users can use **CREATE ROLE** directly. ## Syntax ``` CREATE GROUP group_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; ``` The syntax of the **option** clause is as follows: ``` {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN rol e_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## Parameter Description See [Parameter Description](create_role.md#en-us_topic_0283136858_en-us_topic_0237122112_en-us_topic_0059778189_s5a43ec5742a742089e2c302063de7fe4) in **CREATE ROLE**. ## Helpful Links [ALTER GROUP](alter_group.md), [DROP GROUP](drop_group.md), and [CREATE ROLE](create_role.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_group.md --- # CREATE GROUP ## 功能描述 创建一个新用户组。 ## 注意事项 CREATE GROUP是CREATE ROLE的别名,非SQL标准语法,不推荐使用,建议用户直接使用CREATE ROLE替代。 ## 语法格式 ``` CREATE GROUP group_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; ``` 其中可选项option子句语法为: ``` {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN rol e_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## 参数说明 请参考CREATE ROLE的[参数说明](create_role.md#zh-cn_topic_0283136858_zh-cn_topic_0237122112_zh-cn_topic_0059778189_s5a43ec5742a742089e2c302063de7fe4)。 ## 相关链接 [ALTER GROUP](alter_group.md),[DROP GROUP](drop_group.md),[CREATE ROLE](create_role.md) --- --- url: /zh/docs/latest/sql_reference/create_group.md --- # CREATE GROUP ## 功能描述 创建一个新用户组。 ## 注意事项 CREATE GROUP是CREATE ROLE的别名,非SQL标准语法,不推荐使用,建议用户直接使用CREATE ROLE替代。 ## 语法格式 ``` CREATE GROUP group_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [ EXPIRED ] | DISABLE }; ``` 其中可选项option子句语法为: ``` {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN rol e_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## 参数说明 请参考CREATE ROLE的[参数说明](create_role.md#zh-cn_topic_0283136858_zh-cn_topic_0237122112_zh-cn_topic_0059778189_s5a43ec5742a742089e2c302063de7fe4)。 ## 相关链接 [ALTER GROUP](alter_group.md),[DROP GROUP](drop_group.md),[CREATE ROLE](create_role.md) --- --- url: /en/docs/latest-lite/sql_reference/create_incremental_materialized_view.md --- # CREATE INCREMENTAL MATERIALIZED VIEW ## Function **CREATE INCREMENTAL MATERIALIZED VIEW** creates a fast-refresh materialized view, and you can refresh the data of the materialized view by using **REFRESH MATERIALIZED VIEW** (full refresh) and **REFRESH INCREMENTAL MATERIALIZED VIEW** (incremental refresh). **CREATE INCREMENTAL MATERIALIZED VIEW** is similar to **CREATE TABLE AS**, but it remembers the query used to initialize the view, so it can refresh data later. A materialized view has many attributes that are the same as those of a table, but does not support temporary materialized views. ## Precautions * Fast-refresh materialized views cannot be created on temporary tables or global temporary tables. * Fast-refresh materialized views support only simple filter queries and UNION ALL queries of base tables. * Distribution columns cannot be specified when an incremental MV is created. * After a fast-refresh materialized view is created, most DDL operations in the base table are no longer supported. * IUD operations cannot be performed on fast-refresh materialized views. * After a fast-refresh materialized view is created, you need to run the **REFRESH** command to synchronize the materialized view with the base table when the base table data changes. ## Syntax ``` CREATE INCREMENTAL MATERIALIZED VIEW mv_name [ (column_name [, ...] ) ] [ TABLESPACE tablespace_name ] AS query; ``` ## Parameter Description * **mv\_name** Name (optionally schema-qualified) of the materialized view to be created. Value range: a string. It must comply with the naming convention. * **column\_name** Column name in the new materialized view. The materialized view supports specified columns. The number of specified columns must be the same as the number of columns in the result of the subsequent query statement. If no column name is provided, the column name is obtained from the output column name of the query. Value range: a string. It must comply with the naming convention. * **TABLESPACE tablespace\_name** Tablespace to which the new materialized view belongs. If not specified, the default tablespace is used. * **AS query** **SELECT** or **TABLE** command. This query will be run in a security-constrained operation. ## Examples ``` -- Create an ordinary table. openGauss=# CREATE TABLE my_table (c1 int, c2 int); -- Create a fast-refresh materialized view. openGauss=# CREATE INCREMENTAL MATERIALIZED VIEW my_imv AS SELECT * FROM my_table; -- Write data to the base table. openGauss=# INSERT INTO my_table VALUES(1,1),(2,2); -- Incrementally refresh the fast-refresh materialized view my_imv. openGauss=# REFRESH INCREMENTAL MATERIALIZED VIEW my_imv; ``` ## Helpful Links [ALTER MATERIALIZED VIEW](alter_materialized_view.md), [CREATE MATERIALIZED VIEW](create_materialized_view.md), [CREATE TABLE](create_table.md), [DROP MATERIALIZED VIEW](drop_materialized_view.md), [REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md), and [REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /en/docs/latest/sql_reference/create_incremental_materialized_view.md --- # CREATE INCREMENTAL MATERIALIZED VIEW ## Function **CREATE INCREMENTAL MATERIALIZED VIEW** creates an fast-refresh materialized view, and you can refresh the data of the materialized view by using **REFRESH MATERIALIZED VIEW** (full refresh) and **REFRESH INCREMENTAL MATERIALIZED VIEW** (incremental refresh). **CREATE INCREMENTAL MATERIALIZED VIEW** is similar to **CREATE TABLE AS**, but it remembers the query used to initialize the view, so it can refresh data later. A materialized view has many attributes that are the same as those of a table, but does not support temporary materialized views. ## Precautions * fast-refresh materialized views cannot be created on temporary tables or global temporary tables. * fast-refresh materialized views support only simple filter queries and UNION ALL queries of base tables. * Distribution columns cannot be specified when an incremental MV is created. * After an fast-refresh materialized view is created, most DDL operations in the base table are no longer supported. * IUD operations cannot be performed on fast-refresh materialized views. * After an fast-refresh materialized view is created, you need to run the **REFRESH** command to synchronize the materialized view with the base table when the base table data changes. ## Syntax ``` CREATE INCREMENTAL MATERIALIZED VIEW mv_name [ (column_name [, ...] ) ] [ TABLESPACE tablespace_name ] AS query; ``` ## Parameter Description * **mv\_name** Name (optionally schema-qualified) of the materialized view to be created. Value range: a string. It must comply with the naming convention. * **column\_name** Column name in the new materialized view. The materialized view supports specified columns. The number of specified columns must be the same as the number of columns in the result of the subsequent query statement. If no column name is provided, the column name is obtained from the output column name of the query. Value range: a string. It must comply with the naming convention. * **TABLESPACE tablespace\_name** Tablespace to which the new materialized view belongs. If not specified, the default tablespace is used. * **AS query** **SELECT** or **TABLE** command This query will be run in a security-constrained operation. ## Examples ``` -- Create an ordinary table. openGauss=# CREATE TABLE my_table (c1 int, c2 int); -- Create an fast-refresh materialized view. openGauss=# CREATE INCREMENTAL MATERIALIZED VIEW my_imv AS SELECT * FROM my_table; -- Write data to the base table. openGauss=# INSERT INTO my_table VALUES(1,1),(2,2); -- Incrementally refresh thefast-refresh materializedd view my_imv. openGauss=# REFRESH INCREMENTAL MATERIALIZED VIEW my_imv; ``` ## Helpful Links [ALTER MATERIALIZED VIEW](alter_materialized_view.md), [CREATE MATERIALIZED VIEW](create_materialized_view.md), [CREATE TABLE](create_table.md), [DROP MATERIALIZED VIEW](drop_materialized_view.md), [REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md), and [REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_incremental_materialized_view.md --- # CREATE INCREMENTAL MATERIALIZED VIEW ## 功能描述 CREATE INCREMENTAL MATERIALIZED VIEW会创建一个增量物化视图,并且后续可以使用REFRESH MATERIALIZED VIEW(全量刷新)和REFRESH INCREMENTAL MATERIALIZED VIEW(增量刷新)刷新物化视图的数据。 CREATE INCREMENTAL MATERIALIZED VIEW类似于CREATE TABLE AS,不过它会记住被用来初始化该视图的查询, 因此它可以在后续中进行数据刷新。一个物化视图有很多和表相同的属性,但是不支持临时物化视图。 ## 注意事项 * 增量物化视图不可以在临时表或全局临时表上创建。 * 增量物化视图仅支持简单过滤查询和基表UNION ALL查询。 * 创建增量物化视图不可指定分布列。 * 创建增量物化视图后,基表中的绝大多数DDL操作不再支持。 * 不支持对增量物化视图进行IUD操作。 * 增量物化视图创建后,当基表数据发生变化时,需要使用刷新(REFRESH)命令保持物化视图与基表同步。 ## 语法格式 ``` CREATE INCREMENTAL MATERIALIZED VIEW mv_name [ (column_name [, ...] ) ] [ TABLESPACE tablespace_name ] AS query; ``` ## 参数说明 * **mv\_name** 要创建的物化视图的名称(可以被模式限定)。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新物化视图中的一个列名。物化视图支持指定列,指定列需要和后面的查询语句结果的列数量保持一致;如果没有提供列名,会从查询的输出列名中获取列名。 取值范围:字符串,要符合标识符的命名规范。 * **TABLESPACE tablespace\_name** 指定新建物化视图所属表空间。如果没有声明,将使用默认表空间。 * **AS query** 一个SELECT或者TABLE命令。这个查询将在一个安全受限的操作中运行。 ## 示例 ``` --创建一个普通表 openGauss=# CREATE TABLE my_table (c1 int, c2 int); --创建增量物化视图 openGauss=# CREATE INCREMENTAL MATERIALIZED VIEW my_imv AS SELECT * FROM my_table; --基表写入数据 openGauss=# INSERT INTO my_table VALUES(1,1),(2,2); --对增量物化视图my_imv进行增量刷新 openGauss=# REFRESH INCREMENTAL MATERIALIZED VIEW my_imv; ``` ## 相关链接 [ALTER MATERIALIZED VIEW](alter_materialized_view.md), [CREATE MATERIALIZED VIEW](create_materialized_view.md),[CREATE TABLE](create_table.md), [DROP MATERIALIZED VIEW](drop_materialized_view.md),[REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md) ,[REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /zh/docs/latest/sql_reference/create_incremental_materialized_view.md --- # CREATE INCREMENTAL MATERIALIZED VIEW ## 功能描述 CREATE INCREMENTAL MATERIALIZED VIEW会创建一个增量物化视图,并且后续可以使用REFRESH MATERIALIZED VIEW(全量刷新)和REFRESH INCREMENTAL MATERIALIZED VIEW(增量刷新)刷新物化视图的数据。 CREATE INCREMENTAL MATERIALIZED VIEW类似于CREATE TABLE AS,不过它会记住被用来初始化该视图的查询, 因此它可以在后续中进行数据刷新。一个物化视图有很多和表相同的属性,但是不支持临时物化视图。 ## 注意事项 * 增量物化视图不可以在临时表或全局临时表上创建。 * 增量物化视图仅支持简单过滤查询和基表UNION ALL查询。 * 创建增量物化视图不可指定分布列。 * 创建增量物化视图后,基表中的绝大多数DDL操作不再支持。 * 不支持对增量物化视图进行IUD操作。 * 增量物化视图创建后,当基表数据发生变化时,需要使用刷新(REFRESH)命令保持物化视图与基表同步。 ## 语法格式 ``` CREATE INCREMENTAL MATERIALIZED VIEW mv_name [ (column_name [, ...] ) ] [ TABLESPACE tablespace_name ] AS query; ``` ## 参数说明 * **mv\_name** 要创建的物化视图的名称(可以被模式限定)。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新物化视图中的一个列名。物化视图支持指定列,指定列需要和后面的查询语句结果的列数量保持一致;如果没有提供列名,会从查询的输出列名中获取列名。 取值范围:字符串,要符合标识符的命名规范。 * **TABLESPACE tablespace\_name** 指定新建物化视图所属表空间。如果没有声明,将使用默认表空间。 * **AS query** 一个SELECT或者TABLE命令。这个查询将在一个安全受限的操作中运行。 ## 示例 ``` --创建一个普通表 openGauss=# CREATE TABLE my_table (c1 int, c2 int); --创建增量物化视图 openGauss=# CREATE INCREMENTAL MATERIALIZED VIEW my_imv AS SELECT * FROM my_table; --基表写入数据 openGauss=# INSERT INTO my_table VALUES(1,1),(2,2); --对增量物化视图my_imv进行增量刷新 openGauss=# REFRESH INCREMENTAL MATERIALIZED VIEW my_imv; ``` ## 相关链接 [ALTER MATERIALIZED VIEW](alter_materialized_view.md), [CREATE MATERIALIZED VIEW](alter_materialized_view.md),[CREATE TABLE](create_table.md), [DROP MATERIALIZED VIEW](drop_materialized_view.md),[REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md) ,[REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /en/docs/latest-lite/sql_reference/create_index.md --- # CREATE INDEX ## Function **CREATE INDEX-bak** defines a new index. Indexes are primarily used to enhance database performance (though inappropriate use can result in database performance deterioration). You are advised to create indexes on: * Columns that are often queried * Join conditions. For a query on joined columns, you are advised to create a composite index on the columns, For example, for **select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b**, you can create a composite index on columns **a** and **b** in table **t1**. * Columns having filter criteria (especially scope criteria) of a **where** clause * Columns that appear after **order by**, **group by**, and **distinct** The partitioned table does not support partial index creation. ## Precautions * Indexes consume storage and computing resources. Creating too many indexes has negative impact on database performance (especially the performance of data import. Therefore, you are advised to import the data before creating indexes). Therefore, create indexes only when they are necessary. * All functions and operators used in an index definition must be immutable, that is, their results must depend only on their parameters and never on any outside influence (such as the contents of another table or the current time). This restriction ensures that the behavior of the index is well-defined. To use a customized function in an index expression or **WHERE** clause, remember to mark the function **immutable** when you create it. * Partitioned table indexes are classified into LOCAL indexes and GLOBAL indexes. A LOCAL index binds to a specific partition, and a GLOBAL index corresponds to the entire partitioned table. * If the two indexes are used, you cannot create expression and partial indexes. If the PSORT index is used, you cannot create unique indexes. If the B-tree index is used, you can create unique indexes. * Column-store tables support GIN indexes, rather than partial indexes and unique indexes. If GIN indexes are used, you can create expression indexes. However, an expression in this situation cannot contain empty splitters, empty columns, or multiple columns. * Currently, only row-store table indexes, temporary table indexes, and local indexes of partitioned tables can be used as hash indexes. Multi-column indexes are not supported. * A user granted with the **CREATE ANY INDEX** permission can create indexes in both the public and user schemas. ## Syntax * Create an index on a table. ``` CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [schema_name.]index_name ] ON table_name [ USING method ] ({ { column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ INCLUDE ( column_name [, ...] )] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ COMMENT text ] [ WHERE predicate ]; ``` * Create an index on a partitioned table. ``` CREATE [ UNIQUE ] INDEX [ [schema_name.]index_name ] ON table_name [ USING method ] ( {{ column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name | SUBPARTITION index_subpartition_name [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ INCLUDE ( column_name [, ...] )] [ WITH ( { storage_parameter = value } [, ...] ) ] [ TABLESPACE tablespace_name ] [ COMMENT text ]; ``` ## 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 entries will generate an error. Currently, only B-tree and UB-tree indexes support unique indexes. * **CONCURRENTLY** Create an index (with ShareUpdateExclusiveLock) in non-blocking DML mode. A normal **CREATE INDEX** acquires exclusive lock on the table on which the index depends, blocking other accesses until the index drop can be completed. If this keyword is specified, DML is not blocked during the creation. * This option can only specify a name of one index. * The **CREATE INDEX** statement can be run within a transaction, but **CREATE INDEX CONCURRENTLY** cannot. * Column-store tables, partitioned tables, and temporary tables do not support **CREATE INDEX CONCURRENTLY**. > \[!NOTE]NOTE > > * This keyword is specified when an index is created. The entire table needs to be scanned twice and built. When the table is scanned for the first time, an index is created and the read and write operations are not blocked. During the second scan, changes that have occurred since the first scan are merged and updated. > * The table needs to be scanned and built twice, and all existing transactions that may modify the table must be completed. This means that the creation of the index takes a longer time than normal. In addition, the CPU and I/O consumption also affects other services. > * If an index build fails, it leaves an "unusable" index. This index is ignored by the query, but it still consumes the update overhead. In this case, you are advised to delete the index and try **CREATE INDEX CONCURRENTLY** again. > * After the second scan, index creation must wait for any transaction that holds a snapshot earlier than the snapshot taken by the second scan to terminate. In addition, the ShareUpdateExclusiveLock (level 4) added during index creation conflicts with a lock whose level is greater than or equal to 4. Therefore, when such an index is created, the system is prone to hang or deadlock. For example: > * If two sessions create an index concurrently for the same table, a deadlock occurs. > * If a session creates an index concurrently for a table and another session drops a table, a deadlock occurs. > * There are three sessions. Session 1 locks table **a** and does not commit it. Session 2 creates an index concurrently for table **b**. Session 3 writes data to table **a**. Before the transaction of session 1 is committed, session 2 is blocked. > * The transaction isolation level is set to repeatable read (read committed by default). Two sessions are started. Session 1 writes data to table **a** and does not commit it. Session 2 creates an index concurrently for table **b**. Before the transaction of session 1 is committed, session 2 is blocked. * **schema\_name** Specifies the schema name. Value range: an existing schema name * **index\_name** Specifies the name of the index to be created. The schema of the index is the same as that of the table. Value range: a string. It must comply with the identifier naming convention. * **table\_name** Specifies the name of the table to be indexed (optionally schema-qualified). Value range: an existing table name * **USING method** Specifies the name of the index method to be used. Value range: * **btree**: B-tree indexes store key values of data in a B+ tree structure. This structure helps users to quickly search for indexes. B-tree indexes support comparison queries with ranges specified. * **hash**: Hash indexes use hash functions to hash index keywords. Only simple equivalence comparison can be processed. This value is applicable to scenarios where index values are long. * **gin**: GIN indexes are reverse indexes and can process values that contain multiple keys (for example, arrays). * **gist**: GiST indexes are suitable for the set data type and multidimensional data types, such as geometric and geographic data types. The following data types are supported: box, point, poly, circle, tsvector, tsquery, and range. * **Psort**: psort index. It is used to perform partial sort on column-store tables. * **ubtree**: Multi-version B-tree index used only for Ustore tables. The index page contains transaction information and can be recycled. By default, the INSERTPT function is enabled for UBtree indexes. Row-store tables (Astore storage engine) support the following index types: **btree** (default), **hash**, **gin**, and **gist**. Row-store tables (Ustore storage engine) support the following index type: **ubtree**. Column-store tables support the following index types: **Psort** (default), **btree**, and **gin**. Global temporary tables do not support GIN and GiST indexes. > \[!NOTE]NOTE > Column-store tables support GIN indexes only for the tsvector type. That is, the input parameter for creating a column-store GIN index must be the return value of the **to\_tsvector** function. This method is commonly used for GIN indexes. * **column\_name** Specifies the name of the column on which an index is to be created. Multiple columns can be specified if the index method supports multi-column indexes. A global index supports a maximum of 31 columns, and other indexes support a maximum of 32 columns. * **column\_name ( length )** Creates a prefix key index based on a column in the table. **column\_name** indicates the column name of the prefix key, and **length** indicates the prefix length. The prefix key uses the prefix of the specified column data as the index key value, which reduces the storage space occupied by the index. Indexes can be used for filter and join conditions that contain prefix key columns. > \[!NOTE]NOTE > > * This syntax is valid only when **sql\_compatibility** is set to **B**. If **sql\_compatibility** is set to other values, this clause is regarded as the function expression key. > * The prefix key supports the following index methods: btree and ubtree. > * The data type of the prefix key column must be binary or character (excluding special characters). > * The prefix length must be a positive integer that does not exceed 2676 and cannot exceed the maximum length of the column. For the binary type, the prefix length is measured in bytes. For non-binary character types, the prefix length is measured in characters. The actual length of the key value is restricted by the internal page. If a column contains multi-byte characters or an index has multiple keys, the length of the index line may exceed the upper limit. As a result, an error is reported. Consider this situation when setting a long prefix length. > * In the CREATE INDEX syntax, the following keywords cannot be used as prefix keys for column names: COALESCE, EXTRACT, GREATEST, LEAST, NULLIF, NVARCHAR, NVL, OVERLAY, POSITION, SUBSTRING, TIMESTAMPDIFF, TREAT, TRIM, XMLCONCAT, XMLELEMENT, XMLEXISTS, XMLFOREST, XMLPARSE, XMLPI, XMLROOT, and XMLSERIALIZE. * **expression** Specifies an expression based on one or more columns of the table. The expression usually must be written with surrounding parentheses, as shown in the syntax. However, the parentheses can be omitted if the expression has the form of a function call. Expression can be used to obtain fast access to data based on some transformation of the basic data. For example, an index computed on **upper(col)** would allow the clause **WHERE upper(col) = 'JIM'** to use an index. If an expression contains **IS NULL**, the index for this expression is invalid. In this case, you are advised to create a partial index. * **COLLATE collation** Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the **select \* from pg\_collation** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **opclass** Specifies the name of an operator class. An operator class can be specified for each column of an index. The operator class identifies the operators to be used by the index for that column. For example, a B-tree index on the type int4 would use the **int4\_ops** class; this operator class includes comparison functions for values of type int4. In practice, the default operator class for the column's data type is sufficient. The operator class applies to data with multiple sorts. For example, users might want to sort a complex-number data type either by absolute value or by real part. They could do this by defining two operator classes for the data type and then selecting the proper class when making an index. * **ASC** Specifies an ascending (default) sort order. * **DESC** Specifies a descending sort order. * **NULLS FIRST** Specifies that null values appear before non-null values in the sort ordering. This is the default when **DESC** is specified. * **NULLS LAST** Specifies that null values appear after non-null values in the sort ordering. This is the default when **DESC** is not specified. * **LOCAL** Specifies that the partitioned index to be created is a LOCAL index. * **GLOBAL** Specifies the partitioned index to be created as a GLOBAL index. If no keyword is specified, a GLOBAL index is created by default. * **INCLUDE ( column\_name \[, ...]** ) The optional **INCLUDE** clause specifies that some non-key columns are included in indexes. Non-key columns cannot be used as search criteria for accelerating index scans, and they are omitted when the unique constraints of the indexes are checked. An index-only scan can directly return content in the non-key columns without accessing the heap table corresponding to the indexes. Exercise caution when adding non-key columns as **INCLUDE** columns, especially for wide columns. If the size of an index tuple exceeds the maximum size allowed by the index type, data insertion fails. Note that in any case, adding non-key columns to an index increases the space occupied by the index, which may slow down the search speed. Currently, only UBtree indexes access mode supports this feature. Non-key columns are stored in the index leaf tuple corresponding to the heap tuple and are not included in the tuple on the upper-layer index page. * **WITH ( {storage\_parameter = value} \[, ... ] )** Specifies the storage parameter used for an index. Value range: Only index GIN supports parameters **FASTUPDATE** and **GIN\_PENDING\_LIST\_LIMIT**. Indexes other than GIN and psort support the **FILLFACTOR** parameter. Only UBtree indexes support **INDEXSPLIT**. * FILLFACTOR The fill factor of an index is a percentage from 10 to 100. Value range: 10–100 * FASTUPDATE Specifies whether fast update is enabled for the GIN index. Value range: : **ON** and **OFF** Default value: **ON** * GIN\_PENDING\_LIST\_LIMIT Specifies the maximum capacity of the pending list of the GIN index when fast update is enabled for the GIN index. Value range: 64–\*INT\*MAX\_. The unit is KB. Default value: The default value of **gin\_pending\_list\_limit** depends on **gin\_pending\_list\_limit** specified in GUC parameters. By default, the value is **4**. * INDEXSPLIT Specifies the splitting policy of UBtree indexes. The **DEFAULT** policy is the same as the splitting policy of UBtree indexes. The **INSERTPT** policy can significantly reduce the index space usage in some scenarios. Value range: **INSERTPT** and **DEFAULT** Default value: **INSERTPT** * **TABLESPACE tablespace\_name** Specifies the tablespace for an index. If no tablespace is specified, the default tablespace is used. Value range: an existing table name * **COMMENT text** Specifies the comment of an index. If no comment is specified, the comment is empty. * **WHERE predicate** Creates a partial index. A partial index is an index that contains entries for only a portion of a table, usually a portion that is more useful for indexing than the rest of the table. For example, if you have a table that contains both billed and unbilled orders where the unbilled orders take up a small fraction of the total table and yet that is an often used portion, you can improve performance by creating an index on just that portion. In addition, **WHERE** with **UNIQUE** can be used to enforce uniqueness over a subset for a table. Value range: The **predicate** expression can only refer to columns of the underlying table, but it can use all columns, not just the ones being indexed. Currently, subqueries and aggregate expressions are forbidden in **WHERE**. You are not advised to use numeric types such as int for **predicate**, because such types can be implicitly converted to bool values (non-zero values are implicitly converted to **true** and **0** is implicitly converted to **false**), which may cause unexpected results. * **PARTITION index\_partition\_name** Specifies the name of an index partition. Value range: a string. It must comply with the identifier naming convention. * **SUBPARTITION index\_subpartition\_name** Specifies the name of an level-2 index partition. Value range: a string. It must comply with the identifier naming convention. * **TABLESPACE index\_partition\_tablespace** Specifies the tablespace of an index partition. Value range: If this parameter is not specified, the value of **index\_tablespace** is used. * **COMPRESSTYPE** Sets the index compression algorithm. The value **1** indicates the PGLZ algorithm, the value **2** indicates the ZSTD algorithm, the value **3** indicates the PGZSTD algorithm (currently not supported), and the value **4** indicates the ZLIB algorithm. By default, indexes are not compressed. (Only B-tree indexes are supported.) Value range: 0 to 4. The default value is **0**. * **COMPRESS\_LEVEL** Sets the index compression algorithm level. This parameter is valid only when **COMPRESSTYPE** is set to **2** or **4**. A higher compression level indicates a better index compression effect and a slower index access speed. (Only B-tree indexes are supported.) Value range: –31 to 31. The default value is **0**. * **COMPRESS\_CHUNK\_SIZE** Specifies the size of an index compression chunk. A smaller chunk size indicates a better compression effect, and a larger data dispersion degree indicates a slower index access speed. This parameter cannot be modified after it takes effect. (Only B-tree indexes are supported.) Value range: subject to the page size. When the page size is 8 KB, the value can be **512**, **1024**, **2048**, or **4096**. Default value: **4096** * **COMPRESS\_PREALLOC\_CHUNKS** Specifies the number of pre-allocated index compression chunks. A larger number of pre-allocated chunks indicates a lower index compression ratio, and a smaller data dispersion degree indicates a better access performance. (Only B-tree indexes are supported.) Value range: 0 to 7. The default value is **0**. * The maximum value of this parameter is **7** when **COMPRESS\_CHUNK\_SIZE** is set to **512** or **1024**. * The maximum value of this parameter is **3** when **COMPRESS\_CHUNK\_SIZE** is set to **2048**. * The maximum value of this parameter is **1** when **COMPRESS\_CHUNK\_SIZE** is set to **4096**. * **COMPRESS\_BYTE\_CONVERT** Sets the preprocessing of index compression byte conversion. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * **COMPRESS\_DIFF\_CONVERT** Sets the pre-processing of index compression differentiation. This parameter can be used together only with **COMPRESS\_BYTE\_CONVERT**. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. ## Examples ``` -- Create the tpcds.ship_mode_t1 table. openGauss=# create schema tpcds; openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) ; -- Create a common unique index on the SM_SHIP_MODE_SK column in the tpcds.ship_mode_t1 table. openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index1 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK); -- Create a B-tree index on the SM_SHIP_MODE_SK column in the tpcds.ship_mode_t1 table. openGauss=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree(SM_SHIP_MODE_SK); -- Create an expression index on the SM_CODE column in the tpcds.ship_mode_t1 table: openGauss=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1(SUBSTR(SM_CODE,1 ,4)); -- Create a partial index on the SM_SHIP_MODE_SK column where SM_SHIP_MODE_SK is greater than 10 in the tpcds.ship_mode_t1 table. openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) WHERE SM_SHIP_MODE_SK>10; -- Rename an existing index. openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5; -- Set the index as unusable. openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE; -- Rebuild an index. openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD; -- Delete an existing index. openGauss=# DROP INDEX tpcds.ds_ship_mode_t1_index2; -- Delete the table. openGauss=# DROP TABLE tpcds.ship_mode_t1; -- Create a tablespace. openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; -- Create the tpcds.customer_address_p1 table. openGauss=# CREATE TABLE tpcds.customer_address_p1 ( CA_ADDRESS_SK INTEGER NOT NULL, CA_ADDRESS_ID CHAR(16) NOT NULL, CA_STREET_NUMBER CHAR(10) , CA_STREET_NAME VARCHAR(60) , CA_STREET_TYPE CHAR(15) , CA_SUITE_NUMBER CHAR(10) , CA_CITY VARCHAR(60) , CA_COUNTY VARCHAR(30) , CA_STATE CHAR(2) , CA_ZIP CHAR(10) , CA_COUNTRY VARCHAR(20) , CA_GMT_OFFSET DECIMAL(5,2) , CA_LOCATION_TYPE CHAR(20) ) TABLESPACE example1 PARTITION BY RANGE(CA_ADDRESS_SK) ( PARTITION p1 VALUES LESS THAN (3000), PARTITION p2 VALUES LESS THAN (5000) TABLESPACE example1, PARTITION p3 VALUES LESS THAN (MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; -- Create the partitioned table index ds_customer_address_p1_index1 without specifying the index partition name. openGauss=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL; -- Create the partitioned table index ds_customer_address_p1_index2 with the name of the index partition specified. openGauss=# CREATE INDEX ds_customer_address_p1_index2 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL ( PARTITION CA_ADDRESS_SK_index1, PARTITION CA_ADDRESS_SK_index2 TABLESPACE example3, PARTITION CA_ADDRESS_SK_index3 TABLESPACE example4 ) TABLESPACE example2; -- Create a GLOBAL partitioned index. openGauss=CREATE INDEX ds_customer_address_p1_index3 ON tpcds.customer_address_p1(CA_ADDRESS_ID) GLOBAL; -- If no keyword is specified, a GLOBAL partitioned index is created by default. openGauss=CREATE INDEX ds_customer_address_p1_index4 ON tpcds.customer_address_p1(CA_ADDRESS_ID); -- Change the tablespace of the partitioned table index CA_ADDRESS_SK_index2 to example1. openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1; -- Change the tablespace of the partitioned table index CA_ADDRESS_SK_index3 to example2. openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2; -- Rename a partitioned table index. openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4; -- Delete the created indexes and the partitioned table. openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index1; openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index2; openGauss=# DROP TABLE tpcds.customer_address_p1; -- Delete the tablespace. openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; -- Create a column-store table and its GIN index: openGauss=# create table cgin_create_test(a int, b text) with (orientation = column); CREATE TABLE openGauss=# create index cgin_test on cgin_create_test using gin(to_tsvector('ngram', b)); CREATE INDEX ``` ## Helpful Links [ALTER INDEX](alter_index.md) and [DROP INDEX](drop_index.md) ## Suggestions * create index You are advised to create indexes on: * Columns that are often queried * Join conditions. For a query on joined columns, you are advised to create a composite index on the columns, For example, for **select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b**, you can create a composite index on columns **a** and **b** in table **t1**. * Columns having filter criteria (especially scope criteria) of a **where** clause * Columns that appear after **order by**, **group by**, and **distinct** Constraints: * Partial indexes cannot be created in a partitioned table. * When a GLOBAL index is created on a partitioned table, the following constraints apply: * Expression indexes and partial indexes are not supported. * Row-store tables are not supported. * Only B-tree indexes are supported. * In the same attribute column, the LOCAL index and GLOBAL index of a partition cannot coexist. * GLOBAL index supports a maximum of 31 columns. * If the **ALTER** statement does not contain **UPDATE GLOBAL INDEX**, the original GLOBAL index is invalid. In this case, other indexes are used for query. If the ALTER statement contains UPDATE GLOBAL INDEX, the original GLOBAL index is still valid and the index function is correct. --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-create-index.md --- # CREATE INDEX ## Function **CREATE INDEX** creates an index in a specified table. Indexes are primarily used to enhance database performance (though inappropriate use can result in slower database performance). You are advised to create indexes on: * Columns that are often queried * Join conditions. For a query on joined columns, you are advised to create a composite index on the columns. For example, select \* from t1 join t2 on t1. a=t2. a and t1. b=t2.b. You can create a composite index on the a and b columns of table t1. * Columns having filter criteria (especially scope criteria) of a **where** clause * Columns that appear after **order by**, **group by**, and **distinct** The partitioned table does not support concurrent index creation and partial index creation. ## Precautions * This section describes only the new syntax of Dolphin. The original syntax of openGauss is not deleted or modified. Options can be sorted in random order. ## Syntax * Create an index on a table. ``` CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [schema_name.]index_name ] { ON table_name [ USING method ] | [ USING method ] ON table_name } ({ { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ index_option ] [ WHERE predicate ]; ``` * Create an index on a partitioned table. ``` CREATE [ UNIQUE ] INDEX [ [schema_name.]index_name ] { ON table_name [ USING method ] | [ USING method ] ON table_name } ( {{ column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ index_option ] ``` ## Parameter Description * **column\_name ( length )** Creates a prefix key index based on a column in the table. **column\_name** indicates the column name of the prefix key, and **length** indicates the prefix length. The prefix key uses the prefix of the specified column data as the index key value, which reduces the storage space occupied by the index. Indexes can be used for filter and join conditions that contain prefix key columns. > \[!NOTE]NOTE > > * The prefix key supports the following index methods: btree and ubtree. > * The data type of the prefix key column must be binary or character (excluding special characters). > * The prefix length must be a positive integer that does not exceed 2676 and cannot exceed the maximum length of the column. For the binary type, the prefix length is measured in bytes. For non-binary character types, the prefix length is measured in characters. The actual length of the key value is restricted by the internal page. If a column contains multi-byte characters or an index has multiple keys, the length of the index line may exceed the upper limit. As a result, an error is reported. Consider this situation when setting a long prefix length. > * In the CREATE INDEX syntax, the following keywords cannot be used as prefix keys for column names: COALESCE, CONVERT, DAYOFMONTH, DAYOFWEEK, DAYOFYEAR, DB\_B\_FORMAT, EXTRACT, GREATEST, HOUR\_P, IFNULL, LEAST, LOCATE, MICROSECOND\_P, MID, MINUTE\_P, NULLIF, NVARCHAR, NVL, OVERLAY, POSITION, QUARTER, SECOND\_P, SUBSTR, SUBSTRING, TEXT\_P, TIME, TIMESTAMP, TIMESTAMPDIFF, TREAT, TRIM, WEEKDAY, WEEKOFYEAR, XMLCONCAT, XMLELEMENT, XMLEXISTS, XMLFOREST, XMLPARSE, XMLPI, XMLROOT, and XMLSERIALIZE. If the index where the prefix key containing the preceding keywords resides is created using the ALTER TABLE or CREATE TABLE syntax, the exported CREATE INDEX statement may fail to be executed. Therefore, do not use the preceding keywords as the column names of the prefix keys. * **index\_option** You can specify options when creating an index. The syntax is as follows: ``` INCLUDE ( column_name [, ...] ) | WITH ( { storage_parameter = value } [, ...] ) | TABLESPACE tablespace_name ``` The TABLESPACE option can be entered multiple times. The latest input prevails. ## Examples ``` --Create a table named tpcds.ship_mode_t1. openGauss=# create schema tpcds; openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) ; --Create a common unique index on the SM_SHIP_MODE_SK column in the tpcds.ship_mode_t1 table. openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index1 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK); --Create a B-tree index on the SM_SHIP_MODE_SK column in the tpcds.ship_mode_t1 table. openGauss=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree(SM_SHIP_MODE_SK); --Create an expression index on the SM_CODE column in the table tpcds.ship_mode_t1 table. openGauss=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1(SUBSTR(SM_CODE,1 ,4)); --Create a partial index on the SM_SHIP_MODE_SK column where SM_SHIP_MODE_SK is greater than 10 in the tpcds.ship_mode_t1 table. openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) WHERE SM_SHIP_MODE_SK>10; --Rename an existing index. openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5; --Set the index to be unavailable. openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE; --Recreate an index. openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD; --Delete an existing index. openGauss=# DROP INDEX tpcds.ds_ship_mode_t1_index2; --Delete a table. openGauss=# DROP TABLE tpcds.ship_mode_t1; --Create a tablespace. openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; --Create a table named tpcds.customer_address_p1. openGauss=# CREATE TABLE tpcds.customer_address_p1 ( CA_ADDRESS_SK INTEGER NOT NULL, CA_ADDRESS_ID CHAR(16) NOT NULL, CA_STREET_NUMBER CHAR(10) , CA_STREET_NAME VARCHAR(60) , CA_STREET_TYPE CHAR(15) , CA_SUITE_NUMBER CHAR(10) , CA_CITY VARCHAR(60) , CA_COUNTY VARCHAR(30) , CA_STATE CHAR(2) , CA_ZIP CHAR(10) , CA_COUNTRY VARCHAR(20) , CA_GMT_OFFSET DECIMAL(5,2) , CA_LOCATION_TYPE CHAR(20) ) TABLESPACE example1 PARTITION BY RANGE(CA_ADDRESS_SK) ( PARTITION p1 VALUES LESS THAN (3000), PARTITION p2 VALUES LESS THAN (5000) TABLESPACE example1, PARTITION p3 VALUES LESS THAN (MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --Create the partitioned table index ds_customer_address_p1_index1 without specifying the index partition name. openGauss=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL; --Create the partitioned table index ds_customer_address_p1_index2 with the name of the index partition specified. openGauss=# CREATE INDEX ds_customer_address_p1_index2 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL ( PARTITION CA_ADDRESS_SK_index1, PARTITION CA_ADDRESS_SK_index2 TABLESPACE example3, PARTITION CA_ADDRESS_SK_index3 TABLESPACE example4 ) TABLESPACE example2; --Create a global partitioned index. openGauss=CREATE INDEX ds_customer_address_p1_index3 ON tpcds.customer_address_p1(CA_ADDRESS_ID) GLOBAL; --If no keyword is specified, a global partitioned index is created by default. openGauss=CREATE INDEX ds_customer_address_p1_index4 ON tpcds.customer_address_p1(CA_ADDRESS_ID); --Change the tablespace of the partitioned table index CA_ADDRESS_SK_index2 to example1. openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1; --Change the tablespace of the partitioned table index CA_ADDRESS_SK_index3 to example2. openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2; --Rename a partitioned table index. openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4; --Delete the created indexes and the partition table. openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index1; openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index2; openGauss=# DROP TABLE tpcds.customer_address_p1; --Delete a tablespace. openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; --Create a column-store table and its GIN index. openGauss=# create table cgin_create_test(a int, b text) with (orientation = column); CREATE TABLE openGauss=# create index cgin_test on cgin_create_test using gin(to_tsvector('ngram', b)); CREATE INDEX ``` ## Helpful Links [CREATE INDEX](https://docs.opengauss.org/en/docs/latest/sql_reference/create_index.html) --- --- url: /en/docs/latest/sql_reference/create_index.md --- # CREATE INDEX ## Function **CREATE INDEX-bak** defines a new index. Indexes are primarily used to enhance database performance (though inappropriate use can result in database performance deterioration). You are advised to create indexes on: * Columns that are often queried * Join conditions. For a query on joined columns, you are advised to create a composite index on the columns, For example, for **select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b**, you can create a composite index on columns **a** and **b** in table **t1**. * Columns having filter criteria (especially scope criteria) of a **where** clause * Columns that appear after **order by**, **group by**, and **distinct** The partitioned table does not support partial index creation. ## Precautions * Indexes consume storage and computing resources. Creating too many indexes has negative impact on database performance (especially the performance of data import. Therefore, you are advised to import the data before creating indexes). Therefore, create indexes only when they are necessary. * All functions and operators used in an index definition must be immutable, that is, their results must depend only on their parameters and never on any outside influence (such as the contents of another table or the current time). This restriction ensures that the behavior of the index is well-defined. To use a customized function in an index expression or **WHERE** clause, remember to mark the function **immutable** when you create it. * Partitioned table indexes are classified into LOCAL indexes and GLOBAL indexes. A LOCAL index binds to a specific partition, and a GLOBAL index corresponds to the entire partitioned table. * If the two indexes are used, you cannot create expression and partial indexes. If the PSORT index is used, you cannot create unique indexes. If the B-tree index is used, you can create unique indexes. * Column-store tables support GIN indexes, rather than partial indexes and unique indexes. If GIN indexes are used, you can create expression indexes. However, an expression in this situation cannot contain empty splitters, empty columns, or multiple columns. * Currently, only row-store table indexes, temporary table indexes, and local indexes of partitioned tables can be used as hash indexes. Multi-column indexes are not supported. * A user granted with the **CREATE ANY INDEX** permission can create indexes in both the public and user schemas. ## Syntax * Create an index on a table. ``` CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [schema_name.]index_name ] ON table_name [ USING method ] ({ { column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ INCLUDE ( column_name [, ...] )] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ COMMENT text ] [ WHERE predicate ]; ``` * Create an index on a partitioned table. ``` CREATE [ UNIQUE ] INDEX [ [schema_name.]index_name ] ON table_name [ USING method ] ( {{ column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name | SUBPARTITION index_subpartition_name [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ INCLUDE ( column_name [, ...] )] [ WITH ( { storage_parameter = value } [, ...] ) ] [ TABLESPACE tablespace_name ] [ WHERE predicate ]; ``` ## 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 entries will generate an error. Currently, only B-tree and UB-tree indexes support unique indexes. * **CONCURRENTLY** Create an index (with ShareUpdateExclusiveLock) in non-blocking DML mode. A normal **CREATE INDEX** acquires exclusive lock on the table on which the index depends, blocking other accesses until the index drop can be completed. If this keyword is specified, DML is not blocked during the creation. * This option can only specify a name of one index. * The **CREATE INDEX** statement can be run within a transaction, but **CREATE INDEX CONCURRENTLY** cannot. * Column-store tables, partitioned tables, and temporary tables do not support **CREATE INDEX CONCURRENTLY**. > \[!NOTE]NOTE > > * This keyword is specified when an index is created. The entire table needs to be scanned twice and built. When the table is scanned for the first time, an index is created and the read and write operations are not blocked. During the second scan, changes that have occurred since the first scan are merged and updated. > * The table needs to be scanned and built twice, and all existing transactions that may modify the table must be completed. This means that the creation of the index takes a longer time than normal. In addition, the CPU and I/O consumption also affects other services. > * If an index build fails, it leaves an "unusable" index. This index is ignored by the query, but it still consumes the update overhead. In this case, you are advised to delete the index and try **CREATE INDEX CONCURRENTLY** again. > * After the second scan, index creation must wait for any transaction that holds a snapshot earlier than the snapshot taken by the second scan to terminate. In addition, the ShareUpdateExclusiveLock (level 4) added during index creation conflicts with a lock whose level is greater than or equal to 4. Therefore, when such an index is created, the system is prone to hang or deadlock. For example: > * If two sessions create an index concurrently for the same table, a deadlock occurs. > * If a session creates an index concurrently for a table and another session drops a table, a deadlock occurs. > * There are three sessions. Session 1 locks table **a** and does not commit it. Session 2 creates an index concurrently for table **b**. Session 3 writes data to table **a**. Before the transaction of session 1 is committed, session 2 is blocked. > * The transaction isolation level is set to repeatable read (read committed by default). Two sessions are started. Session 1 writes data to table **a** and does not commit it. Session 2 creates an index concurrently for table **b**. Before the transaction of session 1 is committed, session 2 is blocked. * **schema\_name** Specifies the schema name. Value range: an existing schema name * **index\_name** Specifies the name of the index to be created. The schema of the index is the same as that of the table. Value range: a string. It must comply with the identifier naming convention. * **table\_name** Specifies the name of the table to be indexed (optionally schema-qualified). Value range: an existing table name * **USING method** Specifies the name of the index method to be used. Value range: * **btree**: B-tree indexes store key values of data in a B+ tree structure. This structure helps users to quickly search for indexes. B-tree indexes support comparison queries with ranges specified. * **hash**: Hash indexes use hash functions to hash index keywords. Only simple equivalence comparison can be processed. This value is applicable to scenarios where index values are long. * **gin**: GIN indexes are reverse indexes and can process values that contain multiple keys (for example, arrays). * **gist**: GiST indexes are suitable for the set data type and multidimensional data types, such as geometric and geographic data types. The following data types are supported: box, point, poly, circle, tsvector, tsquery, and range. * **Psort**: psort index. It is used to perform partial sort on column-store tables. * **ubtree**: Multi-version B-tree index used only for Ustore tables. The index page contains transaction information and can be recycled. By default, the INSERTPT function is enabled for UBtree indexes. Row-store tables (Astore storage engine) support the following index types: **btree** (default), **hash**, **gin**, and **gist**. Row-store tables (Ustore storage engine) support the following index type: **ubtree**. Column-store tables support the following index types: **Psort** (default), **btree**, and **gin**. Global temporary tables do not support GIN and GiST indexes. > \[!NOTE]NOTE > > Column-store tables support GIN indexes only for the tsvector type. That is, the input parameter for creating a column-store GIN index must be the return value of the **to\_tsvector** function. This method is commonly used for GIN indexes. * **column\_name** Specifies the name of the column on which an index is to be created. Multiple columns can be specified if the index method supports multi-column indexes. A global index supports a maximum of 31 columns, and other indexes support a maximum of 32 columns. * **column\_name ( length )** Creates a prefix key index based on a column in the table. **column\_name** indicates the column name of the prefix key, and **length** indicates the prefix length. The prefix key uses the prefix of the specified column data as the index key value, which reduces the storage space occupied by the index. Indexes can be used for filter and join conditions that contain prefix key columns. > \[!NOTE]NOTE > > * This syntax is valid only when **sql\_compatibility** is set to **B**. If **sql\_compatibility** is set to other values, this clause is regarded as the function expression key. > * The prefix key supports the following index methods: btree and ubtree. > * The data type of the prefix key column must be binary or character (excluding special characters). > * The prefix length must be a positive integer that does not exceed 2676 and cannot exceed the maximum length of the column. For the binary type, the prefix length is measured in bytes. For non-binary character types, the prefix length is measured in characters. The actual length of the key value is restricted by the internal page. If a column contains multi-byte characters or an index has multiple keys, the length of the index line may exceed the upper limit. As a result, an error is reported. Consider this situation when setting a long prefix length. > * In the CREATE INDEX syntax, the following keywords cannot be used as prefix keys for column names: COALESCE, EXTRACT, GREATEST, LEAST, NULLIF, NVARCHAR, NVL, OVERLAY, POSITION, SUBSTRING, TIMESTAMPDIFF, TREAT, TRIM, XMLCONCAT, XMLELEMENT, XMLEXISTS, XMLFOREST, XMLPARSE, XMLPI, XMLROOT, and XMLSERIALIZE. * **expression** Specifies an expression based on one or more columns of the table. The expression usually must be written with surrounding parentheses, as shown in the syntax. However, the parentheses can be omitted if the expression has the form of a function call. Expression can be used to obtain fast access to data based on some transformation of the basic data. For example, an index computed on **upper(col)** would allow the clause **WHERE upper(col) = 'JIM'** to use an index. If an expression contains **IS NULL**, the index for this expression is invalid. In this case, you are advised to create a partial index. * **COLLATE collation** Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the **select \* from pg\_collation** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **opclass** Specifies the name of an operator class. An operator class can be specified for each column of an index. The operator class identifies the operators to be used by the index for that column. For example, a B-tree index on the type int4 would use the **int4\_ops** class; this operator class includes comparison functions for values of type int4. In practice, the default operator class for the column's data type is sufficient. The operator class applies to data with multiple sorts. For example, users might want to sort a complex-number data type either by absolute value or by real part. They could do this by defining two operator classes for the data type and then selecting the proper class when making an index. * **ASC** Specifies an ascending (default) sort order. * **DESC** Specifies a descending sort order. * **NULLS FIRST** Specifies that null values appear before non-null values in the sort ordering. This is the default when **DESC** is specified. * **NULLS LAST** Specifies that null values appear after non-null values in the sort ordering. This is the default when **DESC** is not specified. * **LOCAL** Specifies that the partitioned index to be created is a LOCAL index. * **GLOBAL** Specifies the partitioned index to be created as a GLOBAL index. If no keyword is specified, a GLOBAL index is created by default. * **INCLUDE ( column\_name \[, ...]** ) The optional **INCLUDE** clause specifies that some non-key columns are included in indexes. Non-key columns cannot be used as search criteria for accelerating index scans, and they are omitted when the unique constraints of the indexes are checked. An index-only scan can directly return content in the non-key columns without accessing the heap table corresponding to the indexes. Exercise caution when adding non-key columns as **INCLUDE** columns, especially for wide columns. If the size of an index tuple exceeds the maximum size allowed by the index type, data insertion fails. Note that in any case, adding non-key columns to an index increases the space occupied by the index, which may slow down the search speed. Currently, only UBtree indexes access mode supports this feature. Non-key columns are stored in the index leaf tuple corresponding to the heap tuple and are not included in the tuple on the upper-layer index page. * **WITH ( {storage\_parameter = value} \[, ... ] )** Specifies the storage parameter used for an index. Value range: Only index GIN supports parameters **FASTUPDATE** and **GIN\_PENDING\_LIST\_LIMIT**. Indexes other than GIN and psort support the **FILLFACTOR** parameter. Only UBtree indexes support **INDEXSPLIT** and **INDEX\_TYPE**. * FILLFACTOR The fill factor of an index is a percentage from 10 to 100. Value range: 10–100 * FASTUPDATE Specifies whether fast update is enabled for the GIN index. Value range: : **ON** and **OFF** Default value: **ON** * GIN\_PENDING\_LIST\_LIMIT Specifies the maximum capacity of the pending list of the GIN index when fast update is enabled for the GIN index. Value range: 64–\*INT\*MAX\_. The unit is KB. Default value: The default value of **gin\_pending\_list\_limit** depends on **gin\_pending\_list\_limit** specified in GUC parameters. By default, the value is **4**. * INDEXSPLIT Specifies the splitting policy of UBtree indexes. The **DEFAULT** policy is the same as the splitting policy of UBtree indexes. The **INSERTPT** policy can significantly reduce the index space usage in some scenarios. Value range: **INSERTPT** and **DEFAULT** Default value: **INSERTPT** * INDEX\_TYPE Specifies the type of UBTREE index. RCR index is based on Row Consistency Read. PCR index is based on Page Consistency Read. This parameter cannot be modified after it takes effect. Value range: **RCR** and **PCR** Default value: **RCR** * **TABLESPACE tablespace\_name** Specifies the tablespace for an index. If no tablespace is specified, the default tablespace is used. Value range: an existing table name * **COMMENT text** Specifies the comment of an index. If no comment is specified, the comment is empty. * **WHERE predicate** Creates a partial index. A partial index is an index that contains entries for only a portion of a table, usually a portion that is more useful for indexing than the rest of the table. For example, if you have a table that contains both billed and unbilled orders where the unbilled orders take up a small fraction of the total table and yet that is an often used portion, you can improve performance by creating an index on just that portion. In addition, **WHERE** with **UNIQUE** can be used to enforce uniqueness over a subset for a table. Value range: The **predicate** expression can only refer to columns of the underlying table, but it can use all columns, not just the ones being indexed. Currently, subqueries and aggregate expressions are forbidden in **WHERE**. You are not advised to use numeric types such as int for **predicate**, because such types can be implicitly converted to bool values (non-zero values are implicitly converted to **true** and **0** is implicitly converted to **false**), which may cause unexpected results. For a partitioned table index, if the created index contains the GLOBAL or LOCAL keyword or the created index is a GLOBAL index, the WHERE clause cannot be used to create an index. * **PARTITION index\_partition\_name** Specifies the name of an index partition. Value range: a string. It must comply with the identifier naming convention. * **SUBPARTITION index\_subpartition\_name** Specifies the name of an level-2 index partition. Value range: a string. It must comply with the identifier naming convention. * **TABLESPACE index\_partition\_tablespace** Specifies the tablespace of an index partition. Value range: If this parameter is not specified, the value of **index\_tablespace** is used. * **COMPRESSTYPE** Sets the index compression algorithm. The value **1** indicates the PGLZ algorithm, the value **2** indicates the ZSTD algorithm, the value **3** indicates the PGZSTD algorithm (currently not supported), and the value **4** indicates the ZLIB algorithm. By default, indexes are not compressed. This parameter cannot be modified after it takes effect. (Only B-tree indexes are supported.) Value range: 0 to 4. The default value is **0**. * **COMPRESS\_LEVEL** Sets the index compression algorithm level. This parameter is valid only when **COMPRESSTYPE** is set to **2** or **4**. A higher compression level indicates a better index compression effect and a slower index access speed. This parameter can be modified. The modification affects the compression level of changed data and new data. (Only B-tree indexes are supported.) Value range: –31 to 31. The default value is **0**. * **COMPRESS\_CHUNK\_SIZE** Specifies the size of an index compression chunk. A smaller chunk size indicates a better compression effect, and a larger data dispersion degree indicates a slower index access speed. This parameter cannot be modified after it takes effect. (Only B-tree indexes are supported.) Value range: subject to the page size. When the page size is 8 KB, the value can be **512**, **1024**, **2048**, or **4096**. Default value: **4096** * **COMPRESS\_PREALLOC\_CHUNKS** Specifies the number of pre-allocated index compression chunks. A larger number of pre-allocated chunks indicates a lower index compression ratio, and a smaller data dispersion degree indicates a better access performance. This parameter can be modified. The modification affects the number of pre-allocated changed data and new data. (Only B-tree indexes are supported.) Value range: 0 to 7. The default value is **0**. * The maximum value of this parameter is **7** when **COMPRESS\_CHUNK\_SIZE** is set to **512** or **1024**. * The maximum value of this parameter is **3** when **COMPRESS\_CHUNK\_SIZE** is set to **2048**. * The maximum value of this parameter is **1** when **COMPRESS\_CHUNK\_SIZE** is set to **4096**. * **COMPRESS\_BYTE\_CONVERT** Sets the preprocessing of index compression byte conversion. In some scenarios, the compression effect can be improved, but the performance deteriorates. This parameter can be modified. The modification determines whether to perform byte conversion preprocessing for changed data and new data. This parameter cannot be set to **false** if `COMPRESS_DIFF_CONVERT` is set to **true**. Value range: Boolean value. By default, this function is disabled. * **COMPRESS\_DIFF\_CONVERT** Sets the pre-processing of index compression differentiation. This parameter can be used together only with **COMPRESS\_BYTE\_CONVERT**. In some scenarios, the compression effect can be improved, but the performance deteriorates. This parameter can be modified. The modification determines whether to perform byte differentiation preprocessing for changed data and new data. Value range: Boolean value. By default, this function is disabled. ## Examples ``` -- Create the tpcds.ship_mode_t1 table. openGauss=# create schema tpcds; openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) ; -- Create a common unique index on the SM_SHIP_MODE_SK column in the tpcds.ship_mode_t1 table. openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index1 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK); -- Create a B-tree index on the SM_SHIP_MODE_SK column in the tpcds.ship_mode_t1 table. openGauss=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree(SM_SHIP_MODE_SK); -- Create an expression index on the SM_CODE column in the tpcds.ship_mode_t1 table: openGauss=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1(SUBSTR(SM_CODE,1 ,4)); -- Create a partial index on the SM_SHIP_MODE_SK column where SM_SHIP_MODE_SK is greater than 10 in the tpcds.ship_mode_t1 table. openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) WHERE SM_SHIP_MODE_SK>10; -- Rename an existing index. openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5; -- Set the index as unusable. openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE; -- Rebuild an index. openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD; -- Delete an existing index. openGauss=# DROP INDEX tpcds.ds_ship_mode_t1_index2; -- Delete the table. openGauss=# DROP TABLE tpcds.ship_mode_t1; -- Create a tablespace. openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; -- Create the tpcds.customer_address_p1 table. openGauss=# CREATE TABLE tpcds.customer_address_p1 ( CA_ADDRESS_SK INTEGER NOT NULL, CA_ADDRESS_ID CHAR(16) NOT NULL, CA_STREET_NUMBER CHAR(10) , CA_STREET_NAME VARCHAR(60) , CA_STREET_TYPE CHAR(15) , CA_SUITE_NUMBER CHAR(10) , CA_CITY VARCHAR(60) , CA_COUNTY VARCHAR(30) , CA_STATE CHAR(2) , CA_ZIP CHAR(10) , CA_COUNTRY VARCHAR(20) , CA_GMT_OFFSET DECIMAL(5,2) , CA_LOCATION_TYPE CHAR(20) ) TABLESPACE example1 PARTITION BY RANGE(CA_ADDRESS_SK) ( PARTITION p1 VALUES LESS THAN (3000), PARTITION p2 VALUES LESS THAN (5000) TABLESPACE example1, PARTITION p3 VALUES LESS THAN (MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; -- Create the partitioned table index ds_customer_address_p1_index1 without specifying the index partition name. openGauss=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL; -- Create the partitioned table index ds_customer_address_p1_index2 with the name of the index partition specified. openGauss=# CREATE INDEX ds_customer_address_p1_index2 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL ( PARTITION CA_ADDRESS_SK_index1, PARTITION CA_ADDRESS_SK_index2 TABLESPACE example3, PARTITION CA_ADDRESS_SK_index3 TABLESPACE example4 ) TABLESPACE example2; -- Create a GLOBAL partitioned index. openGauss=CREATE INDEX ds_customer_address_p1_index3 ON tpcds.customer_address_p1(CA_ADDRESS_ID) GLOBAL; -- If no keyword is specified, a GLOBAL partitioned index is created by default. openGauss=CREATE INDEX ds_customer_address_p1_index4 ON tpcds.customer_address_p1(CA_ADDRESS_ID); -- Change the tablespace of the partitioned table index CA_ADDRESS_SK_index2 to example1. openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1; -- Change the tablespace of the partitioned table index CA_ADDRESS_SK_index3 to example2. openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2; -- Rename a partitioned table index. openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4; -- Delete the created indexes and the partitioned table. openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index1; openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index2; openGauss=# DROP TABLE tpcds.customer_address_p1; -- Delete the tablespace. openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; -- Create a column-store table and its GIN index: openGauss=# create table cgin_create_test(a int, b text) with (orientation = column); CREATE TABLE openGauss=# create index cgin_test on cgin_create_test using gin(to_tsvector('ngram', b)); CREATE INDEX ``` ## Helpful Links [ALTER INDEX](alter_index.md) and [DROP INDEX](drop_index.md) ## Suggestions * create index You are advised to create indexes on: * Columns that are often queried * Join conditions. For a query on joined columns, you are advised to create a composite index on the columns, For example, for **select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b**, you can create a composite index on columns **a** and **b** in table **t1**. * Columns having filter criteria (especially scope criteria) of a **where** clause * Columns that appear after **order by**, **group by**, and **distinct** Constraints: * Partial indexes cannot be created in a partitioned table. * When a GLOBAL index is created on a partitioned table, the following constraints apply: * Expression indexes and partial indexes are not supported. * Row-store tables are not supported. * Only B-tree indexes are supported. * In the same attribute column, the LOCAL index and GLOBAL index of a partition cannot coexist. * GLOBAL index supports a maximum of 31 columns. * If the **ALTER** statement does not contain **UPDATE GLOBAL INDEX**, the original GLOBAL index is invalid. In this case, other indexes are used for query. If the ALTER statement contains UPDATE GLOBAL INDEX, the original GLOBAL index is still valid and the index function is correct. --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CREATE-INDEX.md --- # CREATE INDEX ## 功能描述 在指定的表上创建索引。 索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议仅在匹配如下某条原则时创建索引: * 经常执行查询的字段。 * 在连接条件上创建索引,对于存在多字段连接的查询,建议在这些字段上建立组合索引。例如,select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b,可以在t1表上的a、b字段上建立组合索引。 * where子句的过滤条件字段上(尤其是范围条件)。 * 在经常出现在order by、group by和distinct后的字段。 在分区表上创建索引与在普通表上创建索引的语法不太一样,使用时请注意,如分区表上不支持并行创建索引,不支持创建部分索引。 新增可以指定 ALGORITHM 选项语法。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 * 新增支持option的无序排列。 * 原始openGauss中,索引名是schema级别唯一的,创建索引时如果索引名重复了会报错。在dolphin插件中,如果GUC参数`dolphin.b_compatibility_mode`为on,当索引名重复时,会自动生成一个不重复的索引名做替代,并告警提示。 * 如果GUC参数`dolphin.b_compatibility_mode`为on且`dolphin_nulls_minimal_policy`为on,创建索引默认为NULLS FIRST索引。如果是倒序索引,索引默认为NULLS LAST,以便兼容null值为最小值的表现行为。 ## 语法格式 * 在表上创建索引。 ``` CREATE [ UNIQUE | FULLTEXT ] INDEX [ CONCURRENTLY ] [ [schema_name.]index_name ] { ON table_name [ USING method ] | [ USING method ] ON table_name } ({ { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ index_option ] [ WHERE predicate | ALGORITHM [=] {DEFAULT | INPLACE | COPY} ]; ``` ``` CREATE [UNIQUE] INDEX index_name ON tbl_name (key_part,...) [USING {BTREE | HASH}] ``` * 在分区表上创建索引。 ``` CREATE [ UNIQUE ] INDEX [ [schema_name.]index_name ] { ON table_name [ USING method ] | [ USING method ] ON table_name } ( {{ column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name [ ( SUBPARTITION index_subpartition_name [, ...] ) ] [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ index_option ] [ALGORITHM [=] {DEFAULT | INPLACE | COPY} ] ``` ## 参数说明 * **FULLTEXT** 该关键字为创建兼容MySQL的全文索引的语法。该全文索引主要用于字符串的搜索匹配。包含局部匹配搜索,支持中文,韩文,日文。与MATCH () AGAINST ()配合使用。 * **column\_name ( length )** 创建一个基于该表一个字段的前缀键索引,column\_name为前缀键的字段名,length为前缀长度。 前缀键将取指定字段数据的前缀作为索引键值,可以减少索引占用的存储空间。含有前缀键字段的过滤条件和连接条件可以使用索引。 > \[!NOTE]说明 > > * 前缀键支持的索引方法:Btree、UBtree。 > * 前缀键的字段的数据类型必须是二进制类型或字符类型(不包括特殊字符类型)。 > * 前缀长度必须是不超过2676的正整数,并且不能超过字段的最大长度。对于二进制类型,前缀长度以字节数为单位。对于非二进制字符类型,前缀长度以字符数为单位。键值的实际长度受内部页面限制,若字段中含有多字节字符、或者一个索引上有多个键,索引行长度可能会超限,导致报错,设定较长的前缀长度时请考虑此情况。 > * CREATE INDEX语法中,不支持以下关键字作为前缀键的字段名称:COALESCE、CONVERT、DAYOFMONTH、DAYOFWEEK、DAYOFYEAR、DB\_B\_FORMAT、EXTRACT、GREATEST、HOUR\_P、IFNULL、LEAST、LOCATE、MICROSECOND\_P、MID、MINUTE\_P、NULLIF、NVARCHAR、NVL、OVERLAY、POSITION、QUARTER、SECOND\_P、SUBSTR、SUBSTRING、TEXT\_P、TIME、TIMESTAMP、TIMESTAMPDIFF、TREAT、TRIM、WEEKDAY、WEEKOFYEAR、XMLCONCAT、XMLELEMENT、XMLEXISTS、XMLFOREST、XMLPARSE、XMLPI、XMLROOT、XMLSERIALIZE。若含有上述关键字的前缀键所在的索引是通过ALTER TABLE或CREATE TABLE语法创建的,导出的CREATE INDEX语句可能无法成功执行,请尽量不要使用上述关键字作为前缀键的列名称。 * **index\_option** 创建索引时可指定选项,其语法为: ``` INCLUDE ( column_name [, ...] ) | WITH ( { storage_parameter = value } [, ...] ) | TABLESPACE tablespace_name ``` 其中,TABLESPACE选项允许输入多次,以最后一次的输入为准。 * **ALGORITHM** 指定算法,可选项:DEFAULT、INPLACE、COPY。当前只做语法兼容,暂无实际功能。 ## 示例 ```sql --创建表tpcds.ship_mode_t1。 openGauss=# create schema tpcds; openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) ; --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建普通的唯一索引。 openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index1 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK); --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建指定B-tree索引。 openGauss=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree(SM_SHIP_MODE_SK); --在表tpcds.ship_mode_t1上SM_CODE字段上创建表达式索引。 openGauss=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1(SUBSTR(SM_CODE,1 ,4)); --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建SM_SHIP_MODE_SK大于10的部分索引。 openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) WHERE SM_SHIP_MODE_SK>10; --重命名一个现有的索引。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5; --设置索引不可用。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE; --重建索引。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD; --删除一个现有的索引。 openGauss=# DROP INDEX tpcds.ds_ship_mode_t1_index2; --删除表。 openGauss=# DROP TABLE tpcds.ship_mode_t1; --创建表空间。 openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; --创建表tpcds.customer_address_p1。 openGauss=# CREATE TABLE tpcds.customer_address_p1 ( CA_ADDRESS_SK INTEGER NOT NULL, CA_ADDRESS_ID CHAR(16) NOT NULL, CA_STREET_NUMBER CHAR(10) , CA_STREET_NAME VARCHAR(60) , CA_STREET_TYPE CHAR(15) , CA_SUITE_NUMBER CHAR(10) , CA_CITY VARCHAR(60) , CA_COUNTY VARCHAR(30) , CA_STATE CHAR(2) , CA_ZIP CHAR(10) , CA_COUNTRY VARCHAR(20) , CA_GMT_OFFSET DECIMAL(5,2) , CA_LOCATION_TYPE CHAR(20) ) TABLESPACE example1 PARTITION BY RANGE(CA_ADDRESS_SK) ( PARTITION p1 VALUES LESS THAN (3000), PARTITION p2 VALUES LESS THAN (5000) TABLESPACE example1, PARTITION p3 VALUES LESS THAN (MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --创建分区表索引ds_customer_address_p1_index1,不指定索引分区的名称。 openGauss=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL; --创建分区表索引ds_customer_address_p1_index2,并指定索引分区的名称。 openGauss=# CREATE INDEX ds_customer_address_p1_index2 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL ( PARTITION CA_ADDRESS_SK_index1, PARTITION CA_ADDRESS_SK_index2 TABLESPACE example3, PARTITION CA_ADDRESS_SK_index3 TABLESPACE example4 ) TABLESPACE example2; --创建GLOBAL分区索引 openGauss=CREATE INDEX ds_customer_address_p1_index3 ON tpcds.customer_address_p1(CA_ADDRESS_ID) GLOBAL; --不指定关键字,默认创建GLOBAL分区索引 openGauss=CREATE INDEX ds_customer_address_p1_index4 ON tpcds.customer_address_p1(CA_ADDRESS_ID); --修改分区表索引CA_ADDRESS_SK_index2的表空间为example1。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1; --修改分区表索引CA_ADDRESS_SK_index3的表空间为example2。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2; --重命名分区表索引。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4; --删除索引和分区表。 openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index1; openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index2; openGauss=# DROP TABLE tpcds.customer_address_p1; --删除表空间。 openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; --创建列存表以及列存表GIN索引。 openGauss=# create table cgin_create_test(a int, b text) with (orientation = column); CREATE TABLE openGauss=# create index cgin_test on cgin_create_test using gin(to_tsvector('ngram', b)); CREATE INDEX --索引名重复的场景,打开dolphin.b_compatibility_mode后,重复索引名将自动替换成其他不重复的名字 openGauss=# set dolphin.b_compatibility_mode to on; SET openGauss=# create table t1(id int,index idx_id(id)); CREATE TABLE openGauss=# create table t2(id int,index idx_id(id)); WARNING: index "idx_id" already exists, change index name to "t2_id_idx" CREATE TABLE ``` ## 全文索引 ```sql openGauss=# CREATE SCHEMA fulltext_test; CREATE SCHEMA openGauss=# set current_schema to 'fulltext_test'; SET openGauss=# CREATE TABLE test ( id int unsigned auto_increment not null primary key, title varchar, boby text, name name ); NOTICE: CREATE TABLE will create implicit sequence "test_id_seq" for serial column "test.id" NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_pkey" for table "test" CREATE TABLE openGauss=# \d test Table "fulltext_test.test" Column | Type | Modifiers --------+-------------------+------------------------- id | uint4 | not null AUTO_INCREMENT title | character varying | boby | text | name | name | Indexes: "test_pkey" PRIMARY KEY, btree (id) TABLESPACE pg_default openGauss=# CREATE FULLTEXT INDEX test_index_1 ON test (title, boby) WITH PARSER ngram; \d test_index_1 Index "fulltext_test.test_index_1" Column | Type | Definition --------------+------+------------------------------------------------ to_tsvector | text | to_tsvector('"ngram"'::regconfig, title::text) to_tsvector1 | text | to_tsvector('"ngram"'::regconfig, boby) gin, for table "fulltext_test.test" openGauss=# CREATE FULLTEXT INDEX test_index_2 ON test (title, boby, name); CREATE INDEX ``` ## 相关链接 [CREATE INDEX](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_index_1.html) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-CREATE-INDEX.md --- # CREATE INDEX ## 功能描述 在指定的表上创建索引。 索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议仅在匹配如下某条原则时创建索引: * 经常执行查询的字段。 * 在连接条件上创建索引,对于存在多字段连接的查询,建议在这些字段上建立组合索引。例如,select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b,可以在t1表上的a、b字段上建立组合索引。 * where子句的过滤条件字段上(尤其是范围条件)。 * 在经常出现在order by、group by和distinct后的字段。 在分区表上创建索引与在普通表上创建索引的语法不太一样,使用时请注意,如分区表上不支持并行创建索引,不支持创建部分索引。 新增可以指定 ALGORITHM 选项语法。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。 * 新增支持columnstore选项 ## 语法格式 * 在表上创建索引。 ``` CREATE [ UNIQUE ] [ opt_clustered ] [COLUMNSTORE] INDEX [ CONCURRENTLY ] [ [schema_name.]index_name ] ON table_name [ USING method ] ({ { column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ INCLUDE ( column_name [, ...] )] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ COMMENT text ] [ VISIBLE | INVISIBLE ] [ WHERE predicate ]; ``` ## 参数说明 * **COLUMNSTORE** 该关键字为创建兼容D库的语法,指定列存选项。仅语法作用,没有实际功能。 * **opt\_clustered** 参数内容为CLUSTERED/NONCLUSTERED,兼容D库的语法,指定创建聚合/非聚合索引。仅语法作用,没有实际功能。 ## 示例 ```sql openGauss=# create table t1 (a int); CREATE TABLE openGauss=# create columnstore index on t1 (a); NOTICE: The COLUMNSTORE option is currently ignored CREATE INDEX openGauss=# create table t1 (a int); CREATE TABLE openGauss=# create clustered index on t1 (a); NOTICE: The COLUMNSTORE option is currently ignored CREATE INDEX ``` ## 相关链接 [CREATE INDEX](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_index_1.html) --- --- url: /zh/docs/latest-lite/sql_reference/create_index_1.md --- # CREATE INDEX ## 功能描述 在指定的表上创建索引。 索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议仅在匹配如下某条原则时创建索引: * 经常执行查询的字段。 * 在连接条件上创建索引,对于存在多字段连接的查询,建议在这些字段上建立组合索引。例如,select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b,可以在t1表上的a,b字段上建立组合索引。 * where子句的过滤条件字段上(尤其是范围条件)。 * 在经常出现在order by、group by和distinct后的字段。 在分区表上创建索引与在普通表上创建索引的语法不太一样,使用时请注意,如不支持创建部分索引。 ## 注意事项 * 索引自身也占用存储空间、消耗计算资源,创建过多的索引将对数据库性能造成负面影响(尤其影响数据导入的性能,建议在数据导入后再建索引)。因此,仅在必要时创建索引。 * 索引定义里的所有函数和操作符都必须是immutable类型的,即它们的结果必须只能依赖于它们的输入参数,而不受任何外部的影响(如另外一个表的内容或者当前时间)。这个限制可以确保该索引的行为是定义良好的。要在一个索引上或WHERE中使用用户定义函数,请把它标记为immutable类型函数。 * 分区表索引分为LOCAL索引与GLOBAL索引,LOCAL索引与某个具体分区绑定,而GLOBAL索引则对应整个分区表。目前只有B-tree及UBtree索引支持GLOBAL索引。 * 列存表支持的PSORT和B-tree索引都不支持创建表达式索引、部分索引,PSORT不支持创建唯一索引,B-tree支持创建唯一索引。 * 列存表支持的GIN索引支持创建表达式索引,但表达式不能包含空分词、空列和多列,不支持创建部分索引和唯一索引。 * HASH索引目前仅限于行存表索引、临时表索引和分区表LOCAL索引,且不支持创建多字段索引。 * 被授予CREATE ANY INDEX权限的用户,可以在public模式和用户模式下创建索引。 * 如果表达式索引中调用的是用户自定义函数,按照函数创建者权限执行表达式索引函数。 * 仅支持在B兼容性数据库下指定COMMENT。 * 当前不支持在JSONB类型的数据上创建UBtree索引。 ## 语法格式 * 在表上创建索引。 ``` CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ IF NOT EXISTS ] [ [schema_name.]index_name ] ON table_name [ USING method ] ({ { column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ INCLUDE ( column_name [, ...] )] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ COMMENT text ] [ VISIBLE | INVISIBLE ] [ WHERE predicate ]; ``` * 在分区表上创建索引。 ``` CREATE [ UNIQUE ] INDEX [ IF NOT EXISTS ] [ [schema_name.]index_name ] ON table_name [ USING method ] ( {{ column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name [ ( SUBPARTITION index_subpartition_name [, ...] ) ] [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ INCLUDE ( column_name [, ...] )] [ WITH ( { storage_parameter = value } [, ...] ) ] [ TABLESPACE tablespace_name ] [ COMMENT text ] [ VISIBLE | INVISIBLE ] [ WHERE predicate ]; ``` ## 参数说明 * **UNIQUE** 创建唯一性索引,每次添加数据时检测表中是否有重复值。如果插入或更新的值会引起重复的记录时,将导致一个错误。 目前只有B-tree及UBTree索引支持唯一索引。 * **CONCURRENTLY** 以不阻塞DML的方式创建索引(加ShareUpdateExclusiveLock锁)。创建索引时,一般会阻塞其他语句对该索引所依赖表的访问。指定此关键字,可以实现创建过程中不阻塞DML。 * 此选项只能指定一个索引的名称。 * 普通CREATE INDEX命令可以在事务内执行,但是CREATE INDEX CONCURRENTLY不可以在事务内执行。 * 列存表、分区表和临时表不支持CONCURRENTLY方式创建索引。 > \[!NOTE]说明 > > * 创建索引时指定此关键字,需要执行先后两次对该表的全表扫描来完成build,第一次扫描的时候创建索引,不阻塞读写操作;第二次扫描的时候合并更新第一次扫描到目前为止发生的变更。 > * 由于需要执行两次对表的扫描和build,而且必须等待现有的所有可能对该表执行修改的事务结束。这意味着该索引的创建比正常耗时更长,同时因此带来的CPU和I/O消耗对其他业务也会造成影响。 > * 如果在索引构建时发生失败,那会留下一个“不可用”的索引。这个索引会被查询忽略,但它仍消耗更新开销。这种情况推荐的恢复方法是删除该索引并尝试再次CONCURRENTLY建索引。 > * 由于在第二次扫描之后,索引构建必须等待任何持有早于第二次扫描拿的快照的事务终止,而且建索引时加的ShareUpdateExclusiveLock锁(4级)会和大于等于4级的锁冲突,在创建这类索引时,容易引发卡住(hang)或者死锁问题。例如: > * 两个会话对同一个表创建CONCURRENTLY索引,会引起死锁问题; > * 两个会话,一个对表创建CONCURRENTLY索引,一个drop table,会引起死锁问题; > * 三个会话,会话1先对表a加锁,不提交,会话2接着对表b创建CONCURRENTLY索引,会话3接着对表a执行写入操作,在会话1事务未提交之前,会话2会一直被阻塞; > * 将事务隔离级别设置成可重复读(默认为读已提交),起两个会话,会话1起事务对表a执行写入操作,不提交,会话2对表b创建CONCURRENTLY索引,在会话1事务未提交之前,会话2会一直被阻塞。 * **schema\_name** 模式的名称。 取值范围:已存在模式名。 * **index\_name** 要创建的索引名,索引的模式与表相同。 取值范围:字符串,要符合标识符的命名规范。 * **table\_name** 需要为其创建索引的表的名称,可以用模式修饰。 取值范围:已存在的表名。 * **USING method** 指定创建索引的方法。 取值范围: * btree:B-tree索引使用一种类似于B+树的结构来存储数据的键值,通过这种结构能够快速的查找索引。btree适合支持比较查询以及查询范围。 * hash:Hash索引使用Hash函数对索引的关键字进行散列。只能处理简单等值比较,比较适合在索引值较长的情况下使用。 * gin:GIN索引是倒排索引,可以处理包含多个键的值(比如数组)。 * gist:Gist索引适用于几何和地理等多维数据类型和集合数据类型。目前支持的数据类型有box、point、poly、circle、tsvector、tsquery、range。 * Psort:Psort索引。针对列存表进行局部排序索引。 * ubtree:仅供Ustore表使用的多版本B-tree索引,索引页面上包含事务信息,能并自主回收页面。ubtree索引默认开启insertpt功能。 行存表(Astore存储引擎)支持的索引类型:btree(行存表缺省值)、hash、gin、gist。行存表(Ustore存储引擎)支持的索引类型:ubtree。列存表支持的索引类型:Psort(列存表缺省值)、btree、gin。全局临时表不支持GIN索引和Gist索引。 > \[!NOTE]说明 > > 列存表对GIN索引支持仅限于对于tsvector类型的支持,即创建列存GIN索引入参需要为to\_tsvector函数(的返回值)。此方法为GIN索引比较普遍的使用方式。 * **column\_name** 表中需要创建索引的列的名称(字段名)。 如果索引方式支持多字段索引,可以声明多个字段。全局索引最多可以声明31个字段,其他索引最多可以声明32个字段。 * **column\_name ( length )** 创建一个基于该表一个字段的前缀键索引,column\_name为前缀键的字段名,length为前缀长度。 前缀键将取指定字段数据的前缀作为索引键值,可以减少索引占用的存储空间。含有前缀键字段的过滤条件和连接条件可以使用索引。 > \[!NOTE]说明 > > * 此语法只在sql\_compatibility=B时有效,sql\_compatibility为其他值的情况下,此子句将被视作函数表达式键。 > * 前缀键支持的索引方法:btree、ubtree。 > * 前缀键的字段的数据类型必须是二进制类型或字符类型(不包括特殊字符类型)。 > * 前缀长度必须是不超过2676的正整数,并且不能超过字段的最大长度。对于二进制类型,前缀长度以字节数为单位。对于非二进制字符类型,前缀长度以字符数为单位。键值的实际长度受内部页面限制,若字段中含有多字节字符、或者一个索引上有多个键,索引行长度可能会超限,导致报错,设定较长的前缀长度时请考虑此情况。 > * CREATE INDEX语法中,不支持以下关键字作为前缀键的字段名称:COALESCE、EXTRACT、GREATEST、LEAST、NULLIF、NVARCHAR、NVL、OVERLAY、POSITION、SUBSTRING、TIMESTAMPDIFF、TREAT、TRIM、XMLCONCAT、XMLELEMENT、XMLEXISTS、XMLFOREST、XMLPARSE、XMLPI、XMLROOT、XMLSERIALIZE。 * **expression** 创建一个基于该表的一个或多个字段的表达式索引,通常必须写在圆括弧中。如果表达式有函数调用的形式,圆括弧可以省略。 表达式索引可用于获取对基本数据的某种变形的快速访问。比如,一个在upper(col)上的函数索引将允许WHERE upper(col) = 'JIM'子句使用索引。 在创建表达式索引时,如果表达式中包含IS NULL子句,则这种索引是无效的。此时,建议用户尝试创建一个部分索引。 * **COLLATE collation** COLLATE子句指定列的排序规则(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 * **opclass** 操作符类的名称。对于索引的每一列可以指定一个操作符类,操作符类标识了索引那一列的使用的操作符。例如一个B-tree索引在一个四字节整数上可以使用int4\_ops;这个操作符类包括四字节整数的比较函数。实际上对于列上的数据类型默认的操作符类是足够用的。操作符类主要用于一些有多种排序的数据。例如,用户想按照绝对值或者实数部分排序一个复数。能通过定义两个操作符类然后当建立索引时选择合适的类。 * **ASC** 指定按升序排序(默认)。 * **DESC** 指定按降序排序。 * **NULLS FIRST** 指定空值在排序中排在非空值之前,当指定DESC排序时,本选项为默认的。 * **NULLS LAST** 指定空值在排序中排在非空值之后,未指定DESC排序时,本选项为默认的。 * **LOCAL** 指定创建的分区索引为LOCAL索引。 * **GLOBAL** 指定创建的分区索引为GLOBAL索引,当不指定LOCAL、GLOBAL关键字时,默认创建GLOBAL索引。 * **INCLUDE ( column\_name \[, ...]** ) 可选的 INCLUDE 子句指定将一些非键列(non-key columns)包含在索引中。非键列不能用于作为索引扫描的加速搜索条件,同时在检查索引的唯一性约束时会忽略它们。 仅索引扫描 (Index Only Scan) 可以直接返回非键列中的内容,而不必去访问索引所对应的堆表。 将非键列添加为 INCLUDE 列需要保守一些,尤其是对于宽列。如果索引元组超过索引类型允许的最大大小,数据将插入失败。需要注意的是,任何情况下为索引添加非键列都会增加索引的空间占用,从而可能减慢搜索速度。 目前只有ubtree索引访问方式支持该特性。非键列会被保存在与堆元组对应的索引叶子元组中,不会包含在索引上层页面的元组中。 * **WITH ( {storage\_parameter = value} \[, ... ] )** 指定索引方法的存储参数。 取值范围: 只有 GIN 索引支持 FASTUPDATE,GIN\_PENDING\_LIST\_LIMIT 参数。GIN 和 Psort 之外的索引都支持 FILLFACTOR 参数。只有 UBTREE 索引支持 INDEXSPLIT 参数。 * **FILLFACTOR** 一个索引的填充因子(fillfactor)是一个介于 10 和 100 之间的百分数。 取值范围:10~100 * **FASTUPDATE** GIN 索引是否使用快速更新。 取值范围:ON,OFF 默认值:ON * **GIN\_PENDING\_LIST\_LIMIT** 当 GIN 索引启用 fastupdate 时,设置该索引 pending list 容量的最大值。 取值范围:64~INT\_MAX,单位 KB。 默认值:gin\_pending\_list\_limit 的默认取决于 GUC 中 gin\_pending\_list\_limit 的值(默认为 4MB) * **INDEXSPLIT** UBTREE/BTREE索引选择采取哪种分裂策略。其中 DEFAULT 策略是默认分裂策略。INSERTPT 策略能在某些场景下显著降低索引空间占用。 取值范围:INSERTPT, DEFAULT 默认值:INSERTPT * **COMPRESSTYPE** 索引参数,设置索引压缩算法。1 代表 pglz 算法,2 代表 zstd 算法,3 代表 pgzstd 算法(目前暂不支持),4 代表 zlib 算法,默认不压缩。(仅支持 B-TREE索引) 取值范围:0~4,默认值为 0。 * **COMPRESS\_LEVEL** 索引参数,设置索引压缩算法等级,仅当 COMPRESSTYPE 为 2 或 4 时生效。压缩等级越高,索引的压缩效果越好,索引的访问速度越慢。(仅支持 B-TREE 索引) 取值范围:-31~31,默认值为 0。 * **COMPRESS\_CHUNK\_SIZE** 索引参数,设置索引压缩 chunk 块大小。chunk 数据块越小,预期能达到的压缩效果越好,同时数据越离散,影响索引的访问速度。该参数生效后不允许修改。(仅支持 B-TREE 索引) 取值范围:与页面大小有关。在页面大小为 8k 场景,取值范围为:512、1024、2048、4096。 默认值:4096 * **COMPRESS\_PREALLOC\_CHUNKS** 索引参数,设置索引压缩 chunk 块预分配数量。预分配数量越大,索引的压缩率相对越差,离散度越小,访问性能越好。(仅支持 B-TREE 索引) 取值范围:0~7,默认值为 0。 * 当 COMPRESS\_CHUNK\_SIZE 为 512 和 1024 时,支持预分配设置最大为 7。 * 当 COMPRESS\_CHUNK\_SIZE 为 2048 时,支持预分配设置最大为 3。 * 当 COMPRESS\_CHUNK\_SIZE 为 4096 时,支持预分配设置最大为 1。 * **COMPRESS\_BYTE\_CONVERT** 索引参数,设置索引压缩字节转换预处理。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。 取值范围:布尔值,默认关闭。 * **COMPRESS\_DIFF\_CONVERT** 索引参数,设置索引压缩字节差分预处理。只能与 compress\_byte\_convert 一起使用。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。 取值范围:布尔值,默认关闭。 * **TABLESPACE tablespace\_name** 指定索引的表空间,如果没有声明则使用默认的表空间。 取值范围:已存在的表空间名。 * **COMMENT text** 指定索引的注释,如果没有声明则注释为空。 * **VISIBLE | INVISIBLE** 指定索引是否可见,如果没有声明则默认为VISIBLE。 * **WHERE predicate** 创建一个部分索引。部分索引是一个只包含表的一部分记录的索引,通常是该表中比其他部分数据更有用的部分。例如,有一个表,表里包含已记账和未记账的定单,未记账的定单只占表的一小部分而且这部分是最常用的部分,此时就可以通过只在未记账部分创建一个索引来改善性能。另外一个可能的用途是使用带有UNIQUE的WHERE强制一个表的某个子集的唯一性。 取值范围:predicate表达式只能引用表的字段,它可以使用所有字段,而不仅是被索引的字段。目前,子查询和聚集表达式不能出现在WHERE子句里。不建议使用int等数值类型作为predicate,因为int等数值类型可以隐式转换为bool值(非0值隐式转换为true,0转换为false),可能导致非预期的结果。 对于分区表索引,当创建索引带GLOBAL/LOCAL关键字,或者最终创建的索引类型为GLOBAL索引时,不支持带WHERE子句创建索引。 * **PARTITION index\_partition\_name** 索引分区的名称。 取值范围:字符串,要符合标识符的命名规范。 * **SUBPARTITION index\_subpartition\_name** 索引二级分区的名称。 取值范围:字符串,要符合标识符的命名规范。 * **TABLESPACE index\_partition\_tablespace** 索引分区的表空间。 取值范围:如果没有声明,将使用分区表索引的表空间index\_tablespace。 ## 示例 ``` --创建表tpcds.ship_mode_t1。 openGauss=# create schema tpcds; openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) ; --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建普通的唯一索引。 openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index1 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK); --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建指定B-tree索引。 openGauss=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree(SM_SHIP_MODE_SK); --在表tpcds.ship_mode_t1上SM_CODE字段上创建表达式索引。 openGauss=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1(SUBSTR(SM_CODE,1 ,4)); --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建SM_SHIP_MODE_SK大于10的部分索引。 openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) WHERE SM_SHIP_MODE_SK>10; --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建索引并隐藏。 openGauss=# CREATE INDEX tpcds.ds_ship_mode_t1_index6 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) INVISIBLE; --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建索引并可见。 openGauss=# CREATE INDEX tpcds.ds_ship_mode_t1_index6 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) VISIBLE; --重命名一个现有的索引。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5; --设置索引不可用。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE; --设置索引隐藏。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 INVISIBLE; --设置索引可见。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 VISIBLE; --重建索引。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD; --删除一个现有的索引。 openGauss=# DROP INDEX tpcds.ds_ship_mode_t1_index2; --创建INVISIBLE索引 openGauss=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1(SUBSTR(SM_CODE,1 ,4)) INVISIBLE; --禁用索引 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 DISABLE; --启用索引 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 ENABLE; --删除表。 openGauss=# DROP TABLE tpcds.ship_mode_t1; --创建表空间。 openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; --创建表tpcds.customer_address_p1。 openGauss=# CREATE TABLE tpcds.customer_address_p1 ( CA_ADDRESS_SK INTEGER NOT NULL, CA_ADDRESS_ID CHAR(16) NOT NULL, CA_STREET_NUMBER CHAR(10) , CA_STREET_NAME VARCHAR(60) , CA_STREET_TYPE CHAR(15) , CA_SUITE_NUMBER CHAR(10) , CA_CITY VARCHAR(60) , CA_COUNTY VARCHAR(30) , CA_STATE CHAR(2) , CA_ZIP CHAR(10) , CA_COUNTRY VARCHAR(20) , CA_GMT_OFFSET DECIMAL(5,2) , CA_LOCATION_TYPE CHAR(20) ) TABLESPACE example1 PARTITION BY RANGE(CA_ADDRESS_SK) ( PARTITION p1 VALUES LESS THAN (3000), PARTITION p2 VALUES LESS THAN (5000) TABLESPACE example1, PARTITION p3 VALUES LESS THAN (MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --创建分区表索引ds_customer_address_p1_index1,不指定索引分区的名称。 openGauss=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL; --创建分区表索引ds_customer_address_p1_index2,并指定索引分区的名称。 openGauss=# CREATE INDEX ds_customer_address_p1_index2 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL ( PARTITION CA_ADDRESS_SK_index1, PARTITION CA_ADDRESS_SK_index2 TABLESPACE example3, PARTITION CA_ADDRESS_SK_index3 TABLESPACE example4 ) TABLESPACE example2; --创建GLOBAL分区索引 openGauss=CREATE INDEX ds_customer_address_p1_index3 ON tpcds.customer_address_p1(CA_ADDRESS_ID) GLOBAL; --不指定关键字,默认创建GLOBAL分区索引 openGauss=CREATE INDEX ds_customer_address_p1_index4 ON tpcds.customer_address_p1(CA_ADDRESS_ID); --修改分区表索引CA_ADDRESS_SK_index2的表空间为example1。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1; --修改分区表索引CA_ADDRESS_SK_index3的表空间为example2。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2; --重命名分区表索引。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4; --删除索引和分区表。 openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index1; openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index2; openGauss=# DROP TABLE tpcds.customer_address_p1; --删除表空间。 openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; --创建列存表以及列存表GIN索引。 openGauss=# create table cgin_create_test(a int, b text) with (orientation = column); CREATE TABLE openGauss=# create index cgin_test on cgin_create_test using gin(to_tsvector('ngram', b)); CREATE INDEX ``` ## 相关链接 [ALTER INDEX](alter_index.md),[DROP INDEX](drop_index.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CREATE-INDEX.md --- # CREATE INDEX ## 功能描述 在指定的表上创建索引。 索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议仅在匹配如下某条原则时创建索引: * 经常执行查询的字段。 * 在连接条件上创建索引,对于存在多字段连接的查询,建议在这些字段上建立组合索引。例如,select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b,可以在t1表上的a、b字段上建立组合索引。 * where子句的过滤条件字段上(尤其是范围条件)。 * 在经常出现在order by、group by和distinct后的字段。 在分区表上创建索引与在普通表上创建索引的语法不太一样,使用时请注意,如分区表上不支持并行创建索引,不支持创建部分索引。 新增可以指定 ALGORITHM 选项语法。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 * 新增支持option的无序排列。 * 原始openGauss中,索引名是schema级别唯一的,创建索引时如果索引名重复了会报错。在dolphin插件中,如果GUC参数`dolphin.b_compatibility_mode`为on,当索引名重复时,会自动生成一个不重复的索引名做替代,并告警提示。 * 如果GUC参数`dolphin.b_compatibility_mode`为on且`dolphin.nulls_minimal_policy`为on,创建索引默认为NULLS FIRST索引。如果是倒序索引,索引默认为NULLS LAST,以便兼容null值为最小值的表现行为。 ## 语法格式 * 在表上创建索引。 ``` CREATE [ UNIQUE | FULLTEXT ] INDEX [ CONCURRENTLY ] [ [schema_name.]index_name ] { ON table_name [ USING method ] | [ USING method ] ON table_name } ({ { column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ index_option ] [ WHERE predicate | ALGORITHM [=] {DEFAULT | INPLACE | COPY} ]; ``` ``` CREATE [UNIQUE] INDEX index_name ON tbl_name (key_part,...) [USING {BTREE | HASH}] ``` * 在分区表上创建索引。 ``` CREATE [ UNIQUE ] INDEX [ [schema_name.]index_name ] { ON table_name [ USING method ] | [ USING method ] ON table_name } ( {{ column_name | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name [ ( SUBPARTITION index_subpartition_name [, ...] ) ] [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ index_option ] [ALGORITHM [=] {DEFAULT | INPLACE | COPY} ] ``` ## 参数说明 * **FULLTEXT** 该关键字为创建兼容MySQL的全文索引的语法。该全文索引主要用于字符串的搜索匹配。包含局部匹配搜索,支持中文,韩文,日文。与MATCH () AGAINST ()配合使用。 * **column\_name ( length )** 创建一个基于该表一个字段的前缀键索引,column\_name为前缀键的字段名,length为前缀长度。 前缀键将取指定字段数据的前缀作为索引键值,可以减少索引占用的存储空间。含有前缀键字段的过滤条件和连接条件可以使用索引。 > \[!NOTE]说明 > > * 前缀键支持的索引方法:Btree、UBtree。 > * 前缀键的字段的数据类型必须是二进制类型或字符类型(不包括特殊字符类型)。 > * 前缀长度必须是不超过2676的正整数,并且不能超过字段的最大长度。对于二进制类型,前缀长度以字节数为单位。对于非二进制字符类型,前缀长度以字符数为单位。键值的实际长度受内部页面限制,若字段中含有多字节字符、或者一个索引上有多个键,索引行长度可能会超限,导致报错,设定较长的前缀长度时请考虑此情况。 > * CREATE INDEX语法中,不支持以下关键字作为前缀键的字段名称:COALESCE、CONVERT、DAYOFMONTH、DAYOFWEEK、DAYOFYEAR、DB\_B\_FORMAT、EXTRACT、GREATEST、HOUR\_P、IFNULL、LEAST、LOCATE、MICROSECOND\_P、MID、MINUTE\_P、NULLIF、NVARCHAR、NVL、OVERLAY、POSITION、QUARTER、SECOND\_P、SUBSTR、SUBSTRING、TEXT\_P、TIME、TIMESTAMP、TIMESTAMPDIFF、TREAT、TRIM、WEEKDAY、WEEKOFYEAR、XMLCONCAT、XMLELEMENT、XMLEXISTS、XMLFOREST、XMLPARSE、XMLPI、XMLROOT、XMLSERIALIZE。若含有上述关键字的前缀键所在的索引是通过ALTER TABLE或CREATE TABLE语法创建的,导出的CREATE INDEX语句可能无法成功执行,请尽量不要使用上述关键字作为前缀键的列名称。 * **index\_option** 创建索引时可指定选项,其语法为: ``` INCLUDE ( column_name [, ...] ) | WITH ( { storage_parameter = value } [, ...] ) | TABLESPACE tablespace_name ``` 其中,TABLESPACE选项允许输入多次,以最后一次的输入为准。 * **ALGORITHM** 指定算法,可选项:DEFAULT、INPLACE、COPY。当前只做语法兼容,暂无实际功能。 ## 示例 ```sql --创建表tpcds.ship_mode_t1。 openGauss=# create schema tpcds; openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) ; --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建普通的唯一索引。 openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index1 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK); --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建指定B-tree索引。 openGauss=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree(SM_SHIP_MODE_SK); --在表tpcds.ship_mode_t1上SM_CODE字段上创建表达式索引。 openGauss=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1(SUBSTR(SM_CODE,1 ,4)); --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建SM_SHIP_MODE_SK大于10的部分索引。 openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) WHERE SM_SHIP_MODE_SK>10; --重命名一个现有的索引。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5; --设置索引不可用。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE; --重建索引。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD; --删除一个现有的索引。 openGauss=# DROP INDEX tpcds.ds_ship_mode_t1_index2; --删除表。 openGauss=# DROP TABLE tpcds.ship_mode_t1; --创建表空间。 openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; --创建表tpcds.customer_address_p1。 openGauss=# CREATE TABLE tpcds.customer_address_p1 ( CA_ADDRESS_SK INTEGER NOT NULL, CA_ADDRESS_ID CHAR(16) NOT NULL, CA_STREET_NUMBER CHAR(10) , CA_STREET_NAME VARCHAR(60) , CA_STREET_TYPE CHAR(15) , CA_SUITE_NUMBER CHAR(10) , CA_CITY VARCHAR(60) , CA_COUNTY VARCHAR(30) , CA_STATE CHAR(2) , CA_ZIP CHAR(10) , CA_COUNTRY VARCHAR(20) , CA_GMT_OFFSET DECIMAL(5,2) , CA_LOCATION_TYPE CHAR(20) ) TABLESPACE example1 PARTITION BY RANGE(CA_ADDRESS_SK) ( PARTITION p1 VALUES LESS THAN (3000), PARTITION p2 VALUES LESS THAN (5000) TABLESPACE example1, PARTITION p3 VALUES LESS THAN (MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --创建分区表索引ds_customer_address_p1_index1,不指定索引分区的名称。 openGauss=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL; --创建分区表索引ds_customer_address_p1_index2,并指定索引分区的名称。 openGauss=# CREATE INDEX ds_customer_address_p1_index2 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL ( PARTITION CA_ADDRESS_SK_index1, PARTITION CA_ADDRESS_SK_index2 TABLESPACE example3, PARTITION CA_ADDRESS_SK_index3 TABLESPACE example4 ) TABLESPACE example2; --创建GLOBAL分区索引 openGauss=CREATE INDEX ds_customer_address_p1_index3 ON tpcds.customer_address_p1(CA_ADDRESS_ID) GLOBAL; --不指定关键字,默认创建GLOBAL分区索引 openGauss=CREATE INDEX ds_customer_address_p1_index4 ON tpcds.customer_address_p1(CA_ADDRESS_ID); --修改分区表索引CA_ADDRESS_SK_index2的表空间为example1。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1; --修改分区表索引CA_ADDRESS_SK_index3的表空间为example2。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2; --重命名分区表索引。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4; --删除索引和分区表。 openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index1; openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index2; openGauss=# DROP TABLE tpcds.customer_address_p1; --删除表空间。 openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; --创建列存表以及列存表GIN索引。 openGauss=# create table cgin_create_test(a int, b text) with (orientation = column); CREATE TABLE openGauss=# create index cgin_test on cgin_create_test using gin(to_tsvector('ngram', b)); CREATE INDEX --索引名重复的场景,打开dolphin.b_compatibility_mode后,重复索引名将自动替换成其他不重复的名字 openGauss=# set dolphin.b_compatibility_mode to on; SET openGauss=# create table t1(id int,index idx_id(id)); CREATE TABLE openGauss=# create table t2(id int,index idx_id(id)); WARNING: index "idx_id" already exists, change index name to "t2_id_idx" CREATE TABLE ``` ## 全文索引 ```sql openGauss=# CREATE SCHEMA fulltext_test; CREATE SCHEMA openGauss=# set current_schema to 'fulltext_test'; SET openGauss=# CREATE TABLE test ( id int unsigned auto_increment not null primary key, title varchar, boby text, name name ); NOTICE: CREATE TABLE will create implicit sequence "test_id_seq" for serial column "test.id" NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_pkey" for table "test" CREATE TABLE openGauss=# \d test Table "fulltext_test.test" Column | Type | Modifiers --------+-------------------+------------------------- id | uint4 | not null AUTO_INCREMENT title | character varying | boby | text | name | name | Indexes: "test_pkey" PRIMARY KEY, btree (id) TABLESPACE pg_default openGauss=# CREATE FULLTEXT INDEX test_index_1 ON test (title, boby) WITH PARSER ngram; \d test_index_1 Index "fulltext_test.test_index_1" Column | Type | Definition --------------+------+------------------------------------------------ to_tsvector | text | to_tsvector('"ngram"'::regconfig, title::text) to_tsvector1 | text | to_tsvector('"ngram"'::regconfig, boby) gin, for table "fulltext_test.test" openGauss=# CREATE FULLTEXT INDEX test_index_2 ON test (title, boby, name); CREATE INDEX ``` ## 相关链接 [CREATE INDEX](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_index.html) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/spqplugin-CREATE-INDEX.md --- # CREATE INDEX ## 功能描述 在指定的表上创建索引。 索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议在以下场景创建索引: * 经常执行查询的字段。 * 在连接条件上创建索引,对于存在多字段连接的查询,建议在这些字段上建立组合索引。例如,select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b,可以在t1表上的a、b字段上建立组合索引。 * where子句的过滤条件字段上(尤其是范围条件)。 * 在经常出现在order by、group by和distinct后的字段。 在分区表上创建索引与在普通表上创建索引的语法不太一样,使用时请注意,如不支持创建部分表索引。 ## 注意事项 * 本章节只包含spqplugin新增的多机并行功能,原openGauss的语法未做删除和修改。 ## 示例 ```sql --创建表t1。 openGauss=# create table t1(c1 int, c2 char); CREATE TABLE openGauss=# insert into t1 values(1, 'a'); INSERT 0 1 --在表t1上的c1字段上创建默认B-tree索引。 openGauss=# set spqplugin.spq_enable_btbuild = on; SET openGauss=# create index idx1 on t1 (c1) with (spq_build=on); CREATE INDEX openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+--------------+-----------+----------+--------------+------------- c1 | integer | | plain | | c2 | character(1) | | extended | | Indexes: "idx1" btree (c1) WITH (spq_build=finish) TABLESPACE pg_default Has OIDs: no Options: orientation=row, compression=no --删除索引。 openGauss=# drop index idx1; --在表t1上的c1字段上创建在线B-tree索引。 openGauss=# set spqplugin.spq_enable_btbuild = on; openGauss=# set spqplugin.spq_enable_btbuild_cic = on; SET SET openGauss=# create index concurrently idx1 on t1 (c1) with (spq_build=on); CREATE INDEX openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+--------------+-----------+----------+--------------+------------- c1 | integer | | plain | | c2 | character(1) | | extended | | Indexes: "idx1" btree (c1) WITH (spq_build=finish) TABLESPACE pg_default Has OIDs: no Options: orientation=row, compression=no --删除索引、表。 openGauss=# drop index idx1; openGauss=# drop table t1; ``` 目前仅支持btree索引多机并行。 ## 相关链接 [CREATE INDEX](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_index.html) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-CREATE-INDEX.md --- # CREATE INDEX ## 功能描述 在指定的表上创建索引。 索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议仅在匹配如下某条原则时创建索引: * 经常执行查询的字段。 * 在连接条件上创建索引,对于存在多字段连接的查询,建议在这些字段上建立组合索引。例如,select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b,可以在t1表上的a、b字段上建立组合索引。 * where子句的过滤条件字段上(尤其是范围条件)。 * 在经常出现在order by、group by和distinct后的字段。 在分区表上创建索引与在普通表上创建索引的语法不太一样,使用时请注意,如分区表上不支持并行创建索引,不支持创建部分索引。 新增可以指定 ALGORITHM 选项语法。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。 * 新增支持columnstore选项 ## 语法格式 * 在表上创建索引。 ``` CREATE [ UNIQUE ] [ opt_clustered ] [COLUMNSTORE] INDEX [ CONCURRENTLY ] [ [schema_name.]index_name ] ON table_name [ USING method ] ({ { column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ INCLUDE ( column_name [, ...] )] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ COMMENT text ] [ VISIBLE | INVISIBLE ] [ WHERE predicate ]; ``` ## 参数说明 * **COLUMNSTORE** 该关键字为创建兼容D库的语法,指定列存选项。仅语法作用,没有实际功能。 * **opt\_clustered** 参数内容为CLUSTERED/NONCLUSTERED,兼容D库的语法,指定创建聚合/非聚合索引。仅语法作用,没有实际功能。 ## 示例 ```sql openGauss=# create table t1 (a int); CREATE TABLE openGauss=# create columnstore index on t1 (a); NOTICE: The COLUMNSTORE option is currently ignored CREATE INDEX openGauss=# create table t1 (a int); CREATE TABLE openGauss=# create clustered index on t1 (a); NOTICE: The COLUMNSTORE option is currently ignored CREATE INDEX ``` ## 相关链接 [CREATE INDEX](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_index.html) --- --- url: /zh/docs/latest/ograc/sql_reference/create_index.md --- # CREATE INDEX ## 功能描述 在指定的表上创建索引,用于提升查询性能。 ## 注意事项 * 创建索引需要CREATE ANY INDEX权限 * 复合索引包含的列数不超过16个,最大长度4052 * LOB/ARRAY/IMAGE类型不支持创建普通索引,函数索引的参数是表达式时,结果不能为LOB/ARRAY/IMAGE类型 * 函数索引支持abs、decode、jsonb\_value、json\_value、lower、nvl、nvl2、radians、regexp\_instr、regexp\_substr、reverse、substr、substrb、to\_char、to\_date、to\_number、trim、trunc、upper * 分区索引只支持分区表,分区表可以创建分区索引和全局索引,分区索引和分区数需要一致 ## 语法格式 **stmt:** ```sql CREATE [UNIQUE] INDEX [IF NOT EXISTS] [schema_name.]index_name ON index_table_clause [CRMODE PAGE] [PARALLEL n] [REVERSE] [NOLOGGING] ``` **index\_table\_clause:** ``` [schema_name.]table_name ({column_name | column_expr }[,...]) index_attr_clause ``` **index\_attr\_clause:** ``` [[TABLESPACE tablespace_name] [index_partition_clause]] ``` **index\_partition\_clause:** ``` LOCAL [({PARTITION partition_name [TABLESPACE tablespace_name] [PCTFREE int]}[,...])] ``` ## 参数说明 * **column\_expr**: 索引表达式,函数索引列表达式仅支持部分函数表达式[注意事项](#注意事项)。 * **CRMODE**: MVCC模式。PAGE是页级MVCC, 默认和表的CRMODE一致 * **PARALLEL**: 并行创建索引的并行度。不支持函数索引/临时表索引/在线创建索引 * **REVERSE**: 反向索引 * **NOLOGGING**: 创建索引时不记录REDO * **LOCAL**: 分区索引,即每个分区上单独创建索引 * **PCTFREE**: 指定索引块中为未来索引条目更新预留的空间百分比,单位% ## 示例 ``` -- 在employees表的last_name列上创建普通索引 CREATE INDEX idx_emp_lastname ON employees(last_name); -- 在departments表的department_name列上创建唯一索引 CREATE UNIQUE INDEX idx_dept_name ON departments(department_name); -- 在orders表上创建客户和日期的复合索引 CREATE INDEX idx_orders_customer_date ON orders(customer_id, order_date); -- 创建反向键索引,减少索引块争用 CREATE INDEX idx_emp_id_reverse ON employees(manager_id) REVERSE; -- 在分区表sales上创建本地分区索引 CREATE INDEX idx_sales_date_local ON sales(sale_date) LOCAL; -- 指定每个分区的表空间和属性 CREATE INDEX idx_sales_product_local ON sales(product_id, sale_date) LOCAL ( PARTITION p1_2023 TABLESPACE idx_ts1 COMPRESS, PARTITION p2_2023 TABLESPACE idx_ts2, PARTITION p3_2023 TABLESPACE idx_ts3, PARTITION p4_2023 TABLESPACE idx_ts3, PARTITION p5_future TABLESPACE idx_ts3 ); -- 在表达式上创建索引(需语法支持idx_column_expr) CREATE INDEX idx_emp_upper_name ON employees(UPPER(last_name)); -- 大型表的并行索引创建 CREATE INDEX idx_logs_timestamp ON application_logs(log_timestamp, user_id) PARALLEL 8 NOLOGGING TABLESPACE logs_index_ts CRMODE PAGE; ``` --- --- url: /zh/docs/latest/sql_reference/create_index.md --- # CREATE INDEX ## 功能描述 在指定的表上创建索引。 索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议仅在匹配如下某条原则时创建索引: * 经常执行查询的字段。 * 在连接条件上创建索引,对于存在多字段连接的查询,建议在这些字段上建立组合索引。例如,select \* from t1 join t2 on t1.a=t2.a and t1.b=t2.b,可以在t1表上的a、b字段上建立组合索引。 * where子句的过滤条件字段上(尤其是范围条件)。 * 在经常出现在order by、group by和distinct后的字段。 在分区表上创建索引与在普通表上创建索引的语法不太一样,使用时请注意,如不支持创建部分索引。 ## 注意事项 * 索引自身也占用存储空间、消耗计算资源,创建过多的索引将对数据库性能造成负面影响(尤其影响数据导入的性能,建议在数据导入后再建索引)。因此,仅在必要时创建索引。 * 索引定义里的所有函数和操作符都必须是immutable类型的,即它们的结果必须只能依赖于它们的输入参数,而不受任何外部的影响(如另外一个表的内容或者当前时间)。这个限制可以确保该索引的行为是定义良好的。要在一个索引上或WHERE中使用用户定义函数,请把它标记为immutable类型函数。 * 分区表索引分为LOCAL索引与GLOBAL索引,LOCAL索引与某个具体分区绑定,而GLOBAL索引则对应整个分区表。目前只有B-tree及UBtree索引支持GLOBAL索引。 * 列存表支持的PSORT和B-tree索引都不支持创建表达式索引、部分索引,PSORT不支持创建唯一索引,B-tree支持创建唯一索引。 * 列存表支持的GIN索引支持创建表达式索引,但表达式不能包含空分词、空列和多列,不支持创建部分索引和唯一索引。 * HASH索引目前仅限于行存表索引、临时表索引和分区表LOCAL索引,且不支持创建多字段索引。 * 被授予CREATE ANY INDEX权限的用户,可以在public模式和用户模式下创建索引。 * 如果表达式索引中调用的是用户自定义函数,按照函数创建者权限执行表达式索引函数。 * 仅支持在B兼容性数据库下指定COMMENT。 * 分区表上不支持创建部分索引。 * 分区表创建GLOBAL索引时,存在以下约束条件: * 不支持表达式索引、部分索引 * 不支持列存表 * 仅支持B-tree索引 * 在相同属性列上,分区LOCAL索引与GLOBAL索引不能共存。 * GLOBAL索引,最大支持31列。 * 如果alter语句不带有UPDATE GLOBAL INDEX,那么原有的GLOBAL索引将失效,查询时将使用其他索引进行查询;如果alter语句带有UPDATE GLOBAL INDEX,原有的GLOBAL索引仍然有效,并且索引功能正确。 * 对于分区表的local unique索引,索引键必须包含所有的分区键。 * 当前不支持在JSONB类型的数据上创建UBtree索引。 ## 语法格式 * 在表上创建索引。 ``` CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ IF NOT EXISTS ] [ [schema_name.]index_name ] ON table_name [ USING method ] ({ { column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] }[, ...] ) [ INCLUDE ( column_name [, ...] )] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] [ COMMENT text ] [ VISIBLE | INVISIBLE ] [ WHERE predicate ]; ``` * 在分区表上创建索引。 ``` CREATE [ UNIQUE ] INDEX [ IF NOT EXISTS ] [ [schema_name.]index_name ] ON table_name [ USING method ] ( {{ column_name [ ( length ) ] | ( expression ) } [ COLLATE collation ] [ opclass ] [ ASC | DESC ] [ NULLS LAST ] }[, ...] ) [ LOCAL [ ( { PARTITION index_partition_name [ ( SUBPARTITION index_subpartition_name [, ...] ) ] [ TABLESPACE index_partition_tablespace ] } [, ...] ) ] | GLOBAL ] [ INCLUDE ( column_name [, ...] )] [ WITH ( { storage_parameter = value } [, ...] ) ] [ TABLESPACE tablespace_name ] [ COMMENT text ] [ VISIBLE | INVISIBLE ] [ WHERE predicate ]; ``` ## 参数说明 * **UNIQUE** 创建唯一性索引,每次添加数据时检测表中是否有重复值。如果插入或更新的值会引起重复的记录时,将导致一个错误。 目前只有B-tree及UBTree索引支持唯一索引。 * **CONCURRENTLY** 以不阻塞DML的方式创建索引(加ShareUpdateExclusiveLock锁)。创建索引时,一般会阻塞其他语句对该索引所依赖表的访问。指定此关键字,可以实现创建过程中不阻塞DML。 * 此选项只能指定一个索引的名称。 * 普通CREATE INDEX命令可以在事务内执行,但是CREATE INDEX CONCURRENTLY不可以在事务内执行。 * 列存表、分区表和临时表不支持CONCURRENTLY方式创建索引。 > \[!NOTE]说明 > > * 创建索引时指定此关键字,需要执行先后两次对该表的全表扫描来完成build,第一次扫描的时候创建索引,不阻塞读写操作;第二次扫描的时候合并更新第一次扫描到目前为止发生的变更。 > * 由于需要执行两次对表的扫描和build,而且必须等待现有的所有可能对该表执行修改的事务结束。这意味着该索引的创建比正常耗时更长,同时因此带来的CPU和I/O消耗对其他业务也会造成影响。 > * 如果在索引构建时发生失败,那会留下一个“不可用”的索引。这个索引会被查询忽略,但它仍消耗更新开销。这种情况推荐的恢复方法是删除该索引并尝试再次CONCURRENTLY建索引。 > * 由于在第二次扫描之后,索引构建必须等待任何持有早于第二次扫描拿的快照的事务终止,而且建索引时加的ShareUpdateExclusiveLock锁(4级)会和大于等于4级的锁冲突,在创建这类索引时,容易引发卡住(hang)或者死锁问题。例如: > * 两个会话对同一个表创建CONCURRENTLY索引,会引起死锁问题; > * 两个会话,一个对表创建CONCURRENTLY索引,一个drop table,会引起死锁问题; > * 三个会话,会话1先对表a加锁,不提交,会话2接着对表b创建CONCURRENTLY索引,会话3接着对表a执行写入操作,在会话1事务未提交之前,会话2会一直被阻塞; > * 将事务隔离级别设置成可重复读(默认为读已提交),起两个会话,会话1起事务对表a执行写入操作,不提交,会话2对表b创建CONCURRENTLY索引,在会话1事务未提交之前,会话2会一直被阻塞。 * **schema\_name** 模式的名称。 取值范围:已存在模式名。 * **index\_name** 要创建的索引名,索引的模式与表相同。 取值范围:字符串,要符合标识符的命名规范。 * **table\_name** 需要为其创建索引的表的名称,可以用模式修饰。 取值范围:已存在的表名。 * **USING method** 指定创建索引的方法。 取值范围: * btree:B-tree索引使用一种类似于B+树的结构来存储数据的键值,通过这种结构能够快速的查找索引。btree适合支持比较查询以及查询范围。 * hash:Hash索引使用Hash函数对索引的关键字进行散列。只能处理简单等值比较,比较适合在索引值较长的情况下使用。 * gin:GIN索引是倒排索引,可以处理包含多个键的值(比如数组)。 * gist:Gist索引适用于几何和地理等多维数据类型和集合数据类型。目前支持的数据类型有box、point、poly、circle、tsvector、tsquery、range。 * Psort:Psort索引。针对列存表进行局部排序索引。 * ubtree:仅供Ustore表使用的多版本B-tree索引,索引页面上包含事务信息,能并自主回收页面。 行存表(Astore存储引擎)支持的索引类型:btree(行存表缺省值)、hash、gin、gist。行存表(Ustore存储引擎)支持的索引类型:ubtree。列存表支持的索引类型:Psort(列存表缺省值)、btree、gin。全局临时表不支持GIN索引和Gist索引。 > \[!NOTE]说明 > 列存表对GIN索引支持仅限于对于tsvector类型的支持,即创建列存GIN索引入参需要为to\_tsvector函数(的返回值)。此方法为GIN索引比较普遍的使用方式。 * **column\_name** 表中需要创建索引的列的名称(字段名)。 如果索引方式支持多字段索引,可以声明多个字段。全局索引最多可以声明31个字段,其他索引最多可以声明32个字段。 * **column\_name ( length )** 创建一个基于该表一个字段的前缀键索引,column\_name为前缀键的字段名,length为前缀长度。 前缀键将取指定字段数据的前缀作为索引键值,可以减少索引占用的存储空间。含有前缀键字段的过滤条件和连接条件可以使用索引。 > \[!NOTE]说明 > > * 此语法只在sql\_compatibility=B时有效,sql\_compatibility为其他值的情况下,此子句将被视作函数表达式键。 > * 前缀键支持的索引方法:btree、ubtree。 > * 前缀键的字段的数据类型必须是二进制类型或字符类型(不包括特殊字符类型)。 > * 前缀长度必须是不超过2676的正整数,并且不能超过字段的最大长度。对于二进制类型,前缀长度以字节数为单位。对于非二进制字符类型,前缀长度以字符数为单位。键值的实际长度受内部页面限制,若字段中含有多字节字符、或者一个索引上有多个键,索引行长度可能会超限,导致报错,设定较长的前缀长度时请考虑此情况。 > * CREATE INDEX语法中,不支持以下关键字作为前缀键的字段名称:COALESCE、EXTRACT、GREATEST、LEAST、NULLIF、NVARCHAR、NVL、OVERLAY、POSITION、SUBSTRING、TIMESTAMPDIFF、TREAT、TRIM、XMLCONCAT、XMLELEMENT、XMLEXISTS、XMLFOREST、XMLPARSE、XMLPI、XMLROOT、XMLSERIALIZE。 * **expression** 创建一个基于该表的一个或多个字段的表达式索引,通常必须写在圆括弧中。如果表达式有函数调用的形式,圆括弧可以省略。 表达式索引可用于获取对基本数据的某种变形的快速访问。比如,一个在upper(col)上的函数索引将允许WHERE upper(col) = 'JIM'子句使用索引。 在创建表达式索引时,如果表达式中包含IS NULL子句,则这种索引是无效的。此时,建议用户尝试创建一个部分索引。 * **COLLATE collation** COLLATE子句指定列的排序规则(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 * **opclass** 操作符类的名称。对于索引的每一列可以指定一个操作符类,操作符类标识了索引那一列的使用的操作符。例如一个B-tree索引在一个四字节整数上可以使用int4\_ops;这个操作符类包括四字节整数的比较函数。实际上对于列上的数据类型默认的操作符类是足够用的。操作符类主要用于一些有多种排序的数据。例如,用户想按照绝对值或者实数部分排序一个复数。能通过定义两个操作符类然后当建立索引时选择合适的类。 * **ASC** 指定按升序排序(默认)。 * **DESC** 指定按降序排序。 * **NULLS FIRST** 指定空值在排序中排在非空值之前,当指定DESC排序时,本选项为默认的。 * **NULLS LAST** 指定空值在排序中排在非空值之后,未指定DESC排序时,本选项为默认的。 * **LOCAL** 指定创建的分区索引为LOCAL索引。 * **GLOBAL** 指定创建的分区索引为GLOBAL索引,当不指定LOCAL、GLOBAL关键字时,默认创建GLOBAL索引。 * **INCLUDE ( column\_name \[, ...]** ) 可选的 INCLUDE 子句指定将一些非键列(non-key columns)包含在索引中。非键列不能用于作为索引扫描的加速搜索条件,同时在检查索引的唯一性约束时会忽略它们。 仅索引扫描 (Index Only Scan) 可以直接返回非键列中的内容,而不必去访问索引所对应的堆表。 将非键列添加为 INCLUDE 列需要保守一些,尤其是对于宽列。如果索引元组超过索引类型允许的最大大小,数据将插入失败。需要注意的是,任何情况下为索引添加非键列都会增加索引的空间占用,从而可能减慢搜索速度。 目前只有ubtree索引访问方式支持该特性。非键列会被保存在与堆元组对应的索引叶子元组中,不会包含在索引上层页面的元组中。 * **WITH ( {storage\_parameter = value} \[, ... ] )** 指定索引方法的存储参数。 取值范围: 只有 GIN 索引支持 FASTUPDATE、GIN\_PENDING\_LIST\_LIMIT 参数。GIN 和 Psort 之外的索引都支持 FILLFACTOR 参数。只有 UBTREE 索引支持INDEX\_TYPE 参数。 * **FILLFACTOR** 一个索引的填充因子(fillfactor)是一个介于 10 和 100 之间的百分数。 取值范围:10~100 * **FASTUPDATE** GIN 索引是否使用快速更新。 取值范围:ON,OFF 默认值:ON * **GIN\_PENDING\_LIST\_LIMIT** 当 GIN 索引启用 fastupdate 时,设置该索引 pending list 容量的最大值。 取值范围:64~INT\_MAX,单位 KB。 默认值:gin\_pending\_list\_limit 的默认取决于 GUC 中 gin\_pending\_list\_limit 的值(默认为 4MB) * **INDEXSPLIT** UBTREE/BTREE索引选择采取哪种分裂策略。其中 DEFAULT 策略是默认分裂策略。INSERTPT 策略能在某些场景下显著降低索引空间占用。 取值范围:INSERTPT,DEAFAULT 默认值:INSERTPT * **COMPRESSTYPE** 索引参数,设置索引压缩算法。1 代表 pglz 算法(不推荐使用),2 代表 zstd 算法,3 代表 pgzstd 算法(目前暂不支持),4 表示 zlib 算法,默认不压缩。该参数生效后不允许修改。(仅支持 B-TREE 索引) 取值范围:0~4,默认值为 0。 * **COMPRESS\_LEVEL** 索引参数,设置索引压缩算法等级,仅当 COMPRESSTYPE 为 2 或 4 时生效。压缩等级越高,索引的压缩效果越好,索引的访问速度越慢。该参数允许修改,修改后影响变更数据、新增数据的压缩等级。(仅支持 B-TREE 索引) 取值范围:-31~31,默认值为 0。 * **COMPRESS\_CHUNK\_SIZE** 索引参数,设置索引压缩 chunk 块大小。chunk 数据块越小,预期能达到的压缩效果越好,同时数据越离散,影响索引的访问速度。该参数生效后不允许修改。(仅支持 B-TREE 索引) 取值范围:与页面大小有关。在页面大小为 8k 场景,取值范围为:512、1024、2048、4096。 默认值:4096 * **COMPRESS\_PREALLOC\_CHUNKS** 索引参数,设置索引压缩 chunk 块预分配数量。预分配数量越大,索引的压缩率相对越差,离散度越小,访问性能越好。该参数允许修改,修改后影响变更数据、新增数据的预分配数量。(仅支持 B-TREE 索引) 取值范围:0~7,默认值为 0。 * 当 COMPRESS\_CHUNK\_SIZE 为 512 和 1024 时,支持预分配设置最大为 7。 * 当 COMPRESS\_CHUNK\_SIZE 为 2048 时,支持预分配设置最大为 3。 * 当 COMPRESS\_CHUNK\_SIZE 为 4096 时,支持预分配设置最大为 1。 * **COMPRESS\_BYTE\_CONVERT** 索引参数,设置索引压缩字节转换预处理。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改,修改后决定变更数据、新增数据是否进行字节转换预处理。当 COMPRESS\_DIFF\_CONVERT 为真时,该值不允许修改为假。 取值范围:布尔值,默认关闭。 * **COMPRESS\_DIFF\_CONVERT** 索引参数,设置索引压缩字节差分预处理。只能与 COMPRESS\_BYTE\_CONVERT 一起使用。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改,修改后决定变更数据、新增数据是否进行字节差分预处理。 取值范围:布尔值,默认关闭。 * **INDEX\_TYPE** UBTREE 索引的具体类型,分为RCR、PRC两种类型。该参数生效后不允许修改。 RCR索引基于行一致性读,是默认的UBTREE 索引类型。它在索引元组中存储事务XID,历史版本和最新版本的数据同时存储在索引页中。PCR索引基于页面一致性读,自openGauss 7.0.0-RC2版本开始引入。PCR索引不在索引元组中存储事务XID,并且历史版本数据存储在回滚段而不是索引页中,这些变化使得在PCR索引在索引空间上相比RCR索引有一定优化。在判断元组可见性时,PCR索引可以在内存中构建对当前查询快照可见的页面版本,在某些情况下这可能带来性能优势,但也会增加内存的使用。 取值范围:RCR, PCR 默认值:RCR * **TABLESPACE tablespace\_name** 指定索引的表空间,如果没有声明则使用默认的表空间。 取值范围:已存在的表空间名。 * **COMMENT text** 指定索引的注释,如果没有声明则注释为空。 * **VISIBLE | INVISIBLE** 指定索引是否可见,如果没有声明则默认为VISIBLE。 * **WHERE predicate** 创建一个部分索引。部分索引是一个只包含表的一部分记录的索引,通常是该表中比其他部分数据更有用的部分。例如,有一个表,表里包含已记账和未记账的定单,未记账的定单只占表的一小部分而且这部分是最常用的部分,此时就可以通过只在未记账部分创建一个索引来改善性能。另外一个可能的用途是使用带有UNIQUE的WHERE强制一个表的某个子集的唯一性。 取值范围:predicate表达式只能引用表的字段,它可以使用所有字段,而不仅是被索引的字段。目前,子查询和聚集表达式不能出现在WHERE子句里。不建议使用int等数值类型作为predicate,因为int等数值类型可以隐式转换为bool值(非0值隐式转换为true,0转换为false),可能导致非预期的结果。 对于分区表索引,当创建索引带GLOBAL/LOCAL关键字,或者最终创建的索引类型为GLOBAL索引时,不支持带WHERE子句创建索引。 * **PARTITION index\_partition\_name** 索引分区的名称。 取值范围:字符串,要符合标识符的命名规范。 * **SUBPARTITION index\_subpartition\_name** 索引二级分区的名称。 取值范围:字符串,要符合标识符的命名规范 * **TABLESPACE index\_partition\_tablespace** 索引分区的表空间。 取值范围:如果没有声明,将使用分区表索引的表空间index\_tablespace。 ## 示例 ``` --创建表tpcds.ship_mode_t1。 openGauss=# create schema tpcds; openGauss=# CREATE TABLE tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK INTEGER NOT NULL, SM_SHIP_MODE_ID CHAR(16) NOT NULL, SM_TYPE CHAR(30) , SM_CODE CHAR(10) , SM_CARRIER CHAR(20) , SM_CONTRACT CHAR(20) ) ; --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建普通的唯一索引。 openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index1 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK); --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建指定B-tree索引。 openGauss=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree(SM_SHIP_MODE_SK); --在表tpcds.ship_mode_t1上SM_CODE字段上创建表达式索引。 openGauss=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1(SUBSTR(SM_CODE,1 ,4)); --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建SM_SHIP_MODE_SK大于10的部分索引。 openGauss=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) WHERE SM_SHIP_MODE_SK>10; --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建索引并隐藏。 openGauss=# CREATE INDEX tpcds.ds_ship_mode_t1_index6 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) INVISIBLE; --在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建索引并可见。 openGauss=# CREATE INDEX tpcds.ds_ship_mode_t1_index6 ON tpcds.ship_mode_t1(SM_SHIP_MODE_SK) VISIBLE; --重命名一个现有的索引。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5; --设置索引不可用。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE; --设置索引隐藏。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 INVISIBLE; --设置索引可见。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 VISIBLE; --重建索引。 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD; --删除一个现有的索引。 openGauss=# DROP INDEX tpcds.ds_ship_mode_t1_index2; --创建INVISIBLE索引 openGauss=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1(SUBSTR(SM_CODE,1 ,4)) INVISIBLE; --禁用索引 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 DISABLE; --启用索引 openGauss=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 ENABLE; --删除表。 openGauss=# DROP TABLE tpcds.ship_mode_t1; --创建表空间。 openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; --创建表tpcds.customer_address_p1。 openGauss=# CREATE TABLE tpcds.customer_address_p1 ( CA_ADDRESS_SK INTEGER NOT NULL, CA_ADDRESS_ID CHAR(16) NOT NULL, CA_STREET_NUMBER CHAR(10) , CA_STREET_NAME VARCHAR(60) , CA_STREET_TYPE CHAR(15) , CA_SUITE_NUMBER CHAR(10) , CA_CITY VARCHAR(60) , CA_COUNTY VARCHAR(30) , CA_STATE CHAR(2) , CA_ZIP CHAR(10) , CA_COUNTRY VARCHAR(20) , CA_GMT_OFFSET DECIMAL(5,2) , CA_LOCATION_TYPE CHAR(20) ) TABLESPACE example1 PARTITION BY RANGE(CA_ADDRESS_SK) ( PARTITION p1 VALUES LESS THAN (3000), PARTITION p2 VALUES LESS THAN (5000) TABLESPACE example1, PARTITION p3 VALUES LESS THAN (MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --创建分区表索引ds_customer_address_p1_index1,不指定索引分区的名称。 openGauss=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL; --创建分区表索引ds_customer_address_p1_index2,并指定索引分区的名称。 openGauss=# CREATE INDEX ds_customer_address_p1_index2 ON tpcds.customer_address_p1(CA_ADDRESS_SK) LOCAL ( PARTITION CA_ADDRESS_SK_index1, PARTITION CA_ADDRESS_SK_index2 TABLESPACE example3, PARTITION CA_ADDRESS_SK_index3 TABLESPACE example4 ) TABLESPACE example2; --创建GLOBAL分区索引 openGauss=CREATE INDEX ds_customer_address_p1_index3 ON tpcds.customer_address_p1(CA_ADDRESS_ID) GLOBAL; --不指定关键字,默认创建GLOBAL分区索引 openGauss=CREATE INDEX ds_customer_address_p1_index4 ON tpcds.customer_address_p1(CA_ADDRESS_ID); --修改分区表索引CA_ADDRESS_SK_index2的表空间为example1。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1; --修改分区表索引CA_ADDRESS_SK_index3的表空间为example2。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2; --重命名分区表索引。 openGauss=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4; --删除索引和分区表。 openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index1; openGauss=# DROP INDEX tpcds.ds_customer_address_p1_index2; openGauss=# DROP TABLE tpcds.customer_address_p1; --删除表空间。 openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; --创建列存表以及列存表GIN索引。 openGauss=# create table cgin_create_test(a int, b text) with (orientation = column); CREATE TABLE openGauss=# create index cgin_test on cgin_create_test using gin(to_tsvector('ngram', b)); CREATE INDEX ``` ## 相关链接 [ALTER INDEX](alter_index.md),[DROP INDEX](drop_index.md) --- --- url: /en/docs/latest-lite/sql_reference/create_language.md --- # CREATE LANGUAGE ## Function **CREATE LANGUAGE** defines a new procedural language. A single-node system or centralized system does not support creating procedural languages. ## Syntax ``` CREATE [ OR REPLACE ] [ PROCEDURAL ] LANGUAGE name CREATE [ OR REPLACE ] [ TRUSTED ] [ PROCEDURAL ] LANGUAGE name HANDLER call_handler [ INLINE inline_handler ] [ VALIDATOR valfunction ] ``` ## Parameter Description * **TRUSTED** Specifies that the language does not authorize users who do not have permissions to access data. If this keyword is ignored when the language is registered, only the super user has the permission to use the language. * **PROCEDURAL** It is a useless word. * **name** Specifies the name of the new procedural language. This name should be unique across all languages of the database. For downward compatibility, the name can be enclosed in single quotation marks ('). * **HANDLER call\_handler** **call\_handler** is a previously registered function that will be used to execute the procedural language. The call handler of the procedural language must be written in a compiled language (such as C), the call style must be version 1, and the function must be registered as a function that does not accept parameters and returns the language\_handler type. **language\_handler** is a placeholder for declaring a function as a call handler. * **INLINE inline\_handler** **inline\_handler** is the name of a previously registered function that executes an anonymous block of code (**DO** command) in the language. If the **inline\_handler** function is not specified, the language does not support anonymous code blocks. The handler function must accept a parameter of the internal type, which will be the internal representation of the **DO** command, and it usually returns a void value. Ignore the return value of the handler. * **VALIDATOR valfunction** **valfunction** is a previously registered function name, which is used to verify a new function when it is created in the language. If the verification function is not declared, it will not be checked when a new function is created. The verification function must accept a parameter of the oid type, which is the OID of the function to be created and usually returns a void value. A check function usually checks the function body for syntax errors, but it can also check other attributes of the function, for example, whether the language can process a certain parameter type. The verification function should use the **ereport()** function to report errors. The return value of this function will be ignored. ## Examples A good way to create a standard procedural language: ``` CREATE LANGUAGE plperl; ``` For languages that pg\_pltemplate does not yet know, the following sequence is needed: ``` CREATE FUNCTION plsample_call_handler() RETURNS language_handler AS '$libdir/plsample' LANGUAGE C; CREATE LANGUAGE plsample HANDLER plsample_call_handler; ``` --- --- url: /en/docs/latest/sql_reference/create_language.md --- # CREATE LANGUAGE ## Function **CREATE LANGUAGE** defines a new procedural language. A single-node system or centralized system does not support creating procedural languages. ## Syntax ``` CREATE [ OR REPLACE ] [ PROCEDURAL ] LANGUAGE name CREATE [ OR REPLACE ] [ TRUSTED ] [ PROCEDURAL ] LANGUAGE name HANDLER call_handler [ INLINE inline_handler ] [ VALIDATOR valfunction ] ``` ## Parameter Description * **TRUSTED** Specifies that the language does not authorize users who do not have permissions to access data. If this keyword is ignored when the language is registered, only the super user has the permission to use the language. * **PROCEDURAL** It is a useless word. * **name** Specifies the name of the new procedural language. This name should be unique across all languages of the database. For downward compatibility, the name can be enclosed in single quotation marks ('). * **HANDLER call\_handler** **call\_handler** is a previously registered function that will be used to execute the procedural language. The call handler of the procedural language must be written in a compiled language (such as C), the call style must be version 1, and the function must be registered as a function that does not accept parameters and returns the language\_handler type. **language\_handler** is a placeholder for declaring a function as a call handler. * **INLINE inline\_handler** **inline\_handler** is the name of a previously registered function that executes an anonymous block of code (**DO** command) in the language. If the **inline\_handler** function is not specified, the language does not support anonymous code blocks. The handler function must accept a parameter of the internal type, which will be the internal representation of the **DO** command, and it usually returns a void value. Ignore the return value of the handler. * **VALIDATOR valfunction** **valfunction** is a previously registered function name, which is used to verify a new function when it is created in the language. If the verification function is not declared, it will not be checked when a new function is created. The verification function must accept a parameter of the oid type, which is the OID of the function to be created and usually returns a void value. A check function usually checks the function body for syntax errors, but it can also check other attributes of the function, for example, whether the language can process a certain parameter type. The verification function should use the **ereport()** function to report errors. The return value of this function will be ignored. ## Examples A good way to create a standard procedural language: ``` CREATE LANGUAGE plperl; ``` For languages that pg\_pltemplate does not yet know, the following sequence is needed: ``` CREATE FUNCTION plsample_call_handler() RETURNS language_handler AS '$libdir/plsample' LANGUAGE C; CREATE LANGUAGE plsample HANDLER plsample_call_handler; ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_language.md --- # CREATE LANGUAGE ## 功能描述 定义一种新的过程语言。单机和集中式暂不支持创建过程语言。 ## 语法格式 ``` CREATE [ OR REPLACE ] [ PROCEDURAL ] LANGUAGE name CREATE [ OR REPLACE ] [ TRUSTED ] [ PROCEDURAL ] LANGUAGE name HANDLER call_handler [ INLINE inline_handler ] [ VALIDATOR valfunction ] ``` ## 参数说明 * **TRUSTED** TRUSTED说明该语言并不授权没有权限的用户访问数据。如果在注册该语言时忽略这个关键字,则只有SYSADMIN权限可以使用。 * **PROCEDURAL** 这是个没有用的字。 * **name** 新过程语言的名称。这个名字应该在数据库的所有语言中唯一。 出于向下兼容的原因,这个名字可以用单引号包围。 * **HANDLER call\_handler** call\_handler是一个以前注册过的函数名字,该函数将被用来执行该过程语言的函数。过程语言的调用处理器必须用一种编译语言(比如C)书写,调用风格必须是版本1的调用风格,并且注册为不接受参数并且返回language\_handler类型的函数。language\_handler是用于将函数声明为调用处理器的占位符。 * **INLINE inline\_handler** inline\_handler是以前注册过的函数名字,用来在该语言中执行一个匿名代码块(DO命令)。如果没有指定inline\_handler函数,那么该语言不支持匿名代码块。处理器函数必须接受一个internal类型的参数,这将是DO命令的内部表示,并且它通常返回void。忽略该处理器的返回值。 * **VALIDATOR valfunction** valfunction是一个以前注册过的函数名字,在用该语言创建新函数的时候将用它来校验新函数。如果没有声明校验函数,那么建立新函数的时候就不会检查它。校验函数必须接受一个类型为oid的参数,它是将要创建的函数的OID,并且通常会返回void。 校验函数通常会检查函数体,看看有没有语法错误,但是它也可以查看函数的其它属性,比如该语言是否不能处理某种参数类型。校验函数应该用ereport()函数报告错误。该函数的返回值将被忽略。 ## 示例 创建标准的过程语言的比较好的方法: ``` CREATE LANGUAGE plperl; ``` 对于pg\_pltemplate还不知道的语言,需要下面这样的序列: ``` CREATE FUNCTION plsample_call_handler() RETURNS language_handler AS '$libdir/plsample' LANGUAGE C; CREATE LANGUAGE plsample HANDLER plsample_call_handler; ``` --- --- url: /zh/docs/latest/sql_reference/create_language.md --- # CREATE LANGUAGE ## 功能描述 定义一种新的过程语言。单机和集中式暂不支持创建过程语言。 ## 语法格式 ``` CREATE [ OR REPLACE ] [ PROCEDURAL ] LANGUAGE name CREATE [ OR REPLACE ] [ TRUSTED ] [ PROCEDURAL ] LANGUAGE name HANDLER call_handler [ INLINE inline_handler ] [ VALIDATOR valfunction ] ``` ## 参数说明 * **TRUSTED** TRUSTED说明该语言并不授权没有权限的用户访问数据。如果在注册该语言时忽略这个关键字,则只有超级用户权限可以使用。 * **PROCEDURAL** 这是个没有用的字。 * **name** 新过程语言的名称。这个名字应该在数据库的所有语言中唯一。 出于向下兼容的原因,这个名字可以用单引号包围。 * **HANDLER call\_handler** call\_handler是一个以前注册过的函数名字,该函数将被用来执行该过程语言的函数。过程语言的调用处理器必须用一种编译语言(比如C)书写,调用风格必须是版本1的调用风格,并且注册为不接受参数并且返回language\_handler类型的函数。language\_handler是用于将函数声明为调用处理器的占位符。 * **INLINE inline\_handler** inline\_handler是以前注册过的函数名字,用来在该语言中执行一个匿名代码块(DO命令)。如果没有指定inline\_handler函数,那么该语言不支持匿名代码块。处理器函数必须接受一个internal类型的参数,这将是DO命令的内部表示,并且它通常返回void。忽略该处理器的返回值。 * **VALIDATOR valfunction** valfunction是一个以前注册过的函数名字,在用该语言创建新函数的时候将用它来校验新函数。如果没有声明校验函数,那么建立新函数的时候就不会检查它。校验函数必须接受一个类型为oid的参数,它是将要创建的函数的OID,并且通常会返回void。 校验函数通常会检查函数体,看看有没有语法错误,但是它也可以查看函数的其它属性,比如该语言是否不能处理某种参数类型。校验函数应该用ereport()函数报告错误。该函数的返回值将被忽略。 ## 示例 创建标准的过程语言的比较好的方法: ``` CREATE LANGUAGE plperl; ``` 对于pg\_pltemplate还不知道的语言,需要下面这样的序列: ``` CREATE FUNCTION plsample_call_handler() RETURNS language_handler AS '$libdir/plsample' LANGUAGE C; CREATE LANGUAGE plsample HANDLER plsample_call_handler; ``` --- --- url: /en/docs/latest-lite/sql_reference/create_masking_policy.md --- # CREATE MASKING POLICY ## Function **CREATE MASKING POLICY** creates a masking policy. ## Precautions Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. The masking policy takes effect only after the security policy is enabled, that is, **enable\_security\_policy** is set to **on**. For details about the execution effect and supported data types of preset masking functions, see "Database Security > Dynamic Data Masking" in *Feature Description*. ## Syntax ``` CREATE MASKING POLICY policy_name masking_clause[, ...]* policy_filter [ENABLE | DISABLE]; ``` * masking\_clause ``` masking_function ON LABEL(label_name[, ...]*) ``` * masking\_function **maskall** is not a preset function. It is hard-coded and cannot be displayed by running **\df**. The masking methods during presetting are as follows: ``` maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking ``` * policy\_filter: ``` FILTER ON FILTER_TYPE(filter_value [,...]*)[,...]* ``` * FILTER\_TYPE: ``` IP | APP | ROLES ``` ## Parameter Description * **policy\_name** Specifies the audit policy name, which must be unique. Value range: a string. It must comply with the naming convention. * **label\_name** Specifies the resource label name. * **masking\_clause** Specifies the masking function to be used to anonymize database resources labeled by **label\_name**. **schema.function** can be used to specify the masking function. * **policy\_filter** Specifies the users for which the masking policy takes effect. If this parameter is left empty, the masking policy takes effect for all users. * **FILTER\_TYPE** Specifies the types of information to be filtered by the policy, including **IP**, **APP**, and **ROLES**. * **filter\_value** Indicates the detailed information to be filtered, such as the IP address, app name, and username. * **ENABLE|DISABLE** Enables or disables the masking policy. If **ENABLE|DISABLE** is not specified, **ENABLE** is used by default. ## Examples ``` -- Create users dev_mask and bob_mask. openGauss=# CREATE USER dev_mask PASSWORD 'xxxxxx'; openGauss=# CREATE USER bob_mask PASSWORD 'xxxxxx'; -- Create table tb_for_masking. openGauss=# CREATE TABLE tb_for_masking(col1 text, col2 text, col3 text); -- Create a resource label for label sensitive column col1. openGauss=# CREATE RESOURCE LABEL mask_lb1 ADD COLUMN(tb_for_masking.col1); -- Create a resource label for label sensitive column col2. openGauss=# CREATE RESOURCE LABEL mask_lb2 ADD COLUMN(tb_for_masking.col2); -- Create a masking policy for the operation of accessing sensitive column col1. openGauss=# CREATE MASKING POLICY maskpol1 maskall ON LABEL(mask_lb1); -- Create a masking policy that takes effect only for scenarios where users are dev_mask and bob_mask, client tools are psql and gsql, and IP addresses are 10.20.30.40, and 127.0.0.0/24. openGauss=# CREATE MASKING POLICY maskpol2 randommasking ON LABEL(mask_lb2) FILTER ON ROLES(dev_mask, bob_mask), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24'); ``` ## Helpful Links [ALTER MASKING POLICY](alter_masking_policy.md) and [DROP MASKING POLICY](drop_masking_policy.md) --- --- url: /en/docs/latest/sql_reference/create_masking_policy.md --- # CREATE MASKING POLICY ## Function **CREATE MASKING POLICY** creates a masking policy. ## Precautions Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. The masking policy takes effect only after the security policy is enabled, that is, **enable\_security\_policy** is set to **on**. For details, see "Database Configuration > Database Security Management Policies > Dynamic Data Masking" in *Security Hardening Guide*. For details about the execution effect and supported data types of preset masking functions, see "Database Security > Dynamic Data Masking" in *Feature Description*. ## Syntax ``` CREATE MASKING POLICY policy_name masking_clause[, ...]* policy_filter [ENABLE | DISABLE]; ``` * masking\_clause ``` masking_function ON LABEL(label_name[, ...]*) ``` * masking\_function **maskall** is not a preset function. It is hard-coded and cannot be displayed by running **\df**. The masking methods during presetting are as follows: ``` maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking ``` * policy\_filter: ``` FILTER ON FILTER_TYPE(filter_value [,...]*)[,...]* ``` * FILTER\_TYPE: ``` IP | APP | ROLES ``` ## Parameter Description * **policy\_name** Specifies the audit policy name, which must be unique. Value range: a string. It must comply with the naming convention. * **label\_name** Specifies the resource label name. * **masking\_clause** Specifies the masking function to be used to anonymize database resources labeled by **label\_name**. **schema.function** can be used to specify the masking function. * **policy\_filter** Specifies the users for which the masking policy takes effect. If this parameter is left empty, the masking policy takes effect for all users. * **FILTER\_TYPE** Specifies the types of information to be filtered by the policy, including **IP**, **APP**, and **ROLES**. * **filter\_value** Indicates the detailed information to be filtered, such as the IP address, app name, and username. * **ENABLE|DISABLE** Enables or disables the masking policy. If **ENABLE|DISABLE** is not specified, **ENABLE** is used by default. ## Examples ``` -- Create users dev_mask and bob_mask. openGauss=# CREATE USER dev_mask PASSWORD 'xxxxxx'; openGauss=# CREATE USER bob_mask PASSWORD 'xxxxxx'; -- Create table tb_for_masking. openGauss=# CREATE TABLE tb_for_masking(col1 text, col2 text, col3 text); -- Create a resource label for label sensitive column col1. openGauss=# CREATE RESOURCE LABEL mask_lb1 ADD COLUMN(tb_for_masking.col1); -- Create a resource label for label sensitive column col2. openGauss=# CREATE RESOURCE LABEL mask_lb2 ADD COLUMN(tb_for_masking.col2); -- Create a masking policy for the operation of accessing sensitive column col1. openGauss=# CREATE MASKING POLICY maskpol1 maskall ON LABEL(mask_lb1); -- Create a masking policy that takes effect only for scenarios where users are dev_mask and bob_mask, client tools are psql and gsql, and IP addresses are 10.20.30.40, and 127.0.0.0/24. openGauss=# CREATE MASKING POLICY maskpol2 randommasking ON LABEL(mask_lb2) FILTER ON ROLES(dev_mask, bob_mask), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24'); ``` ## Helpful Links [ALTER MASKING POLICY](alter_masking_policy.md) and [DROP MASKING POLICY](drop_masking_policy.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_masking_policy.md --- # CREATE MASKING POLICY ## 功能描述 创建脱敏策略。 ## 注意事项 只有poladmin,sysadmin或初始用户能执行此操作。 需要开启安全策略开关,即设置GUC参数enable\_security\_policy=on,脱敏策略才可以生效。 预置脱敏函数的执行效果及支持的数据类型请参考《关于openGauss》中”特性描述 > 数据库安全 > 动态数据脱敏机制”章节。 ## 语法格式 ``` CREATE MASKING POLICY policy_name masking_clause[, ...]* policy_filter [ENABLE | DISABLE]; ``` * masking\_clause: ``` masking_function ON LABEL(label_name[, ...]*) ``` * masking\_function: maskall不是预置函数,硬编码在代码中,不支持\df展示。 预置时脱敏方式如下: ``` maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking ``` * policy\_filter: ``` FILTER ON FILTER_TYPE(filter_value [,...]*)[,...]* ``` * FILTER\_TYPE: ``` IP | APP | ROLES ``` ## 参数说明 * **policy\_name** 审计策略名称,需要唯一,不可重复。 取值范围:字符串,要符合标识符的命名规范。 * **label\_name** 资源标签名称。 * **masking\_clause** 指出使用何种脱敏函数对被label\_name标签标记的数据库资源进行脱敏,支持用schema.function的方式指定脱敏函数。 * **policy\_filter** 指出该脱敏策略对何种身份的用户生效,若为空表示对所用用户生效。 * **FILTER\_TYPE** 描述策略过滤的条件类型,包括IP | APP | ROLES。 * **filter\_value** 指具体过滤信息内容,例如具体的IP,具体的APP名称,具体的用户名。 * **ENABLE|DISABLE** 可以打开或关闭脱敏策略。若不指定ENABLE|DISABLE,语句默认为ENABLE。 ## 示例 ``` --创建dev_mask和bob_mask用户。 openGauss=# CREATE USER dev_mask PASSWORD 'XXXXXXXX'; openGauss=# CREATE USER bob_mask PASSWORD 'XXXXXXXX'; --创建一个表tb_for_masking openGauss=# CREATE TABLE tb_for_masking(col1 text, col2 text, col3 text); --创建资源标签标记敏感列col1 openGauss=# CREATE RESOURCE LABEL mask_lb1 ADD COLUMN(tb_for_masking.col1); --创建资源标签标记敏感列col2 openGauss=# CREATE RESOURCE LABEL mask_lb2 ADD COLUMN(tb_for_masking.col2); --对访问敏感列col1的操作创建脱敏策略 openGauss=# CREATE MASKING POLICY maskpol1 maskall ON LABEL(mask_lb1); --创建仅对用户dev_mask和bob_mask,客户端工具为psql和gsql,IP地址为'10.20.30.40', '127.0.0.0/24'场景下生效的脱敏策略。 openGauss=# CREATE MASKING POLICY maskpol2 randommasking ON LABEL(mask_lb2) FILTER ON ROLES(dev_mask, bob_mask), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24'); ``` ## 相关链接 [ALTER MASKING POLICY](alter_masking_policy.md),[DROP MASKING POLICY](drop_masking_policy.md)。 --- --- url: /zh/docs/latest/sql_reference/create_masking_policy.md --- # CREATE MASKING POLICY ## 功能描述 创建脱敏策略。 ## 注意事项 只有poladmin、sysadmin或初始用户能执行此操作。 需要开启安全策略开关,即设置GUC参数enable\_security\_policy=on,脱敏策略才可以生效。 预置脱敏函数的执行效果及支持的数据类型请参考《关于openGauss》中“特性描述 > 数据库安全 > 动态数据脱敏机制”章节。 ## 语法格式 ``` CREATE MASKING POLICY policy_name masking_clause[, ...]* policy_filter [ENABLE | DISABLE]; ``` * masking\_clause: ``` masking_function ON LABEL(label_name[, ...]*) ``` * masking\_function: maskall不是预置函数,硬编码在代码中,不支持\df展示。 预置时脱敏方式如下: ``` maskall | randommasking | creditcardmasking | basicemailmasking | fullemailmasking | shufflemasking | alldigitsmasking | regexpmasking ``` * policy\_filter: ``` FILTER ON FILTER_TYPE(filter_value [,...]*)[,...]* ``` * FILTER\_TYPE: ``` IP | APP | ROLES ``` ## 参数说明 * **policy\_name** 审计策略名称,需要唯一,不可重复。 取值范围:字符串,要符合标识符的命名规范。 * **label\_name** 资源标签名称。 * **masking\_clause** 指出使用何种脱敏函数对被label\_name标签标记的数据库资源进行脱敏,支持用schema.function的方式指定脱敏函数。 * **policy\_filter** 指出该脱敏策略对何种身份的用户生效,若为空表示对所用用户生效。 * **FILTER\_TYPE** 描述策略过滤的条件类型,包括IP | APP | ROLES。 * **filter\_value** 指具体过滤信息内容,例如具体的IP、具体的APP名称、具体的用户名。 * **ENABLE|DISABLE** 可以打开或关闭脱敏策略。若不指定ENABLE|DISABLE,语句默认为ENABLE。 ## 示例 ``` --创建dev_mask和bob_mask用户。 openGauss=# CREATE USER dev_mask PASSWORD 'XXXXXXXX'; openGauss=# CREATE USER bob_mask PASSWORD 'XXXXXXXX'; --创建一个表tb_for_masking openGauss=# CREATE TABLE tb_for_masking(col1 text, col2 text, col3 text); --创建资源标签标记敏感列col1 openGauss=# CREATE RESOURCE LABEL mask_lb1 ADD COLUMN(tb_for_masking.col1); --创建资源标签标记敏感列col2 openGauss=# CREATE RESOURCE LABEL mask_lb2 ADD COLUMN(tb_for_masking.col2); --对访问敏感列col1的操作创建脱敏策略 openGauss=# CREATE MASKING POLICY maskpol1 maskall ON LABEL(mask_lb1); --创建仅对用户dev_mask和bob_mask,客户端工具为psql和gsql,IP地址为'10.20.30.40', '127.0.0.0/24'场景下生效的脱敏策略。 openGauss=# CREATE MASKING POLICY maskpol2 randommasking ON LABEL(mask_lb2) FILTER ON ROLES(dev_mask, bob_mask), APP(psql, gsql), IP('10.20.30.40', '127.0.0.0/24'); ``` ## 相关链接 [ALTER MASKING POLICY](alter_masking_policy.md),[DROP MASKING POLICY](drop_masking_policy.md)。 --- --- url: /en/docs/latest-lite/sql_reference/create_materialized_view.md --- # CREATE MATERIALIZED VIEW **CREATE MATERIALIZED VIEW** creates a complete-refresh materialized view, and you can use **REFRESH MATERIALIZED VIEW** to fully refresh the data in the materialized view. **CREATE MATERIALIZED VIEW** is similar to **CREATE TABLE AS**, but it remembers the query used to initialize the view, so it can refresh data later. A materialized view has many attributes that are the same as those of a table, but does not support temporary materialized views. ## Precautions * Complete-refresh materialized views cannot be created in temporary tables or global temporary tables. * Complete-refresh materialized views do not support NodeGroups. * After a complete-refresh materialized view is created, most DDL operations in the base table are no longer supported. * The IUD operation cannot be performed on complete-refresh materialized views. * After a complete-refresh materialized view is created, if the base table data changes, you need to run the **REFRESH** command to synchronize the materialized view with the base table. * The Ustore engine does not support the creation and use of materialized views. ## Syntax ``` CREATE MATERIALIZED VIEW mv_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] AS query [ WITH [ NO ] DATA ]; ``` ## Parameter Description * **mv\_name** Name (optionally schema-qualified) of the materialized view to be created. Value range: a string. It must comply with the identifier naming convention. * **column\_name** Specifies a column name in the new materialized view. The materialized view supports specified columns. The number of specified columns must be the same as the number of columns in the result of the subsequent query statement. If no column name is provided, the column name is obtained from the output column name of the query. Value range: a string. It must comply with the identifier naming convention. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. For details, see [CREATE TABLE](create_table.md). * **TABLESPACE tablespace\_name** Tablespace to which the new materialized view belongs. If not specified, the default tablespace is used. * **AS query** Specifies the **SELECT**, **TABLE**, or **VALUES** command. This query will be run in a security-constrained operation. ## Examples ``` -- Create an ordinary table. openGauss=# CREATE TABLE my_table (c1 int, c2 int); -- Create a complete-refresh materialized view. openGauss=# CREATE MATERIALIZED VIEW my_mv AS SELECT * FROM my_table; -- Write data to the base table. openGauss=# INSERT INTO my_table VALUES(1,1),(2,2); -- Refresh the complete-refresh materialized view my_mv. openGauss=# REFRESH MATERIALIZED VIEW my_mv; ``` ## Helpful Links [ALTER MATERIALIZED VIEW](alter_materialized_view.md), [CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md), [CREATE TABLE](create_table.md), [DROP MATERIALIZED VIEW](drop_materialized_view.md), [REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md), and [REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /en/docs/latest/sql_reference/create_materialized_view.md --- # CREATE MATERIALIZED VIEW **CREATE MATERIALIZED VIEW** creates a complete-refresh materialized view, and you can use **REFRESH MATERIALIZED VIEW** to fully refresh the data in the materialized view. **CREATE MATERIALIZED VIEW** is similar to **CREATE TABLE AS**, but it remembers the query used to initialize the view, so it can refresh data later. A materialized view has many attributes that are the same as those of a table, but does not support temporary materialized views. ## Precautions * Complete-refresh materialized views cannot be created in temporary tables or global temporary tables. * Complete-refresh materialized views do not support NodeGroups. * After a complete-refresh materialized view is created, most DDL operations in the base table are no longer supported. * The IUD operation cannot be performed on complete-refresh materialized views. * After a complete-refresh materialized view is created, if the base table data changes, you need to run the **REFRESH** command to synchronize the materialized view with the base table. * The Ustore engine does not support the creation and use of materialized views. ## Syntax ``` CREATE MATERIALIZED VIEW mv_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] AS query [ WITH [ NO ] DATA ]; ``` ## Parameter Description * **mv\_name** Name (optionally schema-qualified) of the materialized view to be created. Value range: a string. It must comply with the identifier naming convention. * **column\_name** Specifies a column name in the new materialized view. The materialized view supports specified columns. The number of specified columns must be the same as the number of columns in the result of the subsequent query statement. If no column name is provided, the column name is obtained from the output column name of the query. Value range: a string. It must comply with the identifier naming convention. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. For details, see [CREATE TABLE](create_table.md). * **TABLESPACE tablespace\_name** Tablespace to which the new materialized view belongs. If not specified, the default tablespace is used. * **AS query** Specifies the **SELECT**, **TABLE**, or **VALUES** command. This query will be run in a security-constrained operation. ## Examples ``` -- Create an ordinary table. openGauss=# CREATE TABLE my_table (c1 int, c2 int); -- Create a complete-refresh materialized view. openGauss=# CREATE MATERIALIZED VIEW my_mv AS SELECT * FROM my_table; -- Write data to the base table. openGauss=# INSERT INTO my_table VALUES(1,1),(2,2); -- Refresh the complete-refresh materialized view my_mv. openGauss=# REFRESH MATERIALIZED VIEW my_mv; ``` ## Helpful Links [ALTER MATERIALIZED VIEW](alter_materialized_view.md), [CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md), [CREATE TABLE](create_table.md), [DROP MATERIALIZED VIEW](drop_materialized_view.md), [REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md), and [REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_materialized_view.md --- # CREATE MATERIALIZED VIEW CREATE MATERIALIZED VIEW会创建一个全量物化视图,并且后续可以使用REFRESH MATERIALIZED VIEW(全量刷新)刷新物化视图的数据。 CREATE MATERIALIZED VIEW类似于CREATE TABLE AS,不过它会记住被用来初始化该视图的查询, 因此它可以在后续中进行数据刷新。一个物化视图有很多和表相同的属性,但是不支持临时物化视图。 ## 注意事项 * 全量物化视图不可以在临时表或全局临时表上创建。 * 全量物化视图不支持nodegroup。 * 创建全量物化视图后,基表中的绝大多数DDL操作不再支持。 * 不支持对全量物化视图进行IUD操作。 * 全量物化视图创建后,当基表数据发生变化时,需要使用刷新(REFRESH)命令保持物化视图与基表同步。 * Ustore引擎不支持物化视图的创建和使用。 ## 语法格式 ``` CREATE MATERIALIZED VIEW mv_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] AS query [ WITH [ NO ] DATA ]; ``` ## 参数说明 * **mv\_name** 要创建的物化视图的名称(可以被模式限定)。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新物化视图中的一个列名。物化视图支持指定列,指定列需要和后面的查询语句结果的列数量保持一致;如果没有提供列名,会从查询的输出列名中获取列名。 取值范围:字符串,要符合标识符的命名规范。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。详见[CREATE TABLE](create_table.md)。 * **TABLESPACE tablespace\_name** 指定新建物化视图所属表空间。如果没有声明,将使用默认表空间。 * **AS query** 一个SELECT、TABLE 或者VALUES命令。这个查询将在一个安全受限的操作中运行。 * **\[ WITH \[ NO ] DATA ]** 创建表时,是否也插入查询到的数据。默认是要数据,选择“NO”参数时,则不要数据。 ## 示例 ``` --创建一个普通表 openGauss=# CREATE TABLE my_table (c1 int, c2 int); --创建全量物化视图 openGauss=# CREATE MATERIALIZED VIEW my_mv AS SELECT * FROM my_table; --基表写入数据 openGauss=# INSERT INTO my_table VALUES(1,1),(2,2); --对全量物化视图my_mv进行全量刷新 openGauss=# REFRESH MATERIALIZED VIEW my_mv; ``` ## 相关链接 [ALTER MATERIALIZED VIEW](alter_materialized_view.md), [CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md),[CREATE TABLE](create_table.md),[DROP MATERIALIZED VIEW](drop_materialized_view.md),[REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md),[REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /zh/docs/latest/sql_reference/create_materialized_view.md --- # CREATE MATERIALIZED VIEW CREATE MATERIALIZED VIEW会创建一个全量物化视图,并且后续可以使用REFRESH MATERIALIZED VIEW(全量刷新)刷新物化视图的数据。 CREATE MATERIALIZED VIEW类似于CREATE TABLE AS,不过它会记住被用来初始化该视图的查询, 因此它可以在后续中进行数据刷新。一个物化视图有很多和表相同的属性,但是不支持临时物化视图。 ## 注意事项 * 全量物化视图不可以在临时表或全局临时表上创建。 * 全量物化视图不支持nodegroup。 * 创建全量物化视图后,基表中的绝大多数DDL操作不再支持。 * 不支持对全量物化视图进行IUD操作。 * 全量物化视图创建后,当基表数据发生变化时,需要使用刷新(REFRESH)命令保持物化视图与基表同步。 * Ustore引擎不支持物化创建、使用视图。 ## 语法格式 ``` CREATE MATERIALIZED VIEW mv_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ] AS query [ WITH [ NO ] DATA ]; ``` ## 参数说明 * **mv\_name** 要创建的物化视图的名称(可以被模式限定)。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新物化视图中的一个列名。物化视图支持指定列,指定列需要和后面的查询语句结果的列数量保持一致;如果没有提供列名,会从查询的输出列名中获取列名。 取值范围:字符串,要符合标识符的命名规范。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。详见[CREATE TABLE](create_table.md)。 * **TABLESPACE tablespace\_name** 指定新建物化视图所属表空间。如果没有声明,将使用默认表空间。 * **AS query** 一个SELECT、TABLE 或者VALUES命令。这个查询将在一个安全受限的操作中运行。 * **\[ WITH \[ NO ] DATA ]** 创建表时,是否也插入查询到的数据。默认是要数据,选择“NO”参数时,则不要数据。 ## 示例 ``` --创建一个普通表 openGauss=# CREATE TABLE my_table (c1 int, c2 int); --创建全量物化视图 openGauss=# CREATE MATERIALIZED VIEW my_mv AS SELECT * FROM my_table; --基表写入数据 openGauss=# INSERT INTO my_table VALUES(1,1),(2,2); --对全量物化视图my_mv进行全量刷新 openGauss=# REFRESH MATERIALIZED VIEW my_mv; ``` ## 相关链接 [ALTER MATERIALIZED VIEW](alter_materialized_view.md), [CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md),[CREATE TABLE](create_table.md),[DROP MATERIALIZED VIEW](drop_materialized_view.md),[REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md),[REFRESH MATERIALIZED VIEW](refresh_materialized_view.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_materialized_view_log.md --- # CREATE MATERIALIZED VIEW LOG CREATE MATERIALIZED VIEW LOG会创建一个物化视图日志,物化视图日志和表是一一对应的关系。 物化视图日志是用于增量刷新物化视图的,创建增量物化视图的时候如果相关的表还没有物化视图日志,会自动创建;如果已有,则直接使用已有的物化视图日志。 ## 注意事项 * 由于物化视图日志只用于增量物化视图的增量刷新,所以在所属表没有被增量物化视图引用的情况下,物化视图日志不会被维护。 * 当某张表的最后一个增量物化视图被删除的时候,这张表对应的物化视图日志也会被自动删除。 * 为了保证数据的完整性,新创建的物化视图日志不能直接用于增量刷新,在创建物化视图日志之后必须先经过一次增量物化视图的全量刷新,之后才能进行增量刷新。 ## 语法格式 ``` CREATE MATERIALIZED VIEW LOG ON table_name; ``` ## 参数说明 * **table\_name** 要创建的物化视图日志所属的表名。 ## 示例 ``` --创建一个普通表 openGauss=# CREATE TABLE my_table (c1 int, c2 int); --创建物化视图日志 openGauss=# CREATE MATERIALIZED VIEW LOG ON my_table; --创建增量物化视图 openGauss=# CREATE INCREMENTAL MATERIALIZED VIEW my_mv AS SELECT * FROM my_table; ``` ## 相关链接 [CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md),[DROP MATERIALIZED VIEW](drop_materialized_view.md),[DROP MATERIALIZED VIEW LOG](drop_materialized_view_log.md),[REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md) --- --- url: /zh/docs/latest/sql_reference/create_materialized_view_log.md --- # CREATE MATERIALIZED VIEW LOG CREATE MATERIALIZED VIEW LOG会创建一个物化视图日志,物化视图日志和表是一一对应的关系。 物化视图日志是用于增量刷新物化视图的,创建增量物化视图的时候如果相关的表还没有物化视图日志,会自动创建;如果已有,则直接使用已有的物化视图日志。 ## 注意事项 * 由于物化视图日志只用于增量物化视图的增量刷新,所以在所属表没有被增量物化视图引用的情况下,物化视图日志不会被维护。 * 当某张表的最后一个增量物化视图被删除的时候,这张表对应的物化视图日志也会被自动删除。 * 为了保证数据的完整性,新创建的物化视图日志不能直接用于增量刷新,在创建物化视图日志之后必须先经过一次增量物化视图的全量刷新,之后才能进行增量刷新。 ## 语法格式 ``` CREATE MATERIALIZED VIEW LOG ON table_name; ``` ## 参数说明 * **table\_name** 要创建的物化视图日志所属的表名。 ## 示例 ``` --创建一个普通表 openGauss=# CREATE TABLE my_table (c1 int, c2 int); --创建物化视图日志 openGauss=# CREATE MATERIALIZED VIEW LOG ON my_table; --创建增量物化视图 openGauss=# CREATE INCREMENTAL MATERIALIZED VIEW my_mv AS SELECT * FROM my_table; ``` ## 相关链接 [CREATE INCREMENTAL MATERIALIZED VIEW](create_incremental_materialized_view.md),[DROP MATERIALIZED VIEW](drop_materialized_view.md),[DROP MATERIALIZED VIEW LOG](drop_materialized_view_log.md),[REFRESH INCREMENTAL MATERIALIZED VIEW](refresh_incremental_materialized_view.md) --- --- url: /en/docs/latest-lite/sql_reference/create_model.md --- # CREATE MODEL ## Function **CREATE MODEL** trains a machine learning model and saves the model. ## Precautions * The model name must be unique. Pay attention to the naming format. * The AI training duration fluctuates greatly, and in some cases, the training duration is long. If the duration specified by the GUC parameter **statement\_timeout** is too long, the training will be interrupted. You are advised to set **statement\_timeout** to **0** so that the statement execution duration is not limited. > \[!NOTE]NOTE > In the Lite scenario, openGauss provides this syntax, but the AI capabilities are unavailable. ## Syntax ``` CREATE MODEL model_name USING algorithm_name [FEATURES { {expression [ [ AS ] output_name ]} [, ...] }] [TARGET { {expression [ [ AS ] output_name ]} [, ...] }] FROM { table_name | select_query } WITH hyperparameter_name = { hyperparameter_value | DEFAULT } [, ...] } ``` ## Parameter Description * **model\_name** Name of the training model, which must be unique. Value range: a string. It must comply with the identifier naming convention. * **architecture\_name** Algorithm type of the training model. Value range: a string. Currently, the value can be **logistic\_regression**, **linear\_regression**, **svm\_classification**, or **kmeans**. * **attribute\_list** Enumerated input column name of the training model. Value range: a string. It must comply with the naming convention of data attributes. * **attribute\_name** Target column name of the retraining model in a supervised learning task (simple expression processing can be performed). Value range: a string. It must comply with the naming convention of data attributes. * **subquery** Data source. Value range: a string. It must comply with the SQL syntax of databases. * **hyper\_parameter\_name** Hyperparameter name of the machine learning model. Value range: a string. The value range varies according to the algorithm. * **hp\_value** Hyperparameter value. Value range: a string. The value range varies according to the algorithm. ## Examples ``` CREATE MODEL price_model USING logistic_regression FEATURES size, lot TARGET price FROM HOUSES (WITH learning_rate=0.88, max_iterations=default); ``` ## Helpful Links [DROP MODEL](drop_model.md) and [PREDICT BY](predict_by.md) --- --- url: /en/docs/latest/sql_reference/create_model.md --- # CREATE MODEL ## Function **CREATE MODEL** trains a machine learning model and saves the model. ## Precautions * The model name must be unique. Pay attention to the naming format. * The AI training duration fluctuates greatly, and in some cases, the training duration is long. If the duration specified by the GUC parameter **statement\_timeout** is too long, the training will be interrupted. You are advised to set **statement\_timeout** to **0** so that the statement execution duration is not limited. ## Syntax ``` CREATE MODEL model_name USING algorithm_name [FEATURES { {expression [ [ AS ] output_name ]} [, ...] }] [TARGET { {expression [ [ AS ] output_name ]} [, ...] }] FROM { table_name | select_query } WITH hyperparameter_name = { hyperparameter_value | DEFAULT } [, ...] } ``` ## Parameter Description * **model\_name** Name of the training model, which must be unique. Value range: a string. It must comply with the identifier naming convention. * **architecture\_name** Algorithm type of the training model. Value range: a string. Currently, the value can be **logistic\_regression**, **linear\_regression**, **svm\_classification**, or **kmeans**. * **attribute\_list** Enumerated input column name of the training model. Value range: a string. It must comply with the naming convention of data attributes. * **attribute\_name** Target column name of the retraining model in a supervised learning task (simple expression processing can be performed). Value range: a string. It must comply with the naming convention of data attributes. * **subquery** Data source. Value range: a string. It must comply with the SQL syntax of databases. * **hyper\_parameter\_name** Hyperparameter name of the machine learning model. Value range: a string. The value range varies depending on the algorithms. For details, see [Table 2](../characteristic_description/aifeature_guide/db4ai_query_for_model_training_and_prediction.md#table15985527185615). * **hp\_value** Hyperparameter value. Value range: a string. The value range varies depending on the algorithms. For details, see [Table 3](../characteristic_description/aifeature_guide/db4ai_query_for_model_training_and_prediction.md#table86881521502). ## Examples ``` CREATE MODEL price_model USING logistic_regression FEATURES size, lot TARGET price FROM HOUSES WITH learning_rate=0.88, max_iterations=default; ``` ## Helpful Links [DROP MODEL](drop_model.md) and [PREDICT BY](predict_by.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_model.md --- # CREATE MODEL ## 功能描述 训练机器学习模型并保存模型。 ## 注意事项 * 模型名称具有唯一性约束,注意命名格式。 * AI训练时长波动较大,在部分情况下训练运行时间较长,设置的GUC参数statement\_timeout时长过短会导致训练中断。建议statement\_timeout设置为0,不对语句执行时长进行限制。 > \[!NOTE]说明 > 轻量版场景下,openGauss提供此语法,但AI能力不可用。 ## 语法格式 ``` CREATE MODEL model_name USING architecture_name FEATURES { {attribute_list} } [TARGET attribute_name, [,attribute_name]*], FROM ([schema.]table_name | subquery) WITH (hyper_parameter_name [= {hp_value | DEFAULT}]) [, ...]*] ``` ## 参数说明 * **model\_name** 对训练模型进行命名,模型名称具有唯一性约束。 取值范围:字符串,需要符合标识符的命名规范。 * **architecture\_name** 训练模型的算法类型。 取值范围:字符型,当前支持:logistic\_regression、linear\_regression、svm\_classification、kmeans。 * **attribute\_list** 枚举训练模型的输入列名。 取值范围:字符型,需要符合数据属性名的命名规范。 * **attribute\_name** 在监督学习任务重训练模型的目标列名(可进行简单的表达式处理)。 取值范围:字符型,需要符合数据属性名的命名规范。 * **subquery** 数据源。 取值范围:字符串,符合数据库SQL语法。 * **hyper\_parameter\_name** 机器学习模型的超参名称。 取值范围:字符串,针对不同算法超参类型范围不同。 * **hp\_value** 超参数值。 取值范围:字符串,针对不同算法范围不同。 ## 示例 ``` --创建数据表 openGauss=# CREATE TABLE houses ( id INTEGER, tax INTEGER, bedroom INTEGER, bath DOUBLE PRECISION, price INTEGER, size INTEGER, lot INTEGER, mark text ); --插入训练数据 openGauss=# INSERT INTO houses(id, tax, bedroom, bath, price, size, lot, mark) VALUES (1,590,2,1,50000,770,22100,'a+'), (2,1050,3,2,85000,1410,12000,'a+'), (3,20,2,1,22500,1060,3500,'a-'), (4,870,2,2,90000,1300,17500,'a+'), (5,1320,3,2,133000,1500,30000,'a+'), (6,1350,2,1,90500,850,25700,'a-'), (7,2790,3,2.5,260000,2130,25000,'a+'), (8,680,2,1,142500,1170,22000,'a-'), (9,1840,3,2,160000,1500,19000,'a+'), (10,3680,4,2,240000,2790,20000,'a-'), (11,1660,3,1,87000,1030,17500,'a+'), (12,1620,3,2,118500,1250,20000,'a-'), (13,3100,3,2,140000,1760,38000,'a+'), (14,2090,2,3,148000,1550,14000,'a-'), (15,650,3,1.5,65000,1450,12000,'a-'); --训练模型 openGauss=# CREATE MODEL price_model USING logistic_regression FEATURES size, lot TARGET mark FROM HOUSES WITH learning_rate=0.88, max_iterations=default; --模型进行模型解析文本化任务 select gs_explain_model('price_model'); --删除模型 openGauss=# DROP MODEL price_model; --删除表 openGauss=# DROP TABLE houses; ``` ## 相关链接 [DROP MODEL](drop_model.md),[PREDICT BY](predict_by.md) --- --- url: /zh/docs/latest/sql_reference/create_model.md --- # CREATE MODEL ## 功能描述 训练机器学习模型并保存模型。 ## 注意事项 * 模型名称具有唯一性约束,注意命名格式。 * AI训练时长波动较大,在部分情况下训练运行时间较长,设置的GUC参数statement\_timeout时长过短会导致训练中断。建议statement\_timeout设置为0,不对语句执行时长进行限制。 ## 语法格式 ``` CREATE MODEL model_name USING architecture_name FEATURES { {attribute_list} } [TARGET attribute_name, [,attribute_name]*], FROM ([schema.]table_name | subquery) WITH (hyper_parameter_name [= {hp_value | DEFAULT}]) [, ...]*] ``` ## 参数说明 * **model\_name** 对训练模型进行命名,模型名称具有唯一性约束。 取值范围:字符串,需要符合标识符的命名规范。 * **architecture\_name** 训练模型的算法类型。 取值范围:字符型,当前支持:logistic\_regression、linear\_regression、svm\_classification、kmeans。 * **attribute\_list** 枚举训练模型的输入列名。 取值范围:字符型,需要符合数据属性名的命名规范。 * **attribute\_name** 在监督学习任务重训练模型的目标列名(可进行简单的表达式处理)。 取值范围:字符型,需要符合数据属性名的命名规范。 * **subquery** 数据源。 取值范围:字符串,符合数据库SQL语法。 * **hyper\_parameter\_name** 机器学习模型的超参名称。 取值范围:字符串,针对不同算法超参类型范围不同,取值范围详情请参考:[表2](../characteristic_description/aifeature_guide/db4ai_query_for_model_training_and_prediction.md#table15985527185615)。 * **hp\_value** 超参数值。 取值范围:字符串,针对不同算法范围不同,取值范围详情请参考:[表3](../characteristic_description/aifeature_guide/db4ai_query_for_model_training_and_prediction.md#table86881521502)。 ## 示例 ``` --创建数据表 openGauss=# CREATE TABLE houses ( id INTEGER, tax INTEGER, bedroom INTEGER, bath DOUBLE PRECISION, price INTEGER, size INTEGER, lot INTEGER, mark text ); --插入训练数据 openGauss=# INSERT INTO houses(id, tax, bedroom, bath, price, size, lot, mark) VALUES (1,590,2,1,50000,770,22100,'a+'), (2,1050,3,2,85000,1410,12000,'a+'), (3,20,2,1,22500,1060,3500,'a-'), (4,870,2,2,90000,1300,17500,'a+'), (5,1320,3,2,133000,1500,30000,'a+'), (6,1350,2,1,90500,850,25700,'a-'), (7,2790,3,2.5,260000,2130,25000,'a+'), (8,680,2,1,142500,1170,22000,'a-'), (9,1840,3,2,160000,1500,19000,'a+'), (10,3680,4,2,240000,2790,20000,'a-'), (11,1660,3,1,87000,1030,17500,'a+'), (12,1620,3,2,118500,1250,20000,'a-'), (13,3100,3,2,140000,1760,38000,'a+'), (14,2090,2,3,148000,1550,14000,'a-'), (15,650,3,1.5,65000,1450,12000,'a-'); --训练模型 openGauss=# CREATE MODEL price_model USING logistic_regression FEATURES size, lot TARGET mark FROM HOUSES WITH learning_rate=0.88, max_iterations=default; --模型进行模型解析文本化任务 select gs_explain_model('price_model'); --删除模型 openGauss=# DROP MODEL price_model; --删除表 openGauss=# DROP TABLE houses; ``` ## 相关链接 [DROP MODEL](drop_model.md),[PREDICT BY](predict_by.md) --- --- url: /en/docs/latest-lite/sql_reference/create_operator.md --- # CREATE OPERATOR ## Function CREATE OPERATOR defines a new operator. ## Precautions CREATE OPERATOR defines a new name operator. The user who defines the operator becomes the owner of the operator. If a schema name is given, the operator is created in the specified schema. Otherwise, it will be created in the current schema. The operator name is a character string consisting of the following characters: * * \* / < > = ~ ! @ # % ^ & | \` ? When selecting a name, note the following restrictions: * \-- and /\* cannot appear anywhere in the operator name, because they are regarded as the beginning of a comment. * A multi-character operator cannot end with + or - unless the name contains at least one of the following characters: \~ ! @ # % ^ & | \` ? * \=> The operator name is no longer used. Operator! = is mapped to <> when being entered. Therefore, the two names are always equivalent. At least one LEFTARG and one RIGHTARG must be defined. For binocular operators, both need to be defined. For the right operator, only LEFTARG needs to be defined. For the left operator, only RIGHTARG needs to be defined. Also, the function\_name procedure must have been defined with CREATE FUNCTION, and must be defined to accept the correct number of specified type parameters (one or two). Other clauses declare optional operator optimization clauses. Their meanings are defined in [Section 35.13](https://www.postgresql.org/docs/9.3/xoper-optimization.html). To create an operator, you must have the USAGE permission on the parameter type and return type, and the EXECUTE permission on the underlying function. If exchange or negative operators are specified, you must have them. ## Syntax ``` CREATE OPERATOR name ( PROCEDURE = function_name [, LEFTARG = left_type ] [, RIGHTARG = right_type ] [, COMMUTATOR = com_op ] [, NEGATOR = neg_op ] [, RESTRICT = res_proc ] [, JOIN = join_proc ] [, HASHES ] [, MERGES ] ) ``` ## Parameter Description * **name** Operator to be defined. The available characters are listed above. The name can be schema-qualified, for example, CREATE OPERATOR myschema.+ (...). If there is no schema, the operator is created in the current schema. Two operators in the same schema can have the same name as long as they operate on different data types. This is a reloading process. * **function\_name** Function used to implement the operator. * **left\_type** Parameter data type on the left of the operator, if any. This parameter can be omitted if the left operator is used. * **right\_type** Parameter data type on the right of the operator, if any. This parameter can be omitted if the right-view operator is used. * **com\_op** Exchange operator corresponding to the operator. * **neg\_op** Negative operator corresponding to the operator. * **res\_proc** This operator constrains the selectivity evaluation function. * **join\_proc** This operator joins the selectivity evaluation function. * **HASHES** Indicates that the operator supports hash joins. * **MERGES** Indicates that this operator supports a merge join. Use the OPERATOR() syntax to provide a schema-qualified operator name in com\_op or other optional parameters. For example: ``` COMMUTATOR = OPERATOR(myschema.===) , ``` ## Example The following command defines a new operator: equal area for the box data type. ``` CREATE OPERATOR === ( LEFTARG = box, RIGHTARG = box, PROCEDURE = area_equal_procedure, COMMUTATOR = ===, NEGATOR = !==, RESTRICT = area_restriction_procedure, JOIN = area_join_procedure, HASHES, MERGES ); ``` --- --- url: /en/docs/latest/sql_reference/create_operator.md --- # CREATE OPERATOR ## Function CREATE OPERATOR defines a new operator. ## Precautions CREATE OPERATOR defines a new name operator. The user who defines the operator becomes the owner of the operator. If a schema name is given, the operator is created in the specified schema. Otherwise, it will be created in the current schema. The operator name is a character string consisting of the following characters: * * \* / < > = ~ ! @ # % ^ & | \` ? When selecting a name, note the following restrictions: * \-- and /\* cannot appear anywhere in the operator name, because they are regarded as the beginning of a comment. * A multi-character operator cannot end with + or - unless the name contains at least one of the following characters: \~ ! @ # % ^ & | \` ? * \=> The operator name is no longer used. Operator! = is mapped to <> when being entered. Therefore, the two names are always equivalent. At least one LEFTARG and one RIGHTARG must be defined. For binocular operators, both need to be defined. For the right operator, only LEFTARG needs to be defined. For the left operator, only RIGHTARG needs to be defined. Also, the function\_name procedure must have been defined with CREATE FUNCTION, and must be defined to accept the correct number of specified type parameters (one or two). Other clauses declare optional operator optimization clauses. Their meanings are defined in [Section 35.13](https://www.postgresql.org/docs/9.3/xoper-optimization.html). To create an operator, you must have the USAGE permission on the parameter type and return type, and the EXECUTE permission on the underlying function. If exchange or negative operators are specified, you must have them. ## Syntax ``` CREATE OPERATOR name ( PROCEDURE = function_name [, LEFTARG = left_type ] [, RIGHTARG = right_type ] [, COMMUTATOR = com_op ] [, NEGATOR = neg_op ] [, RESTRICT = res_proc ] [, JOIN = join_proc ] [, HASHES ] [, MERGES ] ) ``` ## Parameter Description * **name** Operator to be defined. The available characters are listed above. The name can be schema-qualified, for example, CREATE OPERATOR myschema.+ (...). If there is no schema, the operator is created in the current schema. Two operators in the same schema can have the same name as long as they operate on different data types. This is a reloading process. * **function\_name** Function used to implement the operator. * **left\_type** Parameter data type on the left of the operator, if any. This parameter can be omitted if the left operator is used. * **right\_type** Parameter data type on the right of the operator, if any. This parameter can be omitted if the right-view operator is used. * **com\_op** Exchange operator corresponding to the operator. * **neg\_op** Negative operator corresponding to the operator. * **res\_proc** This operator constrains the selectivity evaluation function. * **join\_proc** This operator joins the selectivity evaluation function. * **HASHES** Indicates that the operator supports hash joins. * **MERGES** Indicates that this operator supports a merge join. Use the OPERATOR() syntax to provide a schema-qualified operator name in com\_op or other optional parameters. For example: ``` COMMUTATOR = OPERATOR(myschema.===) , ``` ## Example The following command defines a new operator: equal area for the box data type. ``` CREATE OPERATOR === ( LEFTARG = box, RIGHTARG = box, PROCEDURE = area_equal_procedure, COMMUTATOR = ===, NEGATOR = !==, RESTRICT = area_restriction_procedure, JOIN = area_join_procedure, HASHES, MERGES ); ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_operator.md --- # CREATE OPERATOR ## 功能描述 定义一个新操作符。 ## 注意事项 CREATE OPERATOR定义一个新的 name操作符。 定义该操作符的用户将成为其所有者。如果给出了一个模式名, 那么该操作符将在指定的模式中创建。否则它会在当前模式中创建。 另外,只有初始化用户可以在 public schema 下创建操作符。 操作符 name 是一个由下列字符组成的字符串: * * \* / < > = ~ ! @ # % ^ & | \` ? 选择名字的时候有几个限制: * \--和/\*不能在操作符名的任何地方出现, 因为它们会被认为是一个注释的开始。 * 一个多字符的操作符不能以+或-结尾, 除非该名字还包含至少下面字符之一: \~ ! @ # % ^ & | \` ? * \=> 作为一个操作符名的使用已经废弃了。 操作符!=在输入时映射成<>, 因此这两个名称总是等价的。 至少需要定义一个LEFTARG和RIGHTARG。对于双目操作符来说, 两者都需要定义。对右目操作符来说,只需要定义LEFTARG, 而对于左目操作符来说,只需要定义RIGHTARG。 同样,function\_name 过程必须已经用CREATE FUNCTION定义过, 而且必须定义为接受正确数量的指定类型参数(一个或是两个)。 其它子句声明可选的操作符优化子句。他们的含义在[第 35.13 节](http://postgres.cn/docs/9.3/xoper-optimization.html)里定义。 要想能够创建一个操作符,你必须在参数类型和返回类型上有USAGE权限, 还要在底层函数上有EXECUTE权限。如果指定了交换或者负操作符, 你必须拥有这些操作符。 ## 语法格式 ``` CREATE OPERATOR name ( PROCEDURE = function_name [, LEFTARG = left_type ] [, RIGHTARG = right_type ] [, COMMUTATOR = com_op ] [, NEGATOR = neg_op ] [, RESTRICT = res_proc ] [, JOIN = join_proc ] [, HASHES ] [, MERGES ] ) ``` ## 参数说明 * **name** 要定义的操作符。可用的字符见上文。其名字可以用模式修饰, 比如CREATE OPERATOR myschema.+ (...)。如果没有模式, 则在当前模式中创建操作符。同一个模式中的两个操作符可以有一样的名字, 只要他们操作不同的数据类型。这是一个重载过程。 * **function\_name** 用于实现该操作符的函数。 * **left\_type** 操作符左边的参数数据类型,如果存在的话。如果是左目操作符,这个参数可以省略。 * **right\_type** 操作符右边的参数数据类型,如果存在的话。如果是右目操作符,这个参数可以省略。 * **com\_op** 该操作符对应的交换操作符。 * **neg\_op** 该操作符对应的负操作符。 * **res\_proc** 此操作符约束选择性评估函数。 * **join\_proc** 此操作符连接选择性评估函数。 * **HASHES** 表明此操作符支持 Hash 连接。 * **MERGES** 表明此操作符可以支持一个融合连接。 使用OPERATOR()语法在com\_op 或者其它可选参数里给出一个模式修饰的操作符名,比如: ``` COMMUTATOR = OPERATOR(myschema.===) , ``` ## 示例 下面命令定义一个新操作符:面积相等,用于box数据类型。 ``` CREATE OPERATOR === ( LEFTARG = box, RIGHTARG = box, PROCEDURE = area_equal_procedure, COMMUTATOR = ===, NEGATOR = !==, RESTRICT = area_restriction_procedure, JOIN = area_join_procedure, HASHES, MERGES ); ``` --- --- url: /zh/docs/latest/sql_reference/create_operator.md --- # CREATE OPERATOR ## 功能描述 定义一个新操作符。 ## 注意事项 CREATE OPERATOR定义一个新的 name操作符。 定义该操作符的用户将成为其所有者。如果给出了一个模式名, 那么该操作符将在指定的模式中创建。否则它会在当前模式中创建。 另外,只有初始化用户可以在 public schema 下创建操作符。 操作符 name 是一个由下列字符组成的字符串: * * \* / < > = ~ ! @ # % ^ & | \` ? 选择名字的时候有几个限制: * \--和/\*不能在操作符名的任何地方出现, 因为它们会被认为是一个注释的开始。 * 一个多字符的操作符不能以+或-结尾, 除非该名字还包含至少下面字符之一: \~ ! @ # % ^ & | \` ? * \=> 作为一个操作符名的使用已经废弃了。 操作符!=在输入时映射成<>, 因此这两个名称总是等价的。 至少需要定义一个LEFTARG和RIGHTARG。对于双目操作符来说, 两者都需要定义。对右目操作符来说,只需要定义LEFTARG, 而对于左目操作符来说,只需要定义RIGHTARG。 同样,function\_name 过程必须已经用CREATE FUNCTION定义过, 而且必须定义为接受正确数量的指定类型参数(一个或是两个)。 其它子句声明可选的操作符优化子句。他们的含义在[第 35.13 节](http://postgres.cn/docs/9.3/xoper-optimization.html)里定义。 要想能够创建一个操作符,你必须在参数类型和返回类型上有USAGE权限, 还要在底层函数上有EXECUTE权限。如果指定了交换或者负操作符, 你必须拥有这些操作符。 ## 语法格式 ``` CREATE OPERATOR name ( PROCEDURE = function_name [, LEFTARG = left_type ] [, RIGHTARG = right_type ] [, COMMUTATOR = com_op ] [, NEGATOR = neg_op ] [, RESTRICT = res_proc ] [, JOIN = join_proc ] [, HASHES ] [, MERGES ] ) ``` ## 参数说明 * **name** 要定义的操作符。可用的字符见上文。其名字可以用模式修饰, 比如CREATE OPERATOR myschema.+ (...)。如果没有模式, 则在当前模式中创建操作符。同一个模式中的两个操作符可以有一样的名字, 只要他们操作不同的数据类型。这是一个重载过程。 * **function\_name** 用于实现该操作符的函数。 * **left\_type** 操作符左边的参数数据类型,如果存在的话。如果是左目操作符,这个参数可以省略。 * **right\_type** 操作符右边的参数数据类型,如果存在的话。如果是右目操作符,这个参数可以省略。 * **com\_op** 该操作符对应的交换操作符。 * **neg\_op** 该操作符对应的负操作符。 * **res\_proc** 此操作符约束选择性评估函数。 * **join\_proc** 此操作符连接选择性评估函数。 * **HASHES** 表明此操作符支持 Hash 连接。 * **MERGES** 表明此操作符可以支持一个融合连接。 使用OPERATOR()语法在com\_op 或者其它可选参数里给出一个模式修饰的操作符名,比如: ``` COMMUTATOR = OPERATOR(myschema.===) , ``` ## 示例 下面命令定义一个新操作符:面积相等,用于box数据类型。 ``` CREATE OPERATOR === ( LEFTARG = box, RIGHTARG = box, PROCEDURE = area_equal_procedure, COMMUTATOR = ===, NEGATOR = !==, RESTRICT = area_restriction_procedure, JOIN = area_join_procedure, HASHES, MERGES ); ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_operator_family.md --- # CREATE OPERATOR FAMILY ## 功能描述 定义一个新的运算符族。 ## 语法格式 ```txt CREATE OPERATOR FAMILY name USING index_method ``` ## 参数说明 * `name` 要创建的运算符族名称,可使用模式修饰。 * `index_method` 该运算符族适用的索引方法。 ## 示例 ```sql CREATE OPERATOR FAMILY family_name USING btree; ``` --- --- url: /zh/docs/latest/sql_reference/create_operator_family.md --- # CREATE OPERATOR FAMILY ## 功能描述 定义一个新的运算符族。 ## 语法格式 ```txt CREATE OPERATOR FAMILY name USING index_method ``` ## 参数说明 * `name` 要创建的运算符族名称,可使用模式修饰。 * `index_method` 该运算符族适用的索引方法。 ## 示例 ```sql CREATE OPERATOR FAMILY family_name USING btree; ``` --- --- url: /en/docs/latest-lite/sql_reference/create_package.md --- # CREATE PACKAGE ## Function **CREATE PACKAGE** creates a package. ## Precautions * The package can be used only in centralized databases and cannot be used in distributed databases. * The functions or stored procedures declared in the package specification must be defined in the package body. * During instantiation, the stored procedure with **commit** or **rollback** cannot be invoked. * Package functions cannot be invoked in triggers. * Variables in a package cannot be directly used in external SQL statements. * Private variables and stored procedures in a package cannot be invoked outside the package. * Usage that other stored procedures do not support are not supported. For example, if **commit** or **rollback** cannot be invoked in a function, **commit** or **rollback** cannot be invoked in the function of a package. * The name of a schema cannot be the same as that of a package. * Only A-version stored procedures and function definitions are supported. * Variables with the same name in a package, including parameters with the same name in a package, are not supported. * The global variables in a package are at the session level. The variables in packages cannot be shared in different sessions. * When a function of an autonomous transaction is called in a package, the cursor variables in the package and recursive functions that use the cursor variables in the package are not allowed. * The package does not declare the ref cursor variables. * The default permission on a package is **SECURITY INVOKER**. To change the default permission to **SECURITY DEFINER**, set the GUC parameter **behavior\_compat\_options** to **'plsql\_security\_definer'**. * A user granted with the **CREATE ANY PACKAGE** permission can create packages in the public and user schemas. * If the name of a package to be created contains special characters, the special characters cannot contain spaces. You are advised to set the GUC parameter **behavior\_compat\_options** to **"skip\_insert\_gs\_source"**. Otherwise, an error may occur. ## Syntax * **CREATE PACKAGE SPECIFICATION** ``` CREATE [ OR REPLACE ] PACKAGE [ schema. ] package_name [ invoker_rights_clause ] { IS | AS } item_list_1 END package_name; invoker_rights_clause can be declared as AUTHID DEFINER or AUTHID CURRENT_USER, which indicate the definer permission and invoker permission, respectively. item_list_1 can be a declared variable, stored procedure, or function. ``` The package specification declares public variables, functions, and exceptions in a package, which can be invoked by external functions or stored procedures. It can only declare stored procedures and functions but cannot define them. * **CREATE PACKAGE BODY** ``` CREATE [ OR REPLACE ] PACKAGE BODY [ schema. ] package_name { IS | AS } declare_section [ initialize_section ] END package_name; ``` The package body defines private variables and functions in a package. If a variable or function is not declared by the package specification, it is a private variable or function. The package body also has an initialization part to initialize the package. For details, see the example. ## Examples * **CREATE PACKAGE SPECIFICATION** ``` CREATE OR REPLACE PACKAGE emp_bonus IS var1 int:=1;-- Public variable var2 int:=2; PROCEDURE testpro1(var3 int);-- Public stored procedure, which can be called by external systems. END emp_bonus; / ``` * **CREATE PACKAGE BODY** ``` drop table if exists test1; create or replace package body emp_bonus is var3 int:=3; var4 int:=4; procedure testpro1(var3 int) is begin create table if not exists test1(col1 int); insert into test1 values(var1); insert into test1 values(var4); end; begin: --The instantiation starts. var4:=9; testpro1(var4); end emp_bonus; / ``` * Example of **ALTER PACKAGE OWNER** ``` -- Change the owner of PACKAGE emp_bonus to omm. ALTER PACKAGE emp_bonus OWNER TO omm; ``` * Example of calling a package ``` call emp_bonus.testpro1(1); -- Use **call** to call the stored procedure of a package. select emp_bonus.testpro1(1); -- Use **select** to call the stored procedure of a package. --Call the stored procedure of a package in an anonymous block. begin emp_bonus.testpro1(1); end; / ``` --- --- url: /en/docs/latest/sql_reference/create_package.md --- # CREATE PACKAGE ## Function **CREATE PACKAGE** creates a package. ## Precautions * The package can be used only in centralized databases and cannot be used in distributed databases. * The functions or stored procedures declared in the package specification must be defined in the package body. * During instantiation, the stored procedure with **commit** or **rollback** cannot be invoked. * Package functions cannot be invoked in triggers. * Variables in a package cannot be directly used in external SQL statements. * Private variables and stored procedures in a package cannot be invoked outside the package. * Usage that other stored procedures do not support are not supported. For example, if **commit** or **rollback** cannot be invoked in a function, **commit** or **rollback** cannot be invoked in the function of a package. * The name of a schema cannot be the same as that of a package. * Only A-version stored procedures and function definitions are supported. * Variables with the same name in a package, including parameters with the same name in a package, are not supported. * The global variables in a package are at the session level. The variables in packages cannot be shared in different sessions. * When a function of an autonomous transaction is called in a package, the cursor variables in the package and recursive functions that use the cursor variables in the package are not allowed. * The package does not declare the ref cursor variables. * The default permission on a package is **SECURITY INVOKER**. To change the default permission to **SECURITY DEFINER**, set the GUC parameter **behavior\_compat\_options** to **'plsql\_security\_definer'**. * A user granted with the **CREATE ANY PACKAGE** permission can create packages in the public and user schemas. * If the name of a package to be created contains special characters, the special characters cannot contain spaces. You are advised to set the GUC parameter **behavior\_compat\_options** to **"skip\_insert\_gs\_source"**. Otherwise, an error may occur. ## Syntax * **CREATE PACKAGE SPECIFICATION** ``` CREATE [ OR REPLACE ] PACKAGE [ schema. ] package_name [ invoker_rights_clause ] { IS | AS } item_list_1 END package_name; invoker_rights_clause can be declared as AUTHID DEFINER or AUTHID CURRENT_USER, which indicate the definer permission and invoker permission, respectively. item_list_1 can be a declared variable, stored procedure, or function. ``` The package specification declares public variables, functions, and exceptions in a package, which can be invoked by external functions or stored procedures. It can only declare stored procedures and functions but cannot define them. * **CREATE PACKAGE BODY** ``` CREATE [ OR REPLACE ] PACKAGE BODY [ schema. ] package_name { IS | AS } declare_section [ initialize_section ] END package_name; ``` The package body defines private variables and functions in a package. If a variable or function is not declared by the package specification, it is a private variable or function. The package body also has an initialization part to initialize the package. For details, see the example. ## Examples * **CREATE PACKAGE SPECIFICATION** ``` CREATE OR REPLACE PACKAGE emp_bonus IS var1 int:=1;-- Public variable var2 int:=2; PROCEDURE testpro1(var3 int);-- Public stored procedure, which can be called by external systems. END emp_bonus; / ``` * **CREATE PACKAGE BODY** ``` drop table if exists test1; create or replace package body emp_bonus is var3 int:=3; var4 int:=4; procedure testpro1(var3 int) is begin create table if not exists test1(col1 int); insert into test1 values(var1); insert into test1 values(var4); end; begin: --The instantiation starts. var4:=9; testpro1(var4); end emp_bonus; / ``` * Example of **ALTER PACKAGE OWNER** ``` -- Change the owner of PACKAGE emp_bonus to omm. ALTER PACKAGE emp_bonus OWNER TO omm; ``` * Example of calling a package ``` call emp_bonus.testpro1(1); -- Use **call** to call the stored procedure of a package. select emp_bonus.testpro1(1); -- Use **select** to call the stored procedure of a package. --Call the stored procedure of a package in an anonymous block. begin emp_bonus.testpro1(1); end; / ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_package.md --- # CREATE PACKAGE ## 功能描述 创建一个新的PACKAGE。 ## 注意事项 * package只支持集中式,无法在分布式中使用。 * 在package specification中声明过的函数或者存储过程,必须在package body中找到定义。 * 在实例化中,无法调用带有commit/rollback的存储过程。 * 不能在Trigger中调用package函数。 * 不能在外部SQL中直接使用package当中的变量。 * 不允许在package外部调用package的私有变量和存储过程。 * 不支持其它存储过程不支持的用法,例如,在function中不允许调用commit/rollback,则package的function中同样无法调用commit/rollback。 * 不支持schema与package同名。 * 只支持A风格的存储过程和函数定义。 * 不支持package内有同名变量,包括包内同名参数。 * package的全局变量为session级,不同session之间package的变量不共享。 * package中调用自治事务的函数,不允许使用package中的cursor变量,以及递归的使用package中cursor变量的函数。 * package中不支持声明ref cursor变量。 * package默认为SECURITY INVOKER权限,如果想将默认行为改为SECURITY DEFINER权限,需要设置guc参数behavior\_compat\_options='plsql\_security\_definer'。 * 被授予CREATE ANY PACKAGE权限的用户,可以在public模式和用户模式下创建PACKAGE。 * 如果需要创建带有特殊字符的package名,特殊字符中不能含有空格,并且最好设置GUC参数behavior\_compat\_options="skip\_insert\_gs\_source",否则可能引起报错。 * 允许创建package时忽略依赖关系进行创建,并对未定义的类型/存储过程/函数/包变量提供告警功能,需要设置guc参数behavior\_compat\_options='plpgsql\_dependency'。 ## 语法格式 * CREATE PACKAGE SPECIFICATION语法格式 ``` CREATE [ OR REPLACE ] PACKAGE [ schema. ]package_name [ invoker_rights_clause ] { IS | AS } item_list_1 END package_name; invoker_rights_clause可以被声明为AUTHID DEFINER或者AUTHID CURRENT_USER,分别为定义者权限和调用者权限。 item_list_1可以为声明的变量或者存储过程以及函数。 ``` PACKAGE SPECIFICATION(包规格)声明了包内的公有变量、函数、异常等,可以被外部函数或者存储过程调用。在PACKAGE SPECIFICATION中只能声明存储过程,函数,不能定义存储过程或者函数。 * CREATE PACKAGE BODY语法格式。 ``` CREATE [ OR REPLACE ] PACKAGE BODY [ schema. ]package_name { IS | AS } declare_section [ initialize_section ] END package_name; ``` PACKAGE BODY(包体内)定义了包的私有变量,函数等。如果变量或者函数没有在PACKAGE SPECIFICATION中声明过,那么这个变量或者函数则为私有变量或者函数。 PACKAGE BODY也可以声明实例化部分,用来初始化package,详见示例。 ## 参数说明 * OR REPLACE 当存在同名的PACKAGE时,替换原来的定义。 * package\_name 创建的PACKAGE名称,可以带有模式名。 取值范围:字符串,要符合标识符的命名规范。 * invoker\_rights\_clause 可以被声明为AUTHID DEFINER或者AUTHID CURRENT\_USER,分别为定义者权限和调用者权限。 * item\_list\_1 声明的变量、存储过程、函数等。 * declare\_section 声明部分,PACKAGE SPECIFICATION中声明的变量、存储过程、函数的具体定义。 * initialize\_section 初始化变量并设置一次性的步骤。首次引用包时,对于每个会话包初始化部分中的语句会执行一次。 ## 示例 * CREATE PACKAGE SPECIFICATION示例 ``` CREATE OR REPLACE PACKAGE emp_bonus IS var1 int:=1;--公有变量 var2 int:=2; PROCEDURE testpro1(var3 int);--公有存储过程,可以被外部调用 END emp_bonus; / ``` * CREATE PACKAGE BODY示例 ``` drop table if exists test1; create or replace package body emp_bonus is var3 int:=3; var4 int:=4; procedure testpro1(var3 int) is begin create table if not exists test1(col1 int); insert into test1 values(var1); insert into test1 values(var4); end; begin --实例化开始 var4:=9; testpro1(var4); end emp_bonus; / ``` * ALTER PACKAGE OWNER示例 ``` --将PACKAGE emp_bonus的所属者改为omm ALTER PACKAGE emp_bonus OWNER TO omm; ``` - 调用PACKAGE示例 ``` call emp_bonus.testpro1(1); --使用call调用package存储过程 select emp_bonus.testpro1(1); --使用select调用package存储过程 --匿名块里调用package存储过程 begin emp_bonus.testpro1(1); end; / ``` --- --- url: /zh/docs/latest/sql_reference/create_package.md --- # CREATE PACKAGE ## 功能描述 创建一个新的PACKAGE。 ## 注意事项 * package只支持集中式,无法在分布式中使用。 * 在package specification中声明过的函数或者存储过程,必须在package body中找到定义。 * 在实例化中,无法调用带有commit/rollback的存储过程。 * 不能在Trigger中调用package函数。 * 不能在外部SQL中直接使用package当中的变量。 * 不允许在package外部调用package的私有变量和存储过程。 * 不支持其它存储过程不支持的用法,例如,在function中不允许调用commit/rollback,则package的function中同样无法调用commit/rollback。 * 不支持schema与package同名。 * 只支持A风格的存储过程和函数定义。 * 不支持package内有同名变量,包括包内同名参数。 * package的全局变量为session级,不同session之间package的变量不共享。 * package中调用自治事务的函数,不允许使用package中的cursor变量,以及递归的使用package中cursor变量的函数。 * package中不支持声明ref cursor变量。 * package默认为SECURITY INVOKER权限,如果想将默认行为改为SECURITY DEFINER权限,需要设置guc参数behavior\_compat\_options='plsql\_security\_definer'。 * 被授予CREATE ANY PACKAGE权限的用户,可以在public模式和用户模式下创建PACKAGE。 * 如果需要创建带有特殊字符的package名,特殊字符中不能含有空格,并且最好设置GUC参数behavior\_compat\_options="skip\_insert\_gs\_source",否则可能引起报错。 * 允许创建package时忽略依赖关系进行创建,并对未定义的类型/存储过程/函数/包变量提供告警功能,需要设置guc参数behavior\_compat\_options='plpgsql\_dependency'。 ## 语法格式 * CREATE PACKAGE SPECIFICATION语法格式。 ``` CREATE [ OR REPLACE ] PACKAGE [ schema. ]package_name [ invoker_rights_clause ] { IS | AS } item_list_1 END package_name; invoker_rights_clause可以被声明为AUTHID DEFINER或者AUTHID CURRENT_USER,分别为定义者权限和调用者权限。 item_list_1可以为声明的变量或者存储过程以及函数。 ``` PACKAGE SPECIFICATION(包规格)声明了包内的公有变量、函数、异常等,可以被外部函数或者存储过程调用。在PACKAGE SPECIFICATION中只能声明存储过程、函数,不能定义存储过程或者函数。 * CREATE PACKAGE BODY语法格式。 ``` CREATE [ OR REPLACE ] PACKAGE BODY [ schema. ]package_name { IS | AS } declare_section [ initialize_section ] END package_name; ``` PACKAGE BODY(包体内)定义了包的私有变量、函数等。如果变量或者函数没有在PACKAGE SPECIFICATION中声明过,那么这个变量或者函数则为私有变量或者函数。 PACKAGE BODY也可以声明实例化部分,用来初始化package,详见示例。 ## 参数说明 * OR REPLACE 当存在同名的PACKAGE时,替换原来的定义。 * package\_name 创建的PACKAGE名称,可以带有模式名。 取值范围:字符串,要符合标识符的命名规范。 * invoker\_rights\_clause 可以被声明为AUTHID DEFINER或者AUTHID CURRENT\_USER,分别为定义者权限和调用者权限。 * item\_list\_1 声明的变量、存储过程、函数等。 * declare\_section 声明部分,PACKAGE SPECIFICATION中声明的变量、存储过程、函数的具体定义。 * initialize\_section 初始化变量并设置一次性的步骤。首次引用包时,对于每个会话包初始化部分中的语句会执行一次。 ## 示例 * CREATE PACKAGE SPECIFICATION示例 ``` CREATE OR REPLACE PACKAGE emp_bonus IS var1 int:=1;--公有变量 var2 int:=2; PROCEDURE testpro1(var3 int);--公有存储过程,可以被外部调用 END emp_bonus; / ``` * CREATE PACKAGE BODY示例 ``` drop table if exists test1; create or replace package body emp_bonus is var3 int:=3; var4 int:=4; procedure testpro1(var3 int) is begin create table if not exists test1(col1 int); insert into test1 values(var1); insert into test1 values(var4); end; begin --实例化开始 var4:=9; testpro1(var4); end emp_bonus; / ``` * ALTER PACKAGE OWNER示例 ``` --将PACKAGE emp_bonus的所属者改为omm ALTER PACKAGE emp_bonus OWNER TO omm; ``` - 调用PACKAGE示例 ``` call emp_bonus.testpro1(1); --使用call调用package存储过程 select emp_bonus.testpro1(1); --使用select调用package存储过程 --匿名块里调用package存储过程 begin emp_bonus.testpro1(1); end; / ``` ## 相关链接 [DROP PACKAGE](drop_package.md) , [ALTER PACKAGE](alter_package.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-CREATE-PROC.md --- # CREATE PROC ## 功能描述 创建一个新的存储过程。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。原openGauss的CREATE PROCEDURE语法请参考章节[CREATE PROCEDURE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_procedure.html)。 * 新增支持通过CREATE PROC方式创建存储过程,功能和CREATE PROCEDURE方式保持一致。 ## 语法格式 ``` CREATE [ OR REPLACE ] { PROCEDURE | PROC } procedure_name [ ( {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] { IS | AS } plsql_body / ``` ## 参数说明 * **PROC** 新增通过CREATE PROC方式创建存储过程,功能和CREATE PROCEDURE方式保持一致。 ## 示例 ```sql create schema test_proc; set current_schema to test_proc; create procedure p1() is begin RAISE INFO 'call procedure: p1'; end; / create proc p2() is begin RAISE INFO 'call procedure: p2'; end; / \df p1(); List of functions Schema | Name | Result data type | Argument data types | Type | fencedmode | propackage | prokind -----------+------+------------------+---------------------+--------+------------+------------+--------- test_proc | p1 | void | | normal | f | f | p (1 row) \df p2(); List of functions Schema | Name | Result data type | Argument data types | Type | fencedmode | propackage | prokind -----------+------+------------------+---------------------+--------+------------+------------+--------- test_proc | p2 | void | | normal | f | f | p (1 row) call test_proc.p1(); INFO: call procedure: p1 p1 ---- (1 row) call test_proc.p2(); INFO: call procedure: p2 p2 ---- (1 row) ``` ## 相关链接 [CREATE PROCEDURE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_procedure.html) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-CREATE-PROC.md --- # CREATE PROC ## 功能描述 创建一个新的存储过程。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。原openGauss的CREATE PROCEDURE语法请参考章节[CREATE PROCEDURE](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_procedure.html)。 * 新增支持通过CREATE PROC方式创建存储过程,功能和CREATE PROCEDURE方式保持一致。 ## 语法格式 ``` CREATE [ OR REPLACE ] { PROCEDURE | PROC } procedure_name [ ( {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] { IS | AS } plsql_body / ``` ## 参数说明 * **PROC** 新增通过CREATE PROC方式创建存储过程,功能和CREATE PROCEDURE方式保持一致。 ## 示例 ```sql create schema test_proc; set current_schema to test_proc; create procedure p1() is begin RAISE INFO 'call procedure: p1'; end; / create proc p2() is begin RAISE INFO 'call procedure: p2'; end; / \df p1(); List of functions Schema | Name | Result data type | Argument data types | Type | fencedmode | propackage | prokind -----------+------+------------------+---------------------+--------+------------+------------+--------- test_proc | p1 | void | | normal | f | f | p (1 row) \df p2(); List of functions Schema | Name | Result data type | Argument data types | Type | fencedmode | propackage | prokind -----------+------+------------------+---------------------+--------+------------+------------+--------- test_proc | p2 | void | | normal | f | f | p (1 row) call test_proc.p1(); INFO: call procedure: p1 p1 ---- (1 row) call test_proc.p2(); INFO: call procedure: p2 p2 ---- (1 row) ``` ## 相关链接 [CREATE PROCEDURE](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_procedure.html) --- --- url: /en/docs/latest-lite/sql_reference/create_procedure.md --- # CREATE PROCEDURE ## Function **CREATE PROCEDURE** creates a stored procedure. ## Precautions * If the parameters or return values of a stored procedure have precision, the precision is not checked. * When creating a stored procedure, you are advised to explicitly specify the schemas of all operations on table objects in the stored procedure definition. Otherwise, the stored procedure may fail to be executed. * **current\_schema** and **search\_path** specified by **SET** during stored procedure creation are invalid. **search\_path** and **current\_schema** before and after function execution should be the same. * If a stored procedure has output parameters, the **SELECT** statement uses the default values of the output parameters when calling the procedure. When the **CALL** statement calls the stored procedure or a non-overloaded function, output parameters must be specified. When the **CALL** statement calls an overloaded **PACKAGE** function, it can use the default values of the output parameters. For details, see examples in [CALL](call.md). * A stored procedure with the **PACKAGE** attribute can use overloaded functions. * When you create a procedure, you cannot insert aggregate functions or other functions out of the average function. * When stored procedures without parameters are called in another stored procedure, you can omit brackets and call stored procedures using their names directly. * When functions with output parameters are called in a stored procedure which is an assignment expression, you can omit the output parameters of the called functions. * The stored procedure supports viewing, exporting, and importing parameter comments. * The stored procedure supports viewing, exporting, and importing parameter comments between IS/AS and plsql\_body. * The default permission on a stored procedure is **SECURITY INVOKER**. If you want to change the default permission to **SECURITY DEFINER**, you need to set the GUC parameter **behavior\_compat\_options** to **'plsql\_security\_definer'**. For details about the S**ECURITY DEFINER** permission, see section "Permission Control" in *Security Hardening Guide*. * Users granted with the **CREATE ANY FUNCTION** permission can create or replace stored procedures in the user schemas. * **out/inout** must be set to a variable but not a constant. * In a centralized environment, if you want to call a stored procedure with the same in parameters but different out parameters, you need to set the GUC parameter **behavior\_compat\_options** to **'proc\_outparam\_override'**. After the parameter is enabled, you must add the out parameters no matter whether you use the SELECT or CALL statement to call the stored procedure. After the parameter is enabled, you cannot use **perform** to call a stored procedure or function. ## Syntax ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name [ ( {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] [ { IMMUTABLE | STABLE | VOLATILE } | { SHIPPABLE | NOT SHIPPABLE } | {PACKAGE} | [ NOT ] LEAKPROOF | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | SET configuration_parameter { TO value | = value | FROM CURRENT } | COMMENT text ][ ... ] { IS | AS } plsql_body / ``` ## Parameter Description * **OR REPLACE** Replaces the original definition when two stored procedures are with the same name. * **procedure\_name** Specifies the name of the stored procedure that is created (optionally with schema names). Value range: a string. It must comply with the identifier naming convention. * **argmode** Specifies the mode of an argument. > \[!TIP]NOTICE > **VARIADIC** specifies parameters of the array type. Value range: **IN**, **OUT**, **INOUT**, and **VARIADIC**. The default value is **IN**. Only the parameters in **OUT** mode can follow the **VARIADIC** parameter. * **argname** Specifies the argument name. Value range: a string. It must comply with the identifier naming convention. * **argtype** Specifies the type of an argument. **%TYPE** or **%ROWTYPE** can be used to indirectly reference a variable or table type. For details, see [Variable Definition Statements](variable_definition_statements.md). Value range: a valid data type * **configuration\_parameter** * **value** Sets the specified configuration parameter to a specified value. If the **value** is **DEFAULT**, the default setting is used in the new session. **OFF** disables the setting. Value range: a string * DEFAULT * OFF * Specified default value * **from current** Uses the value of **configuration\_parameter** of the current session. * **IMMUTABLE, STABLE,**... Specifies a constraint. The function of each parameter is similar to that of **CREATE FUNCTION**. For details, see [CREATE FUNCTION](create_function.md). * **COMMENT text** Comments a stored procedure. * **plsql\_body** Specifies the PL/SQL stored procedure body. > \[!TIP]NOTICE > When you create a user, or perform other operations requiring password input in a stored procedure, the system catalog and CSV log record the password in plaintext. Therefore, you are advised not to perform such operations in the stored procedure. > \[!NOTE]NOTE > No specific order is applied to **argname** and **argname**. The following order is advised: **argname**, **argmode**, and **argtype**. ## Helpful Links [DROP PROCEDURE](drop_procedure.md) ## Suggestions * analyse | analyze * Do not run **ANALYZE** in a transaction or anonymous block. * Do not run **ANALYZE** in a function or stored procedure. --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-create-procedure.md --- # CREATE PROCEDURE ## Function Description Creates a stored procedure. ## Precautions Compared with the original openGauss, Dolphin modifies the CREATE PROCEDURE syntax as follows: 1. The LANGUAGE option is added. 2. The syntax compatibility item \[NOT] DETERMINISTIC is added. 3. The syntax compatibility item { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } is added. 4. The syntax compatibility item SQL SECURITY { DEFINER | INVOKER } is added. ## Syntax ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name [ ( {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] [ { IMMUTABLE | STABLE | VOLATILE } | { SHIPPABLE | NOT SHIPPABLE } | {PACKAGE} | [ NOT ] LEAKPROOF | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL |SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | SET configuration_parameter { TO value | = value | FROM CURRENT } | COMMENT text | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][ ... ] { IS | AS } plsql_body / ``` ## Parameter Description * **LANGUAGE lang\_name** Name of the language used to implement the stored procedure. Default value: **plpgsql**. * **SQL SECURITY INVOKER** Specifies that the stored procedure is to be executed with the permissions of the user that calls it. This parameter can be omitted. The functions of SQL SECURITY INVOKER and SECURITY INVOKER and AUTHID CURRENT\_USER are the same. * **SQL SECURITY DEFINER** Specifies that the stored procedure is to be executed with the privileges of the user that created it. The functions of SQL SECURITY DEFINER and AUTHID DEFINER and SECURITY DEFINER are the same. * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** Syntax compatibility item. ## Helpful Links [CREATE PROCEDURE](https://docs.opengauss.org/en/docs/latest/sql_reference/create_procedure.html) --- --- url: /en/docs/latest/sql_reference/create_procedure.md --- # CREATE PROCEDURE ## Function **CREATE PROCEDURE** creates a stored procedure. ## Precautions * If the parameters or return values of a stored procedure have precision, the precision is not checked. * When creating a stored procedure, you are advised to explicitly specify the schemas of all operations on table objects in the stored procedure definition. Otherwise, the stored procedure may fail to be executed. * **current\_schema** and **search\_path** specified by **SET** during stored procedure creation are invalid. **search\_path** and **current\_schema** before and after function execution should be the same. * If a stored procedure has output parameters, the **SELECT** statement uses the default values of the output parameters when calling the procedure. When the **CALL** statement calls the stored procedure or a non-overloaded function, output parameters must be specified. When the **CALL** statement calls an overloaded **PACKAGE** function, it can use the default values of the output parameters. For details, see examples in [CALL](call.md). * A stored procedure with the **PACKAGE** attribute can use overloaded functions. * When you create a procedure, you cannot insert aggregate functions or other functions out of the average function. * When stored procedures without parameters are called in another stored procedure, you can omit brackets and call stored procedures using their names directly. * When functions with output parameters are called in a stored procedure which is an assignment expression, you can omit the output parameters of the called functions. * The stored procedure supports viewing, exporting, and importing parameter comments. * The stored procedure supports viewing, exporting, and importing parameter comments between IS/AS and plsql\_body. * The default permission on a stored procedure is **SECURITY INVOKER**. If you want to change the default permission to **SECURITY DEFINER**, you need to set the GUC parameter **behavior\_compat\_options** to **'plsql\_security\_definer'**. For details about the S**ECURITY DEFINER** permission, see section "Permission Control" in *Security Hardening Guide*. * Users granted with the **CREATE ANY FUNCTION** permission can create or replace stored procedures in the user schemas. * **out/inout** must be set to a variable but not a constant. * In a centralized environment, if you want to call a stored procedure with the same in parameters but different out parameters, you need to set the GUC parameter **behavior\_compat\_options** to **'proc\_outparam\_override'**. After the parameter is enabled, you must add the out parameters no matter whether you use the SELECT or CALL statement to call the stored procedure. After the parameter is enabled, you cannot use **perform** to call a stored procedure or function. ## Syntax ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name [ ( {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] [ { IMMUTABLE | STABLE | VOLATILE } | { SHIPPABLE | NOT SHIPPABLE } | {PACKAGE} | [ NOT ] LEAKPROOF | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | SET configuration_parameter { TO value | = value | FROM CURRENT } | COMMENT text ][ ... ] { IS | AS } plsql_body / ``` ## Parameter Description * **OR REPLACE** Replaces the original definition when two stored procedures are with the same name. * **procedure\_name** Specifies the name of the stored procedure that is created (optionally with schema names). Value range: a string. It must comply with the identifier naming convention. * **argmode** Specifies the mode of an argument. > \[!TIP]NOTICE > **VARIADIC** specifies parameters of the array type. Value range: **IN**, **OUT**, **INOUT**, and **VARIADIC**. The default value is **IN**. Only the parameters in **OUT** mode can follow the **VARIADIC** parameter. * **argname** Specifies the argument name. Value range: a string. It must comply with the identifier naming convention. * **argtype** Specifies the type of an argument. **%TYPE** or **%ROWTYPE** can be used to indirectly reference a variable or table type. For details, see [Variable Definition Statements](variable_definition_statements.md). Value range: a valid data type * **configuration\_parameter** * **value** Sets the specified configuration parameter to a specified value. If the **value** is **DEFAULT**, the default setting is used in the new session. **OFF** disables the setting. Value range: a string * DEFAULT * OFF * Specified default value * **from current** Uses the value of **configuration\_parameter** of the current session. * **IMMUTABLE, STABLE,**... Specifies a constraint. The function of each parameter is similar to that of **CREATE FUNCTION**. For details, see [CREATE FUNCTION](create_function.md). * **COMMENT text** Comments a stored procedure. * **plsql\_body** Specifies the PL/SQL stored procedure body. > \[!TIP]NOTICE > When you create a user, or perform other operations requiring password input in a stored procedure, the system catalog and CSV log record the password in plaintext. Therefore, you are advised not to perform such operations in the stored procedure. > \[!NOTE]NOTE > No specific order is applied to **argname** and **argname**. The following order is advised: **argname**, **argmode**, and **argtype**. ## Helpful Links [DROP PROCEDURE](drop_procedure.md) ## Suggestions * analyse | analyze * Do not run **ANALYZE** in a transaction or anonymous block. * Do not run **ANALYZE** in a function or stored procedure. --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CREATE-PROCEDURE.md --- # CREATE PROCEDURE ## 功能描述 创建一个新的存储过程。 ## 注意事项 相比于原始的openGauss,dolphin对于CREATE PROCEDURE语法的修改为: 1. 增加 LANGUAGE 选项。 2. 增加语法兼容项 \[NOT] DETERMINISTIC。 3. 增加语法兼容项 { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } 。 4. 增加语法兼容项 SQL SECURITY { DEFINER | INVOKER }。 5. 兼容MySQL的创建存储过程的语法格式 6. 兼容创建存储过程紧跟单条查询语句 ## 语法格式 * openGauss 原始创建存储过程的语法。 ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name [ ( {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] [ { IMMUTABLE | STABLE | VOLATILE } | { SHIPPABLE | NOT SHIPPABLE } | {PACKAGE} | [ NOT ] LEAKPROOF | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL |SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | SET configuration_parameter { TO value | = value | FROM CURRENT } | COMMENT text | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][ ... ] { IS | AS } plsql_body / ``` * 使用MySQL的格式进行创建存储过程。 注意:使用MySQL的格式创建时,需要在客户端使用delimiter命令设置结束符。 ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name ( [ {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...] ] ) [ { IMMUTABLE | STABLE | VOLATILE } | { SHIPPABLE | NOT SHIPPABLE } | {PACKAGE} | [ NOT ] LEAKPROOF | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL |SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | SET configuration_parameter { TO value | = value | FROM CURRENT } | COMMENT text | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][ ... ] routine_body ``` * 创建存储过程紧跟单条查询语句。 ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name ( [ {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...] ] ) [ { IMMUTABLE | STABLE | VOLATILE } | { SHIPPABLE | NOT SHIPPABLE } | {PACKAGE} | [ NOT ] LEAKPROOF | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL |SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | SET configuration_parameter { TO value | = value | FROM CURRENT } | COMMENT text | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][ ... ] select_stmt ``` ## 参数说明 * **LANGUAGE lang\_name** 用以实现存储过程的语言的名称。默认值 plpgsql。 * **SQL SECURITY INVOKER** 表明该存储过程将带着调用它的用户的权限执行。该参数可以省略。 SQL SECURITY INVOKER和SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SQL SECURITY DEFINER** 声明该存储过程将以创建它的用户的权限执行。 SQL SECURITY DEFINER和AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** 语法兼容项。 ## 示例 ```sql --创建存储过程使用单条查询语句,显示为CREATE PROCEDURE openGauss=# create procedure procxx() select a from t1; CREATE PROCEDURE --调用时需要开启参数 openGauss=# set dolphin.sql_mode = 'block_return_multi_results'; SET openGauss=# call procxx(); a --- 1 2 (2 rows) CALL ``` ## 相关链接 [CREATE PROCEDURE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_procedure.html) --- --- url: /zh/docs/latest-lite/sql_reference/create_procedure.md --- # CREATE PROCEDURE ## 功能描述 创建一个新的存储过程。 ## 注意事项 * 如果创建存储过程时参数或返回值带有精度,不进行精度检测。 * 创建存储过程时,存储过程定义中对表对象的操作建议都显示指定模式,否则可能会导致存储过程执行异常。 * 在创建存储过程时,存储过程内部通过SET语句设置current\_schema和search\_path无效。执行完函数search\_path和current\_schema与执行函数前的search\_path和current\_schema保持一致。 * SELECT、CALL调用函数时,必须要在出参位置提供实参进行调用,实参不会发生作用。 * 存储过程指定package属性时支持重载。 * 不能创建仅形参名字不同(存储过程名和参数列表类型都一样)的重载存储过程。 * 重载的存储过程在调用时变量需要明确具体的类型。 * 不能创建与函数拥有相同名称和参数列表的存储过程。 * 在存储过程内部使用未声明的变量,存储过程被调用时会报错。 * 在创建procedure时,不能在avg函数外面嵌套其他agg函数,或者其他系统函数。 * 在存储过程内部调用其它无参数的存储过程时,可以省略括号,直接使用存储过程名进行调用。 * 在存储过程内部调用其他有出参的函数,如果在赋值表达式中调用时,被调函数的出参可以省略,给出了也会被忽略。 * 存储过程支持参数注释的查看与导出、导入。 * 存储过程支持介于IS/AS与plsql\_body之间的注释的查看与导出、导入。 * 存储过程默认为SECURITY INVOKER权限,如果想将默认行为改为SECURITY DEFINER权限,需要设置guc参数behavior\_compat\_options='plsql\_security\_definer'。 * 被授予CREATE ANY FUNCTION权限的用户,可以在用户模式下创建/替换存储过程。 * out/inout参数必须传入变量,不能够传入常量。 * 集中式环境下,想要调用in参数相同,out参数不同的存储过程,需要设置guc参数behavior\_compat\_options='proc\_outparam\_override',并且打开参数后,无论使用select还是call调用存储过程,都必须加上out参数。打开参数后,不支持使用perform调用存储过程或函数。 * 不可与同一模式下已存在的synonym产生命名冲突。 * 通过`CREATE OR REPLACE`语法替换已有的存储过程时,会一并重建依赖此存储过程的视图,存储过程中的参数数据类型变更等情况可能会导致重建视图失败,进而导致替换存储过程失败。此种情况下,建议先删除依赖的视图,再重建存储过程,再重新创建视图。 * 允许创建procedure时忽略依赖关系进行创建,并对未定义的类型/存储过程/函数/包变量提供告警功能,需要设置guc参数behavior\_compat\_options='plpgsql\_dependency'。 ## 语法格式 ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name [ ( {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] { IS | AS } plsql_body / ``` ## 参数说明 * **OR REPLACE** 当存在同名的存储过程时,替换原来的定义。 * **procedure\_name** 创建的存储过程名称,可以带有模式名。 取值范围:字符串,要符合标识符的命名规范。 * **argmode** 参数的模式。 > \[!TIP]须知 > > VARIADIC用于声明数组类型的参数。 取值范围: IN,OUT,INOUT或VARIADIC。缺省值是IN。只有OUT模式的参数能跟在VARIADIC参数之后。 * **argname** 参数的名称。 取值范围:字符串,要符合标识符的命名规范。 * **argtype** 参数的数据类型。可以使用%TYPE或%ROWTYPE间接引用变量或表的类型,详细可参考存储过程章节[定义变量](define_variables.md)。 取值范围:可用的数据类型。 * **plsql\_body** PL/SQL存储过程体。 > \[!TIP]须知 > > 当在存储过程体中进行创建用户等涉及用户密码相关操作时,系统表及csv日志中会记录密码的明文。因此不建议用户在存储过程体中进行涉及用户密码的相关操作。 > \[!NOTE]说明 > > argname和argmode的顺序没有严格要求,推荐按照argname、argmode、argtype的顺序使用。 ## 相关链接 [DROP PROCEDURE](drop_procedure.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CREATE-PROCEDURE.md --- # CREATE PROCEDURE ## 功能描述 创建一个新的存储过程。 ## 注意事项 相比于原始的openGauss,dolphin对于CREATE PROCEDURE语法的修改为: 1. 增加 LANGUAGE 选项。 2. 增加语法兼容项 \[NOT] DETERMINISTIC。 3. 增加语法兼容项 { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } 。 4. 增加语法兼容项 SQL SECURITY { DEFINER | INVOKER }。 5. 兼容MySQL的创建存储过程的语法格式 6. 兼容创建存储过程紧跟单条查询语句 ## 语法格式 * openGauss 原始创建存储过程的语法。 ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name [ ( {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] [ { IMMUTABLE | STABLE | VOLATILE } | { SHIPPABLE | NOT SHIPPABLE } | {PACKAGE} | [ NOT ] LEAKPROOF | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL |SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | SET configuration_parameter { TO value | = value | FROM CURRENT } | COMMENT text | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][ ... ] { IS | AS } plsql_body / ``` * 使用MySQL的格式进行创建存储过程。 注意:使用MySQL的格式创建时,需要在客户端使用delimiter命令设置结束符。 ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name ( [ {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...] ] ) [ { IMMUTABLE | STABLE | VOLATILE } | { SHIPPABLE | NOT SHIPPABLE } | {PACKAGE} | [ NOT ] LEAKPROOF | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL |SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | SET configuration_parameter { TO value | = value | FROM CURRENT } | COMMENT text | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][ ... ] routine_body ``` * 创建存储过程紧跟单条查询语句。 ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name ( [ {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...] ] ) [ { IMMUTABLE | STABLE | VOLATILE } | { SHIPPABLE | NOT SHIPPABLE } | {PACKAGE} | [ NOT ] LEAKPROOF | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT } | {[ EXTERNAL |SQL ] SECURITY INVOKER | [ EXTERNAL|SQL ] SECURITY DEFINER | AUTHID DEFINER | AUTHID CURRENT_USER} | COST execution_cost | SET configuration_parameter { TO value | = value | FROM CURRENT } | COMMENT text | {DETERMINISTIC | NOT DETERMINISTIC} | LANGUAGE lang_name | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } ][ ... ] select_stmt ``` ## 参数说明 * **LANGUAGE lang\_name** 用以实现存储过程的语言的名称。默认值 plpgsql。 * **SQL SECURITY INVOKER** 表明该存储过程将带着调用它的用户的权限执行。该参数可以省略。 SQL SECURITY INVOKER和SECURITY INVOKER和AUTHID CURRENT\_USER的功能相同。 * **SQL SECURITY DEFINER** 声明该存储过程将以创建它的用户的权限执行。 SQL SECURITY DEFINER和AUTHID DEFINER和SECURITY DEFINER的功能相同。 * **CONTAINS SQL** | **NO SQL** | **READS SQL DATA** | **MODIFIES SQL DATA** 语法兼容项。 ## 示例 ```sql --创建存储过程使用单条查询语句,显示为CREATE PROCEDURE openGauss=# create procedure procxx() select a from t1; CREATE PROCEDURE --调用时需要开启参数 openGauss=# set dolphin.sql_mode = 'block_return_multi_results'; SET openGauss=# call procxx(); a --- 1 2 (2 rows) CALL ``` ## 相关链接 [CREATE PROCEDURE](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_procedure.html) --- --- url: /zh/docs/latest/sql_reference/create_procedure.md --- # CREATE PROCEDURE ## 功能描述 创建一个新的存储过程。 ## 注意事项 * 如果创建存储过程时参数或返回值带有精度,不进行精度检测。 * 创建存储过程时,存储过程定义中对表对象的操作建议都显示指定模式,否则可能会导致存储过程执行异常。 * 在创建存储过程时,存储过程内部通过SET语句设置current\_schema和search\_path无效。执行完函数search\_path和current\_schema与执行函数前的search\_path和current\_schema保持一致。 * SELECT、CALL调用函数时,必须要在出参位置提供实参进行调用,实参不会发生作用。 * 存储过程指定package属性时支持重载。 * 不能创建仅形参名字不同(存储过程名和参数列表类型都一样)的重载存储过程。 * 重载的存储过程在调用时变量需要明确具体的类型。 * 不能创建与函数拥有相同名称和参数列表的存储过程。 * 在存储过程内部使用未声明的变量,存储过程被调用时会报错。 * 在创建procedure时,不能在avg函数外面嵌套其他agg函数,或者其他系统函数。 * 在存储过程内部调用其它无参数的存储过程时,可以省略括号,直接使用存储过程名进行调用。 * 在存储过程内部调用其他有出参的函数,如果在赋值表达式中调用时,被调函数的出参可以省略,给出了也会被忽略。 * 存储过程支持参数注释的查看与导出、导入。 * 存储过程支持介于IS/AS与plsql\_body之间的注释的查看与导出、导入。 * 存储过程默认为SECURITY INVOKER权限,如果想将默认行为改为SECURITY DEFINER权限,需要设置guc参数behavior\_compat\_options='plsql\_security\_definer'。 * 被授予CREATE ANY FUNCTION权限的用户,可以在用户模式下创建/替换存储过程。 * out/inout参数必须传入变量,不能够传入常量。 * 集中式环境下,想要调用in参数相同,out参数不同的存储过程,需要设置guc参数behavior\_compat\_options='proc\_outparam\_override',并且打开参数后,无论使用select还是call调用存储过程,都必须加上out参数。打开参数后,不支持使用perform调用存储过程或函数。 * 不可与同一模式下已存在的synonym产生命名冲突。 * 通过`CREATE OR REPLACE`语法替换已有的存储过程时,会一并重建依赖此存储过程的视图,存储过程中的参数数据类型变更等情况可能会导致重建视图失败,进而导致替换存储过程失败。此种情况下,建议先删除依赖的视图,再重建存储过程,再重新创建视图。 * 允许创建procedure时忽略依赖关系进行创建,并对未定义的类型/存储过程/函数/包变量提供告警功能,需要设置guc参数behavior\_compat\_options='plpgsql\_dependency'。 ## 语法格式 ``` CREATE [ OR REPLACE ] PROCEDURE procedure_name [ ( {[ argname ] [ argmode ] argtype [ { DEFAULT | := | = } expression ]}[,...]) ] { IS | AS } plsql_body / ``` ## 参数说明 * **OR REPLACE** 当存在同名的存储过程时,替换原来的定义。 * **procedure\_name** 创建的存储过程名称,可以带有模式名。 取值范围:字符串,要符合标识符的命名规范。 * **argmode** 参数的模式。 > \[!TIP]须知 > VARIADIC用于声明数组类型的参数。 取值范围: IN、OUT、INOUT或VARIADIC。缺省值是IN。只有OUT模式的参数能跟在VARIADIC参数之后。 * **argname** 参数的名称。 取值范围:字符串,要符合标识符的命名规范。 * **argtype** 参数的数据类型。可以使用%TYPE或%ROWTYPE间接引用变量或表的类型,详细可参考存储过程章节[定义变量](variable_definition_statements.md)。 取值范围:可用的数据类型。 * **plsql\_body** PL/SQL存储过程体。 > \[!TIP]须知 > 当在存储过程体中进行创建用户等涉及用户密码相关操作时,系统表及csv日志中会记录密码的明文。因此不建议用户在存储过程体中进行涉及用户密码的相关操作。 > \[!NOTE]说明 > argname和argmode的顺序没有严格要求,推荐按照argname、argmode、argtype的顺序使用。 ## 相关链接 [DROP PROCEDURE](drop_procedure.md) --- --- url: /zh/docs/latest/ograc/sql_reference/create_profile.md --- # CREATE PROFILE ## 功能描述 CREATE PROFILE 语句用于创建用户配置文件,用于管理数据库用户的资源限制和密码策略。配置文件可以被多个用户共享,便于统一管理用户的安全和资源使用策略。 ## 注意事项 创建或替换配置文件需要具备相应的系统权限;配置文件中参数设置不当可能导致账户被锁定或密码策略过于严格,请根据实际业务需求合理配置。 ## 语法格式 ```sql CREATE PROFILE profile_name [REPLACE] LIMIT { parameter1 [ { UNLIMITED | DEFAULT | value } ] [ parameter2 [ { UNLIMITED | DEFAULT | value } ] ] ... } ``` ## 参数说明 ### 基本参数 | 参数名 | 说明 | | ------ | ---- | | profile\_name | 配置文件的名称 | | REPLACE | 可选参数,如果指定的配置文件已存在,则替换该配置文件 | ### 参数值选项 | 选项 | 说明 | | ---- | ---- | | UNLIMITED | 表示无限制 | | DEFAULT | 使用系统默认值 | | value | 具体的数值 | ### 可配置参数列表 | 参数名 | 类型 | 默认值 | 单位 | 说明 | | ------ | ---- | ------ | ---- | ---- | | FAILED\_LOGIN\_ATTEMPTS | 整数 | 10 | 次 | 指定用户登录失败的最大尝试次数,超过该次数后账户将被锁定 | | PASSWORD\_LIFE\_TIME | 整数 | 15552000 | 秒 | 指定密码的有效期,超过该时间后密码将过期,用户需要修改密码才能登录 | | PASSWORD\_REUSE\_TIME | 整数 | UNLIMITED | 秒 | 指定密码重用前必须经过的天数,如果设置为整数,则必须将 PASSWORD\_REUSE\_MAX 设置为 UNLIMITED | | PASSWORD\_REUSE\_MAX | 整数 | UNLIMITED | 次 | 指定密码重用前必须更改的次数,如果设置为整数,则必须将 PASSWORD\_REUSE\_TIME 设置为 UNLIMITED | | PASSWORD\_LOCK\_TIME | 整数 | 86400 | 秒 | 指定账户锁定的时间长度 | | PASSWORD\_GRACE\_TIME | 整数 | 604800 | 秒 | 指定密码过期后的宽限期,在此期间登录会收到警告但仍可登录 | | SESSIONS\_PER\_USER | 整数 | UNLIMITED | 个 | 指定每个用户允许的最大并发会话数 | | PASSWORD\_MIN\_LEN | 整数 | 8 | 字符 | 指定密码的最小长度 | ## 示例 ### 创建基本配置文件 ``` CREATE PROFILE app_user_profile LIMIT FAILED_LOGIN_ATTEMPTS 5; ``` ### 替换现有配置文件 ``` CREATE OR REPLACE PROFILE app_user_profile LIMIT FAILED_LOGIN_ATTEMPTS 20; ``` ### 使用默认值创建配置文件 ``` CREATE PROFILE default_profile LIMIT FAILED_LOGIN_ATTEMPTS DEFAULT; ``` ### 创建无限制的配置文件 ``` CREATE PROFILE unlimited_profile LIMIT PASSWORD_LIFE_TIME UNLIMITED; ``` --- --- url: /en/docs/latest-lite/sql_reference/create_publication.md --- # CREATE PUBLICATION ## **Function Description** **CREATE PUBLICATION** adds a new publication to the current database. The publication name must be different from the name of any existing publication in the current database. A publication is essentially the replication of data changes in a set of tables achieved by logical replication. ## **Precautions** * If neither **FOR TABLE** nor **FOR ALL TABLES** is specified, a publication starts with a set of empty tables. Tables can be added later. * Creating a publication does not start replication. It defines only one group and filtering logic for future subscribers. To create a publication, the caller must have the **CREATE** permission on the current database. (The system administrator does not need to perform a check on this.) * To add a table to a publication, the caller must have ownership of the table. The **FOR ALL TABLES** clause requires that the caller be a user with the **SYSADMIN** permission. * Tables added to a publication that publishes UPDATE or DELETE operations must already have **REPLICA IDENTITY** defined; otherwise, these operations will be prohibited in those tables. * The **COPY... FROM** command is used to publish INSERT operations. It cannot be used to publish TRUNCATE and DDL operations. ## **Syntax** ``` CREATE PUBLICATION name [ FOR TABLE table_name [, ...] | FOR ALL TABLES ] [ WITH ( publication_parameter [=value] [, ... ] ) ]; ``` ## **Parameter Description** * **name** Specifies the name of a new publication. * **FOR TABLE** Specifies the list of tables to be added to a publication. Only persistent base tables can be published. Temporary tables, unlogged tables, foreign tables, MOTs, materialized views, and regular views cannot be published. * **FOR ALL TABLES** Marks a publication as replicating changes of all tables in the database, including tables to be created. * **WITH ( publication\_parameter \[= value] \[, ... ] )** Specifies the optional parameters for a publication. The following parameters are supported: * **publish (string)** Specifies which DML operations can be published to subscribers. The value of this parameter is a list of operations separated by commas (,). The allowed operations are INSERT, UPDATE, and DELETE. If this parameter is not specified, all operations are published by default. The default value is **'insert, update, delete'**. ## **Example** ``` --Create a publication to publish all changes in two tables. CREATE PUBLICATION mypublication FOR TABLE users, departments; --Create a publication to publish all changes in all tables. CREATE PUBLICATION alltables FOR ALL TABLES; --Create a publication to publish INSERT operations in only one table. CREATE PUBLICATION insert_only FOR TABLE mydata WITH (publish = 'insert'); --Modify publication operations. ALTER PUBLICATION insert_only SET (publish='insert,update,delete'); --Add a table to a publication. ALTER PUBLICATION insert_only ADD TABLE mydata2; --Delete a publication. DROP PUBLICATION insert_only; ``` ## Helpful Links [ALTER PUBLICATION](alter_publication.md), [DROP PUBLICATION](drop_publication.md) --- --- url: /en/docs/latest/sql_reference/create_publication.md --- # CREATE PUBLICATION ## Function **CREATE PUBLICATION** adds a new publication to the current database. The publication name must be different from the name of any existing publication in the current database. A publication is essentially the replication of data changes in a set of tables achieved by logical replication. ## Precautions * If neither **FOR TABLE** nor **FOR ALL TABLES** is specified, a publication starts with a set of empty tables. Tables can be added later. * Creating a publication does not start replication. It defines only one group and filtering logic for future subscribers. To create a publication, the caller must have the **CREATE** permission on the current database. (The system administrator does not need to perform a check on this.) * To add a table to a publication, the caller must have ownership of the table. The **FOR ALL TABLES** clause requires that the caller be a user with the **SYSADMIN** permission. * Tables in the internal schemas of the database, including **blockchain**, **cstore**, **db4ai**, **dbe\_pldebugger**, **dbe\_pldeveloper**, **pkg\_service**, **snapshot**, and **sqladvisor**, are not published. * Tables added to a publication that publishes UPDATE or DELETE operations must already have **REPLICA IDENTITY** defined or have a primary key; otherwise, these operations will be prohibited in those tables. * The **COPY... FROM** command is used to publish INSERT operations. It cannot be used to publish TRUNCATE and DDL operations. ## Syntax ``` CREATE PUBLICATION name [ FOR TABLE table_name [, ...] | FOR ALL TABLES ] [ WITH ( publication_parameter [=value] [, ... ] ) ]; ``` ## Parameter Description * **name** Specifies the name of a new publication. * **FOR TABLE** Specifies the list of tables to be added to a publication. Only persistent base tables can be published. Temporary tables, unlogged tables, foreign tables, MOTs, materialized views, and regular views cannot be published. * **FOR ALL TABLES** Marks a publication as replicating changes of all tables in the database, including tables to be created. * **WITH ( publication\_parameter \[= value] \[, ... ] )** Specifies the optional parameters for a publication. The following parameters are supported: * **publish (string)** Specifies which DML operations can be published to subscribers. The value of this parameter is a list of operations separated by commas (,). The allowed operations are INSERT, UPDATE, and DELETE. If this parameter is not specified, all operations are published by default. The default value is **'insert, update, delete'**. ## Examples ``` -- Create a publication to publish all changes in two tables. CREATE PUBLICATION mypublication FOR TABLE users, departments; -- Create a publication to publish all changes in all tables. CREATE PUBLICATION alltables FOR ALL TABLES; -- Create a publication to publish INSERT operations in only one table. CREATE PUBLICATION insert_only FOR TABLE mydata WITH (publish = 'insert'); -- Modify publication operations. ALTER PUBLICATION insert_only SET (publish='insert,update,delete'); -- Add a table to a publication. ALTER PUBLICATION insert_only ADD TABLE mydata2; -- Delete a publication. DROP PUBLICATION insert_only; ``` ## Helpful Links [ALTER PUBLICATION](alter_publication.md) and [DROP PUBLICATION](drop_publication.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_publication.md --- # CREATE PUBLICATION ## **功能描述** 向当前数据库添加一个新的发布,发布的名称必须与当前数据库中任何现有发布的名称不同。发布本质上是通过逻辑复制将一组表的数据变更进行复制。 ## **注意事项** * 如果既没有指定FOR TABLE,也没有指定FOR ALL TABLES, 那么这个发布就是以一组空表开始的,可以在后续添加表。 * 创建发布不会开始复制。它只为未来的订阅者定义一个分组和过滤逻辑。 要创建一个发布,调用者必须拥有当前数据库的CREATE权限。(当然,系统管理员不需要这个检查。) * 要将表添加到发布中,调用者必须拥有该表的所有权。FOR ALL TABLES子句要求调用者是具有SYSADMIN权限用户。 * 添加到发布UPDATE或DELETE操作的发布的表必须已经定义了REPLICA IDENTITY,否则将在这些表上禁止这些操作。 * COPY ... FROM命令是作为INSERT操作发布的。不发布TRUNCATE和DDL操作。 ## **语法格式** ``` CREATE PUBLICATION name [ FOR TABLE table_name [, ...] | FOR ALL TABLES ] [ WITH ( publication_parameter [=value] [, ... ] ) ]; ``` ## **参数说明** * **name** 新发布的名称。 * **FOR TABLE** 指定要添加到发布的表的列表。 只有持久基表才能成为发布的一部分,临时表、非日志表、外表、MOT表、物化视图、常规视图不能被发布。 * **FOR ALL TABLES** 将发布标记为复制数据库中所有表的更改,包括在将来创建的表。 * **WITH ( publication\_parameter \[= value] \[, ... ] )** 该子句指定发布的可选参数。支持下列参数: * **publish (string)** 这个参数决定了哪些DML操作可以发布给订阅者。该值是一个用逗号分隔的操作列表,允许的操作是insert、update和delete,不指定则默认发布所有的动作。该选项的默认值是'insert, update, delete'。 * **ddl (string)** 这个参数决定了哪些DDL操作可以发布给订阅者。该值是一个用逗号分隔的操作列表,允许的操作是none、table、all,不指定则默认不发布DDL操作。该选项的默认值是'none'. none: 表示不发布DDL操作 table: 表示只发布数据表的DDL操作 all: 表示发布所有的DDL操作,目前支持的对象类型有TABLE和INDEX,设置为该值时,只允许 FOR ALL TABLES 选项 ## **示例** ``` --创建一个发布,发布两个表中所有更改。 CREATE PUBLICATION mypublication FOR TABLE users, departments; --创建一个发布,发布所有表中的所有更改。 CREATE PUBLICATION alltables FOR ALL TABLES; --创建一个发布,只发布一个表中的INSERT操作。 CREATE PUBLICATION insert_only FOR TABLE mydata WITH (publish = 'insert'); --修改发布的动作。 ALTER PUBLICATION insert_only SET (publish='insert,update,delete'); --向发布中添加表。 ALTER PUBLICATION insert_only ADD TABLE mydata2; --删除发布。 DROP PUBLICATION insert_only; --创建一个发布,发布所有的DDL操作 CREATE PUBLICATION ddl_all FOR ALL TABLES WITH (ddl='all'); --创建一个发布,发布类型为TABLE的DDL操作 CREATE PUBLICATION ddl_all FOR ALL TABLES WITH (ddl='table'); ``` ## 相关链接 [ALTER PUBLICATION](alter_publication.md),[DROP PUBLICATION](drop_publication.md) --- --- url: /zh/docs/latest/sql_reference/create_publication.md --- # CREATE PUBLICATION ## **功能描述** 向当前数据库添加一个新的发布,发布的名称必须与当前数据库中任何现有发布的名称不同。发布本质上是通过逻辑复制将一组表的数据变更进行复制。 ## **注意事项** * 如果既没有指定FOR TABLE,也没有指定FOR ALL TABLES, 那么这个发布就是以一组空表开始的,可以在后续添加表。 * 创建发布不会开始复制。它只为未来的订阅者定义一个分组和过滤逻辑。 要创建一个发布,调用者必须拥有当前数据库的CREATE权限。(当然,系统管理员不需要这个检查。) * 要将表添加到发布中,调用者必须拥有该表的所有权。FOR ALL TABLES子句要求调用者是具有SYSADMIN权限用户。 * 添加到发布UPDATE或DELETE操作的发布的表必须已经定义了REPLICA IDENTITY,否则将在这些表上禁止这些操作。 * COPY ... FROM命令是作为INSERT操作发布的。不发布TRUNCATE和DDL操作。 ## **语法格式** ``` CREATE PUBLICATION name [ FOR TABLE table_name [, ...] | FOR ALL TABLES ] [ WITH ( publication_parameter [=value] [, ... ] ) ]; ``` ## **参数说明** * **name** 新发布的名称。 * **FOR TABLE** 指定要添加到发布的表的列表。 只有持久基表才能成为发布的一部分,临时表、非日志表、外表、MOT表、物化视图、常规视图不能被发布。 * **FOR ALL TABLES** 将发布标记为复制数据库中所有表的更改,包括在将来创建的表。 * **WITH ( publication\_parameter \[= value] \[, ... ] )** 该子句指定发布的可选参数。支持下列参数: * **publish (string)** 这个参数决定了哪些DML操作可以发布给订阅者。该值是一个用逗号分隔的操作列表,允许的操作是insert、update和delete,不指定则默认发布所有的动作。该选项的默认值是'insert, update, delete'。 * **ddl (string)** 这个参数决定了哪些DDL操作可以发布给订阅者。该值是一个用逗号分隔的操作列表,允许的操作是none、table、all,不指定则默认不发布DDL操作。该选项的默认值是'none'. none: 表示不发布DDL操作 table: 表示只发布数据表的DDL操作 all: 表示发布所有的DDL操作,目前支持的对象类型有TABLE和INDEX,设置为该值时,只允许 FOR ALL TABLES 选项 ## **示例** ``` --创建一个发布,发布两个表中所有更改。 CREATE PUBLICATION mypublication FOR TABLE users, departments; --创建一个发布,发布所有表中的所有更改。 CREATE PUBLICATION alltables FOR ALL TABLES; --创建一个发布,只发布一个表中的INSERT操作。 CREATE PUBLICATION insert_only FOR TABLE mydata WITH (publish = 'insert'); --修改发布的动作。 ALTER PUBLICATION insert_only SET (publish='insert,update,delete'); --向发布中添加表。 ALTER PUBLICATION insert_only ADD TABLE mydata2; --删除发布。 DROP PUBLICATION insert_only; --创建一个发布,发布所有的DDL操作 CREATE PUBLICATION ddl_all FOR ALL TABLES WITH (ddl='all'); --创建一个发布,发布类型为TABLE的DDL操作 CREATE PUBLICATION ddl_all FOR ALL TABLES WITH (ddl='table'); ``` ## 相关链接 [ALTER PUBLICATION](alter_publication.md),[DROP PUBLICATION](drop_publication.md) --- --- url: /en/docs/latest-lite/sql_reference/create_resource_label.md --- # CREATE RESOURCE LABEL ## Function **CREATE RESOURCE LABEL** creates a resource label. ## Precautions Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. ## Syntax ``` CREATE RESOURCE LABEL [IF NOT EXISTS] label_name ADD label_item_list[, ...]*; ``` * label\_item\_list ``` resource_type(resource_path[, ...]*) ``` * resource\_type ``` TABLE | COLUMN | SCHEMA | VIEW | FUNCTION ``` ## Parameter Description * **label\_name** Specifies the resource label name, which must be unique. Value range: a string. It must comply with the naming convention. * **resource\_type** Specifies the type of database resources to be labeled. * **resource\_path** Specifies the path of database resources. ## Examples ``` -- Create table tb_for_label. openGauss=# CREATE TABLE tb_for_label(col1 text, col2 text, col3 text); -- Create schema schema_for_label. openGauss=# CREATE SCHEMA schema_for_label; -- Create view view_for_label. openGauss=# CREATE VIEW view_for_label AS SELECT 1; -- Create function func_for_label. openGauss=# CREATE FUNCTION func_for_label RETURNS TEXT AS $$ SELECT col1 FROM tb_for_label; $$ LANGUAGE SQL; -- Create a resource label based on the table. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS table_label add TABLE(public.tb_for_label); -- Create a resource label based on the columns. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS column_label add COLUMN(public.tb_for_label.col1); -- Create a resource label based on the schema. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS schema_label add SCHEMA(schema_for_label); -- Create a resource label based on the view. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS view_label add VIEW(view_for_label); -- Create a resource label based on the function. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS func_label add FUNCTION(func_for_label); ``` ## Helpful Links [ALTER RESOURCE LABEL](alter_resource_label.md) and [DROP RESOURCE LABEL](drop_resource_label.md) --- --- url: /en/docs/latest/sql_reference/create_resource_label.md --- # CREATE RESOURCE LABEL ## Function **CREATE RESOURCE LABEL** creates a resource label. ## Precautions Only users with the **poladmin** or **sysadmin** permission, or the initial user can perform this operation. ## Syntax ``` CREATE RESOURCE LABEL [IF NOT EXISTS] label_name ADD label_item_list[, ...]*; ``` * label\_item\_list ``` resource_type(resource_path[, ...]*) ``` * resource\_type ``` TABLE | COLUMN | SCHEMA | VIEW | FUNCTION ``` ## Parameter Description * **label\_name** Specifies the resource label name, which must be unique. Value range: a string. It must comply with the naming convention. * **resource\_type** Specifies the type of database resources to be labeled. * **resource\_path** Specifies the path of database resources. ## Examples ``` -- Create table tb_for_label. openGauss=# CREATE TABLE tb_for_label(col1 text, col2 text, col3 text); -- Create schema schema_for_label. openGauss=# CREATE SCHEMA schema_for_label; -- Create view view_for_label. openGauss=# CREATE VIEW view_for_label AS SELECT 1; -- Create function func_for_label. openGauss=# CREATE FUNCTION func_for_label RETURNS TEXT AS $$ SELECT col1 FROM tb_for_label; $$ LANGUAGE SQL; -- Create a resource label based on the table. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS table_label add TABLE(public.tb_for_label); -- Create a resource label based on the columns. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS column_label add COLUMN(public.tb_for_label.col1); -- Create a resource label based on the schema. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS schema_label add SCHEMA(schema_for_label); -- Create a resource label based on the view. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS view_label add VIEW(view_for_label); -- Create a resource label based on the function. openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS func_label add FUNCTION(func_for_label); ``` ## Helpful Links [ALTER RESOURCE LABEL](alter_resource_label.md) and [DROP RESOURCE LABEL](drop_resource_label.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_resource_label.md --- # CREATE RESOURCE LABEL ## 功能描述 创建资源标签。 ## 注意事项 只有poladmin,sysadmin或初始用户能正常执行此操作。 ## 语法格式 ``` CREATE RESOURCE LABEL [IF NOT EXISTS] label_name ADD label_item_list[, ...]*; ``` * label\_item\_list: ``` resource_type(resource_path[, ...]*) ``` * resource\_type: ``` TABLE | COLUMN | SCHEMA | VIEW | FUNCTION ``` ## 参数说明 * **label\_name** 资源标签名称,创建时要求不能与已有标签重名。 取值范围:字符串,要符合标识符的命名规范。 * **resource\_type** 指的是要标记的数据库资源类型。 * **resource\_path** 指的是描述具体的数据库资源的路径。 ## 示例 ``` --创建一个表tb_for_label openGauss=# CREATE TABLE tb_for_label(col1 text, col2 text, col3 text); --创建一个模式schema_for_label openGauss=# CREATE SCHEMA schema_for_label; --创建一个视图view_for_label openGauss=# CREATE VIEW view_for_label AS SELECT 1; --创建一个函数func_for_label openGauss=# CREATE FUNCTION func_for_label RETURNS TEXT AS $$ SELECT col1 FROM tb_for_label; $$ LANGUAGE SQL; --基于表创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS table_label add TABLE(public.tb_for_label); --基于列创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS column_label add COLUMN(public.tb_for_label.col1); --基于模式创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS schema_label add SCHEMA(schema_for_label); --基于视图创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS view_label add VIEW(view_for_label); --基于函数创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS func_label add FUNCTION(func_for_label); ``` ## 相关链接 [ALTER RESOURCE LABEL](alter_resource_label.md),[DROP RESOURCE LABEL](drop_resource_label.md)。 --- --- url: /zh/docs/latest/sql_reference/create_resource_label.md --- # CREATE RESOURCE LABEL ## 功能描述 创建资源标签。 ## 注意事项 只有poladmin、sysadmin或初始用户能正常执行此操作。 ## 语法格式 ``` CREATE RESOURCE LABEL [IF NOT EXISTS] label_name ADD label_item_list[, ...]*; ``` * label\_item\_list: ``` resource_type(resource_path[, ...]*) ``` * resource\_type: ``` TABLE | COLUMN | SCHEMA | VIEW | FUNCTION ``` ## 参数说明 * **label\_name** 资源标签名称,创建时要求不能与已有标签重名。 取值范围:字符串,要符合标识符的命名规范。 * **resource\_type** 指的是要标记的数据库资源类型。 * **resource\_path** 指的是描述具体的数据库资源的路径。 ## 示例 ``` --创建一个表tb_for_label openGauss=# CREATE TABLE tb_for_label(col1 text, col2 text, col3 text); --创建一个模式schema_for_label openGauss=# CREATE SCHEMA schema_for_label; --创建一个视图view_for_label openGauss=# CREATE VIEW view_for_label AS SELECT 1; --创建一个函数func_for_label openGauss=# CREATE FUNCTION func_for_label RETURNS TEXT AS $$ SELECT col1 FROM tb_for_label; $$ LANGUAGE SQL; --基于表创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS table_label add TABLE(public.tb_for_label); --基于列创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS column_label add COLUMN(public.tb_for_label.col1); --基于模式创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS schema_label add SCHEMA(schema_for_label); --基于视图创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS view_label add VIEW(view_for_label); --基于函数创建资源标签 openGauss=# CREATE RESOURCE LABEL IF NOT EXISTS func_label add FUNCTION(func_for_label); ``` ## 相关链接 [ALTER RESOURCE LABEL](alter_resource_label.md),[DROP RESOURCE LABEL](drop_resource_label.md)。 --- --- url: /en/docs/latest-lite/sql_reference/create_resource_pool.md --- # CREATE RESOURCE POOL ## Function **CREATE RESOURCE POOL** creates a resource pool and specifies the Cgroup of the resource pool. ## Precautions Only a user with the **CREATE** permission on the current database can perform this operation. ## Syntax ``` CREATE RESOURCE POOL pool_name [WITH ({MEM_PERCENT=pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='io_priority' | nodegroup="nodegroupname" | is_foreign=boolean }[, ... ])]; ``` ## Parameter Description * **pool\_name** Specifies the name of a resource pool. The name of a resource pool cannot be same as that of an existing resource pool. Value range: a string. It must comply with the identifier naming convention. * **group\_name** Specifies the name of a Cgroup. > \[!NOTE]NOTE > > * You can use either double quotation marks ("") or single quotation marks ('') in the syntax when setting the name of a Cgroup. > * The value of **group\_name** is case-sensitive. > * If **group\_name** is not specified, the string "Medium" will be used by default in the syntax, indicating the **Medium** Timeshare Cgroup under **DefaultClass**. > * If a database administrator specifies a Workload Cgroup under **Class**, for example, **control\_group** set to **class1:workload1**, the resource pool will be associated with the **workload1** Cgroup under **class1**. The level of the Workload Cgroup can also be specified. For example, **control\_group** is set to **class1:workload1:1**. > * If a database user specifies the Timeshare Cgroup string (**Rush**, **High**, **Medium**, or **Low**) in the syntax, for example, **control\_group** is set to **High**, the resource pool will be associated with the **High** Timeshare Cgroup under **DefaultClass**. Value range: a string. It must comply with the rule in the description, which specifies the created Cgroup. * **stmt** Specifies the maximum number of statements that can be concurrently executed in a resource pool. Value range: numeric data ranging from –1 to 2147483647 * **dop** Specifies the maximum statement concurrency degree for a resource pool, equivalent to the number of threads that can be created for executing a statement. Value range: numeric data ranging from 1 to 64 * **memory\_size** Specifies the maximum memory size of a resource pool. Value range: a string from 1 KB to 2047 GB * **mem\_percent** Specifies the proportion of available resource pool memory to the total memory or group user memory. In multi-tenant scenarios, the value of **mem\_percent** of group users or service users ranges from 1 to 100. The default value is **20**. In common scenarios, the value of **mem\_percent** of common users ranges from 0 to 100. The default value is **0**. > \[!NOTE]NOTE > When both **mem\_percent** and **memory\_limit** are specified, only **mem\_percent** takes effect. * **io\_limits** Specifies the upper limit of IOPS in a resource pool. The IOPS is counted by ones for column storage and by 10 thousands for row storage. * **io\_priority** Specifies the I/O priority for jobs that consume many I/O resources. It takes effect when the I/O usage reaches 90%. There are three priorities: **Low**, **Medium**, and **High**. If you do not want to control I/O resources, use the default value **None**. > \[!NOTE]NOTE > The settings of **io\_limits** and **io\_priority** are valid only for complex jobs, such as batch import (using **INSERT INTO SELECT**, **COPY FROM**, or **CREATE TABLE AS**), complex queries involving over 500 MB data on each DN, and **VACUUM FULL**. * **nodegroup** Specifies the name of a logical cluster. The logical cluster must already exist. If the logical cluster name contains uppercase letters or special characters or begins with a digit, enclose the name with double quotation marks ("") in SQL statements. * **is\_foreign** In logical cluster mode, specifies the current resource pool to control the resources of common users who are not associated with the logical cluster specified by **nodegroup**. > \[!NOTE]NOTE > > * **nodegroup** must specify an existing logical cluster, and cannot be **elastic\_group** or the default node group (**group\_version1**), which is generated during cluster installation. > * If **is\_foreign** is set to **true**, the resource pool cannot be associated with users. That is, **CREATE USER ... RESOURCE POOL** cannot be used to configure resource pools for users. The resource pool automatically checks whether the users are associated with its logical cluster. If they are not, they will be controlled by the resource pool when performing operations on database nodes in the logical cluster. ## Examples This example assumes that Cgroups have been created by users in advance. For details about how to create Cgroups, see [Setting a Cgroup](https://docs.opengauss.org/en/docs/latest-lite/performance_tuning_guide/resource_management_preparation.html). ``` -- Create a default resource pool, and associate it with the Medium Timeshare Cgroup under Workload under DefaultClass. openGauss=# CREATE RESOURCE POOL pool1; -- Create a resource pool, and associate it with the High Timeshare Workload Cgroup under DefaultClass. openGauss=# CREATE RESOURCE POOL pool2 WITH (CONTROL_GROUP="High"); -- Create a resource pool, and associate it with the Low Timeshare Workload Cgroup under class1. openGauss=# CREATE RESOURCE POOL pool3 WITH (CONTROL_GROUP="class1:Low"); -- Create a resource pool, and associate it with the wg1 Workload Cgroup under class1. openGauss=# CREATE RESOURCE POOL pool4 WITH (CONTROL_GROUP="class1:wg1"); -- Create a resource pool, and associate it with the wg2 Workload Cgroup under class1. openGauss=# CREATE RESOURCE POOL pool5 WITH (CONTROL_GROUP="class1:wg2:3"); -- Delete the resource pool. openGauss=# DROP RESOURCE POOL pool1; openGauss=# DROP RESOURCE POOL pool2; openGauss=# DROP RESOURCE POOL pool3; openGauss=# DROP RESOURCE POOL pool4; openGauss=# DROP RESOURCE POOL pool5; ``` ## Helpful Links [ALTER RESOURCE POOL](alter_resource_pool.md) and [DROP RESOURCE POOL](drop_resource_pool.md) --- --- url: /en/docs/latest/sql_reference/create_resource_pool.md --- # CREATE RESOURCE POOL ## Function **CREATE RESOURCE POOL** creates a resource pool and specifies the Cgroup of the resource pool. ## Precautions Only SYSADMIN and VCADMIN users can create resource pools. ## Syntax ``` CREATE RESOURCE POOL pool_name [WITH ({MEM_PERCENT=pct | CONTROL_GROUP="group_name" | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='io_priority' | nodegroup="nodegroupname" | is_foreign=boolean } [, ... ]) ]; ``` ## Parameter Description * **pool\_name** Specifies the name of a resource pool. The name of a resource pool cannot be same as that of an existing resource pool. Value range: a string. It must comply with the identifier naming convention. * **group\_name** Specifies the name of a Cgroup. > \[!NOTE]NOTE > > * You can use either double quotation marks ("") or single quotation marks ('') in the syntax when setting the name of a Cgroup. > * The value of **group\_name** is case-sensitive. > * If **group\_name** is not specified, the string "Medium" will be used by default in the syntax, indicating the **Medium** Timeshare Cgroup under **DefaultClass**. > * If a database administrator specifies a Workload Cgroup under **Class**, for example, **control\_group** set to **class1:workload1**, the resource pool will be associated with the **workload1** Cgroup under **class1**. The level of the Workload Cgroup can also be specified. For example, **control\_group** is set to **class1:workload1:1**. > * If a database user specifies the Timeshare Cgroup string (**Rush**, **High**, **Medium**, or **Low**) in the syntax, for example, **control\_group** is set to **High**, the resource pool will be associated with the **High** Timeshare Cgroup under **DefaultClass**. Value range: a string. It must comply with the rule in the description, which specifies the created Cgroup. * **stmt** Specifies the maximum number of statements that can be concurrently executed in a resource pool. Value range: numeric data ranging from –1 to 2147483647 * **dop** Specifies the maximum statement concurrency degree for a resource pool, equivalent to the number of threads that can be created for executing a statement. Value range: numeric data ranging from 1 to 64 * **memory\_size** Specifies the maximum memory size of a resource pool. Value range: a string from 1 KB to 2047 GB * **mem\_percent** Specifies the proportion of available resource pool memory to the total memory or group user memory. In multi-tenant scenarios, the value of **mem\_percent** of group users or service users ranges from 1 to 100. The default value is **20**. In common scenarios, the value of **mem\_percent** of common users ranges from 0 to 100. The default value is **0**. > \[!NOTE]NOTE > When both **mem\_percent** and **memory\_limit** are specified, only **mem\_percent** takes effect. * **io\_limits** Specifies the upper limit of IOPS in a resource pool. The IOPS is counted by ones for column storage and by 10 thousands for row storage. Value range: numeric data ranging from 0 to 2147483647 * **io\_priority** Specifies the I/O priority for jobs that consume many I/O resources. It takes effect when the I/O usage reaches 90%. There are three priorities: **Low**, **Medium**, and **High**. If you do not want to control I/O resources, use the default value **None**. > \[!NOTE]NOTE > The settings of **io\_limits** and **io\_priority** are valid only for complex jobs, such as batch import (using **INSERT INTO SELECT**, **COPY FROM**, or **CREATE TABLE AS**), complex queries involving over 500 MB data on each DN, and **VACUUM FULL**. * **nodegroup** Specifies the name of a logical cluster. The logical cluster must already exist. If the logical cluster name contains uppercase letters or special characters or begins with a digit, enclose the name with double quotation marks ("") in SQL statements. This parameter is invalid in a standalone system. * **is\_foreign** In logical cluster mode, specifies the current resource pool to control the resources of common users that are not associated with the logical cluster specified by **nodegroup**. This parameter is invalid in a standalone system. > \[!NOTE]NOTE > > * **nodegroup** must specify an existing logical cluster, and cannot be **elastic\_group** or the default node group (**group\_version1**), which is generated during cluster installation. > * If **is\_foreign** is set to **true**, the resource pool cannot be associated with users. That is, **CREATE USER ... RESOURCE POOL** cannot be used to configure resource pools for users. The resource pool automatically checks whether the users are associated with its logical cluster. If they are not, they will be controlled by the resource pool when performing operations on DNs in the logical cluster. ## Examples This example assumes that Cgroups have been created by users in advance. For details about how to create Cgroups, see [Setting a Cgroup](https://docs.opengauss.org/en/docs/latest/performance_tuning_guide/sql_execution_plan_introduction.html). ``` -- Create a default resource pool, and associate it with the Medium Timeshare Cgroup under Workload under DefaultClass. openGauss=# CREATE RESOURCE POOL pool1; -- Create a resource pool, and associate it with the High Timeshare Workload Cgroup under DefaultClass. openGauss=# CREATE RESOURCE POOL pool2 WITH (CONTROL_GROUP="High"); -- Create a resource pool, and associate it with the Low Timeshare Workload Cgroup under class1. openGauss=# CREATE RESOURCE POOL pool3 WITH (CONTROL_GROUP="class1:Low"); -- Create a resource pool, and associate it with the wg1 Workload Cgroup under class1. openGauss=# CREATE RESOURCE POOL pool4 WITH (CONTROL_GROUP="class1:wg1"); -- Create a resource pool, and associate it with the wg2 Workload Cgroup under class1. openGauss=# CREATE RESOURCE POOL pool5 WITH (CONTROL_GROUP="class1:wg2:3"); -- Delete the resource pool. openGauss=# DROP RESOURCE POOL pool1; openGauss=# DROP RESOURCE POOL pool2; openGauss=# DROP RESOURCE POOL pool3; openGauss=# DROP RESOURCE POOL pool4; openGauss=# DROP RESOURCE POOL pool5; ``` ## Helpful Links [ALTER RESOURCE POOL](alter_resource_pool.md) and [DROP RESOURCE POOL](drop_resource_pool.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_resource_pool.md --- # CREATE RESOURCE POOL ## 功能描述 创建一个资源池,并指定此资源池相关联的控制组。 ## 注意事项 只要用户对当前数据库有CREATE权限,就可以创建资源池。 ## 语法格式 ``` CREATE RESOURCE POOL pool_name [WITH (CONTROL_GROUP="group_name",{MEM_PERCENT=pct | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='io_priority' | nodegroup="nodegroupname" | is_foreign=boolean }[, ... ])]; ``` ## 参数说明 * **pool\_name** 资源池名称。 资源池名称不能和当前数据库里已有的资源池重名。 取值范围:字符串,要符合标识符的命名规范。 * **group\_name** 控制组名称。 > \[!NOTE]说明 > > * 设置控制组名称时,语法可以使用双引号,也可以使用单引号。 > * group\_name对大小写敏感。 > * 若数据库管理员指定自定义Class组下的Workload控制组,如control\_group的字符串为:"class1:workload1";代表此资源池指定到class1控制组下的workload1控制组。也可同时指定Workload控制组的层次,如control\_group的字符串为:"class1:workload1:1"。 > * 若数据库用户指定Timeshare控制组代表的字符串,即"Rush"、"High"、"Medium"或"Low"其中一种,如control\_group的字符串为"High";代表资源池指定到DefaultClass控制组下的"High" Timeshare控制组。 取值范围:字符串,要符合说明中的规则,其指定已创建的控制组。 * **stmt** 资源池语句执行的最大并发数量。 取值范围:数值型,-1~2147483647‬。 * **dop** 资源池最大并发度,语句执行时能够创建的最多线程数量。 取值范围:数值型,1~64‬ * **memory\_size** 资源池最大使用内存。 取值范围:字符串,内容范围1KB~2047GB * **mem\_percent** 资源池可用内存占全部内存或者组用户内存使用的比例。 在多租户场景下,组用户和业务用户的mem\_percent范围1-100,默认为20。 在普通场景下,普通用户的mem\_percent范围为0-100,默认值为0。 > \[!NOTE]说明 > > mem\_percent和memory\_limit同时指定时,只有mem\_percent起作用。 * **io\_limits** 资源池每秒可触发IO次数上限。 对于行存,以万次为单位计数,而列存则以正常次数计数。 * **io\_priority** IO利用率高达90%时,重消耗IO作业进行IO资源管控时关联的优先级等级。 包括三档可选:Low、Medium和High。不控制时可设置为None。默认为None。 > \[!NOTE]说明 > > io\_limits和io\_priority的设置都仅对复杂作业有效。包括批量导入(INSERT INTO SELECT,COPY FROM,CREATE TABLE AS等),单DN数据量大约超过500MB的复杂查询和VACUUM FULL等操作。 * **nodegroup** 在逻辑集群模式下,指定逻辑集群名称。必须是存在的逻辑集群。 如果逻辑集群名称包含大写字符、特殊符号或以数字开头,SQL语句中对逻辑集群名称需要加双引号。 * **is\_foreign** 在逻辑集群模式下,指定当前资源池用于控制没有关联本逻辑集群的普通用户的资源。这里的逻辑集群是由资源池nodegroup字段指定的。 > \[!NOTE]说明 > > * nodegroup必须是存在的逻辑集群,不能是elastic\_group和安装的nodegroup (group\_version1)。 > * 如果指定了is\_foreign为true,则资源池不能再关联用户,即不允许通过CREATE USER ... RESOURCE POOL语句来将该资源池配置给用户。该资源池自动检查用户是否关联到资源池指定的逻辑集群,如果用户没有关联到该逻辑集群,则这些用户在逻辑集群所包含的数据库节点上运行将受到该资源池的资源控制。 ## 示例 本示例假定用户已预先成功创建控制组。 ``` --创建一个默认资源池,其控制组为"DefaultClass"组下属的"Medium" Timeshare Workload控制组。 openGauss=# CREATE RESOURCE POOL pool1; -- 创建一个资源池,其控制组指定为"DefaultClass"组下属的"High" Timeshare Workload控制组。 openGauss=# CREATE RESOURCE POOL pool2 WITH (CONTROL_GROUP="High"); -- 创建一个资源池,其控制组指定为"class1"组下属的"Low" Timeshare Workload控制组。 openGauss=# CREATE RESOURCE POOL pool3 WITH (CONTROL_GROUP="class1:Low"); -- 创建一个资源池,其控制组指定为"class1"组下属的"wg1" Workload控制组。 openGauss=# CREATE RESOURCE POOL pool4 WITH (CONTROL_GROUP="class1:wg1"); -- 创建一个资源池,其控制组指定为"class1"组下属的"wg2" Workload控制组。 openGauss=# CREATE RESOURCE POOL pool5 WITH (CONTROL_GROUP="class1:wg2:3"); --删除资源池。 openGauss=# DROP RESOURCE POOL pool1; openGauss=# DROP RESOURCE POOL pool2; openGauss=# DROP RESOURCE POOL pool3; openGauss=# DROP RESOURCE POOL pool4; openGauss=# DROP RESOURCE POOL pool5; ``` ## 相关链接 [ALTER RESOURCE POOL](alter_resource_pool.md),[DROP RESOURCE POOL](drop_resource_pool.md) --- --- url: /zh/docs/latest/sql_reference/create_resource_pool.md --- # CREATE RESOURCE POOL ## 功能描述 创建一个资源池,并指定此资源池相关联的控制组。 ## 注意事项 只有SYSADMIN、VCADMIN可以创建资源池。 ## 语法格式 ``` CREATE RESOURCE POOL pool_name [WITH (CONTROL_GROUP="group_name",{MEM_PERCENT=pct | ACTIVE_STATEMENTS=stmt | MAX_DOP = dop | MEMORY_LIMIT='memory_size' | io_limits=io_limits | io_priority='io_priority' | nodegroup="nodegroupname" | is_foreign=boolean } [, ... ]) ]; ``` ## 参数说明 * **pool\_name** 资源池名称。 资源池名称不能和当前数据库里已有的资源池重名。 取值范围:字符串,要符合标识符的命名规范。 * **group\_name** 控制组名称。 > \[!NOTE]说明 > > * 设置控制组名称时,语法可以使用双引号,也可以使用单引号。 > > * group\_name对大小写敏感。 > > * 若数据库管理员指定自定义Class组下的Workload控制组,如control\_group的字符串为:“class1:workload1”;代表此资源池指定到class1控制组下的workload1控制组。也可同时指定Workload控制组的层次,如control\_group的字符串为:“class1:workload1:1”。 > > * 若数据库用户指定Timeshare控制组代表的字符串,即“Rush”、“High”、“Medium”或“Low”其中一种,如control\_group的字符串为“High”;代表资源池指定到DefaultClass控制组下的“High” Timeshare控制组。 取值范围:字符串,要符合说明中的规则,其指定已创建的控制组。 * **stmt** 资源池语句执行的最大并发数量。 取值范围:数值型,-1~2147483647‬。 * **dop** 资源池最大并发度,语句执行时能够创建的最多线程数量。 取值范围:数值型,1~64 * **memory\_size** 资源池最大使用内存。 取值范围:字符串,内容范围1KB~2047GB * **mem\_percent** 资源池可用内存占全部内存或者组用户内存使用的比例。 在多租户场景下,组用户和业务用户的mem\_percent范围1-100,默认为20。 在普通场景下,普通用户的mem\_percent范围为0-100,默认值为0。 > \[!NOTE]说明 > mem\_percent和memory\_limit同时指定时,只有mem\_percent起作用。 * **io\_limits** 资源池每秒可触发IO次数上限。 对于行存,以万次为单位计数,而列存则以正常次数计数。 取值范围:数值型,0~2147483647‬。 * **io\_priority** IO利用率高达90%时,重消耗IO作业进行IO资源管控时关联的优先级等级。 包括三档可选:Low、Medium和High。不控制时可设置为None。默认为None。 > \[!NOTE]说明 > io\_limits和io\_priority的设置都仅对复杂作业有效。包括批量导入(INSERT INTO SELECT、COPY FROM、CREATE TABLE AS等),单DN数据量大约超过500MB的复杂查询和VACUUM FULL等操作。 * **nodegroup** 在逻辑集群模式下,指定逻辑集群名称。必须是存在的逻辑集群。 如果逻辑集群名称包含大写字符、特殊符号或以数字开头,SQL语句中对逻辑集群名称需要加双引号。 单机下此参数无用。 * **is\_foreign** 在逻辑集群模式下,指定当前资源池用于控制没有关联本逻辑集群的普通用户的资源。这里的逻辑集群是由资源池nodegroup字段指定的。 单机下此参数无用。 > \[!NOTE]说明 > > * nodegroup必须是存在的逻辑集群,不能是elastic\_group和安装的nodegroup (group\_version1)。 > > * 如果指定了is\_foreign为true,则资源池不能再关联用户,即不允许通过CREATE USER ... RESOURCE POOL语句来将该资源池配置给用户。该资源池自动检查用户是否关联到资源池指定的逻辑集群,如果用户没有关联到该逻辑集群,则这些用户在逻辑集群所包含的DN上运行将受到该资源池的资源控制。 ## 示例 本示例假定用户已预先成功创建控制组(创建控制组请参考[设置控制组](https://docs.opengauss.org/zh/docs/latest/performance_tuning_guide/resource_management_preparation.html))。 ``` --创建一个默认资源池,其控制组为"DefaultClass"组下属的"Medium" Timeshare Workload控制组。 openGauss=# CREATE RESOURCE POOL pool1; -- 创建一个资源池,其控制组指定为"DefaultClass"组下属的"High" Timeshare Workload控制组。 openGauss=# CREATE RESOURCE POOL pool2 WITH (CONTROL_GROUP="High"); -- 创建一个资源池,其控制组指定为"class1"组下属的"Low" Timeshare Workload控制组。 openGauss=# CREATE RESOURCE POOL pool3 WITH (CONTROL_GROUP="class1:Low"); -- 创建一个资源池,其控制组指定为"class1"组下属的"wg1" Workload控制组。 openGauss=# CREATE RESOURCE POOL pool4 WITH (CONTROL_GROUP="class1:wg1"); -- 创建一个资源池,其控制组指定为"class1"组下属的"wg2" Workload控制组。 openGauss=# CREATE RESOURCE POOL pool5 WITH (CONTROL_GROUP="class1:wg2:3"); --删除资源池。 openGauss=# DROP RESOURCE POOL pool1; openGauss=# DROP RESOURCE POOL pool2; openGauss=# DROP RESOURCE POOL pool3; openGauss=# DROP RESOURCE POOL pool4; openGauss=# DROP RESOURCE POOL pool5; ``` ## 相关链接 [ALTER RESOURCE POOL](alter_resource_pool.md),[DROP RESOURCE POOL](drop_resource_pool.md) --- --- url: /en/docs/latest-lite/sql_reference/create_role.md --- # CREATE ROLE ## Function **CREATE ROLE** is used to create a role. A role is an entity that owns database objects and permissions. In different environments, a role can be considered a user, a group, or both. ## Precautions * **CREATE ROLE** adds a role to a database. The role does not have the **LOGIN** permission. * Only the user who has the **CREATE ROLE** permission or a system administrator is allowed to create roles. ## Syntax ``` CREATE ROLE role_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [EXPIRED] | DISABLE }; ``` The syntax of role information configuration clause **option** is as follows: ``` {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN rol e_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## Parameter Description * **role\_name** Specifies the name of a role. Value range: a string. It must comply with the naming convention rule, and can contain a maximum of 63 characters. If the value contains more than 63 characters, the database truncates it and retains the first 63 characters as the role name. When a role is created, the database displays a message if the role contains more than 63 characters. > \[!NOTE]NOTE > The identifier must be letters, underscores (\_), digits (0-9), or dollar signs ($) and must start with a letter (a-z) or underscore (\_). * **password** Specifies the login password. A new password must: * Contain at least eight characters. This is the default length. * Differ from the username or the username spelled backward. * Contain at least three of the following character types: uppercase characters, lowercase characters, digits, and special characters (limited to ~!@#$ %^&\*()-\_=+\\|\[{}];:,<.>/?). * The password can also be a ciphertext character string that meets the format requirements. This mode is mainly used to import user data. You are not advised to use it directly. If a ciphertext password is used, the user must know the plaintext corresponding to the ciphertext password and ensure that the plaintext password meets the complexity requirements. The database does not verify the complexity of the ciphertext password. Instead, the security of the ciphertext password is ensured by the user. * Be enclosed by single or double quotation marks. Value range: a character string that cannot be empty. * **EXPIRED** When creating a user, you can specify the **EXPIRED** parameter to create a user whose password is invalid. The user cannot perform simple or extended queries. The statement can be executed only after the password is changed. * **DISABLE** By default, you can change your password unless it is disabled. To disable the password of a user, use this parameter. After the password of a user is disabled, the password will be deleted from the system. The user can connect to the database only through external authentication, for example, Kerberos authentication. Only administrators can enable or disable a password. Common users cannot disable the password of an initial user. To enable a password, run **ALTER USER** and specify the password. > \[!NOTE]NOTE > In the Lite scenario, Kerberos functions of openGauss are unavailable. * **ENCRYPTED | UNENCRYPTED** Controls whether the password is stored encrypted in the system catalogs. According to product security requirement, the password must be stored encrypted. Therefore, **UNENCRYPTED** is forbidden in openGauss. If the password string has already been encrypted in the SHA256 format, it is stored encrypted as it was, regardless of whether **ENCRYPTED** or **UNENCRYPTED** is specified (since the system cannot decrypt the specified encrypted password string). This allows reloading of encrypted passwords during dump/restore. * **SYSADMIN | NOSYSADMIN** Determines whether a new role is a system administrator. Roles having the **SYSADMIN** attribute have the highest permission. Value range: If not specified, **NOSYSADMIN** is the default. * **MONADMIN | NOMONADMIN** Determines whether a role is a monitoring administrator. Value range: If not specified, **NOMONADMIN** is the default. * **OPRADMIN | NOOPRADMIN** Determines whether a role is an O\&M administrator. Value range: If not specified, **NOOPRADMIN** is the default. * **POLADMIN | NOPOLADMIN** Determines whether a role is a security policy administrator. Value range: If not specified, **NOPOLADMIN** is the default. * **AUDITADMIN | NOAUDITADMIN** Determines whether a role has the audit and management attributes. If not specified, **NOAUDITADMIN** is the default. * **CREATEDB | NOCREATEDB** Determines a role's permission to create databases. A new role does not have the permission to create databases. Value range: If not specified, **NOCREATEDB** is the default. * **USEFT | NOUSEFT** This parameter is reserved and not used in this version. * **CREATEROLE | NOCREATEROLE** Determines whether a role will be permitted to create new roles (that is, execute **CREATE ROLE** and **CREATE USER**). A role with the **CREATEROLE** permission can also modify and delete other roles. Value range: If not specified, **NOCREATEROLE** is the default. * **INHERIT | NOINHERIT** Determines whether a role "inherits" the permissions of roles in the same group. It is not recommended. * **LOGIN | NOLOGIN** Determines whether a role is allowed to log in to a database. A role having the **LOGIN** attribute can be considered as a user. Value range: If not specified, **NOLOGIN** is the default. * **REPLICATION | NOREPLICATION** Determines whether a role is allowed to initiate streaming replication or put the system in and out of backup mode. A role having the **REPLICATION** attribute is specific to replication. If not specified, **NOREPLICATION** is the default. * **INDEPENDENT | NOINDEPENDENT** Defines private, independent roles. For a role with the **INDEPENDENT** attribute, administrators' permissions to control and access this role are separated. The rules are as follows: * Administrators have no permission to add, delete, query, modify, copy, or authorize the corresponding table objects without the authorization from the **INDEPENDENT** role. * If permissions related to private user tables are granted to non-private users, the system administrator will obtain the same permissions. * System administrators and security administrators with the **CREATEROLE** attribute have no permission to modify the inheritance relationship of the **INDEPENDENT** role without the authorization of the **INDEPENDENT** role. * System administrators have no permission to modify the owner of the table objects for the **INDEPENDENT** role. * System administrators and security administrators with the **CREATEROLE** attribute have no permission to remove the **INDEPENDENT** attribute of the **INDEPENDENT** role. * System administrators and security administrators with the **CREATEROLE** attribute have no permission to change the database password of the **INDEPENDENT** role. The **INDEPENDENT** role must manage its own password. If the password is lost, it cannot be reset. * The **SYSADMIN** attribute of a user cannot be changed to the **INDEPENDENT** attribute. * **CONNECTION LIMIT** Specifies how many concurrent connections the role can make. > \[!TIP]NOTICE > > * The system administrator is not restricted by this parameter. > * The number of concurrent connections of each primary database node is calculated separately (which is the value of **connlimit**). The number of all connections of openGauss = Value of **connlimit** x Number of normal primary database nodes. Value range: an integer greater than or equal to -1. The default value is **-1**, which means unlimited. * **VALID BEGIN** Sets a date and time when the role's password takes effect. If this clause is omitted, the password takes effect immediately. * **VALID UNTIL** Sets a date and time after which the role's password is no longer valid. If this clause is omitted, the password will be valid for all time. * **RESOURCE POOL** Sets the name of resource pool used by the role. The name belongs to the system catalog **pg\_resource\_pool**. * **USER GROUP** Creates a sub-user. This function is not supported in the current version. * **PERM SPACE** Sets the space available for a user. * **TEMP SPACE** Sets the space allocated to the temporary table of a user. * **SPILL SPACE** Sets the operator disk flushing space of a user. * **NODE GROUP** Specifies the name of the logical cluster associated with a user. This function is not supported in the current version. * **IN ROLE** Lists one or more existing roles to which the new role will be immediately added as a new member. It is not recommended. * **IN GROUP** Specifies an obsolete spelling of **IN ROLE**. It is not recommended. * **ROLE** Lists one or more existing roles which are automatically added as members of the new role. * **ADMIN** Similar to **ROLE**. However, **ADMIN** grants permissions of new roles to other roles. * **USER** Specifies an obsolete spelling of the **ROLE** clause. * **SYSID** The **SYSID** clause is ignored. * **DEFAULT TABLESPACE** The **DEFAULT TABLESPACE** clause is ignored. * **PROFILE** The **PROFILE** clause is ignored. * **PGUSER** In the current version, this attribute is reserved only for forward compatibility. ## Examples ``` -- Create role manager whose password is xxxxxxxxx. openGauss=# CREATE ROLE manager IDENTIFIED BY 'xxxxxxxxx'; -- Create a role with its validity from January 1, 2015 to January 1, 2026. openGauss=# CREATE ROLE miriam WITH LOGIN PASSWORD 'xxxxxxxxx' VALID BEGIN '2015-01-01' VALID UNTIL '2026-01-01'; -- Change the password of role manager to abcd@123. openGauss=# ALTER ROLE manager IDENTIFIED BY 'abcd@123' REPLACE 'xxxxxxxxx'; -- Change role manager to the system administrator. openGauss=# ALTER ROLE manager SYSADMIN; -- Delete role manager. openGauss=# DROP ROLE manager; -- Delete role miriam. openGauss=# DROP ROLE miriam; ``` ## Helpful Links [SET ROLE](set_role.md), [ALTER ROLE](alter_role.md), [DROP ROLE](drop_role.md), and [GRANT](grant.md) --- --- url: /en/docs/latest/sql_reference/create_role.md --- # CREATE ROLE ## Function **CREATE ROLE** creates a role. A role is an entity that owns database objects and permissions. In different environments, a role can be considered a user, a group, or both. ## Precautions * **CREATE ROLE** adds a role to a database. The role does not have the **LOGIN** permission. * Only the user who has the **CREATE ROLE** permission or a system administrator is allowed to create roles. ## Syntax ``` CREATE ROLE role_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [EXPIRED] | DISABLE }; ``` The syntax of role information configuration clause **option** is as follows: ``` {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN rol e_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## Parameter Description * **role\_name** Specifies the name of a role. Value range: a string. It must comply with the naming convention rule, and can contain a maximum of 63 characters. If the value contains more than 63 characters, the database truncates it and retains the first 63 characters as the role name. When a role is created, the database will display a message. > \[!NOTE]NOTE > The identifier must be letters, underscores (\_), digits (0-9), or dollar signs ($) and must start with a letter (a-z) or underscore (\_). * **password** Specifies the login password. A new password must: * Contain at least eight characters. This is the default length. * Differ from the username or the username spelled backward. * Contain at least three of the following character types: uppercase characters, lowercase characters, digits, and special characters (limited to ~!@#$ %^&\*()-\_=+\\|\[{}];:,<.>/?). * The password can also be a ciphertext character string that meets the format requirements. This mode is mainly used to import user data. You are not advised to use it directly. If a ciphertext password is used, the user must know the plaintext corresponding to the ciphertext password and ensure that the plaintext password meets the complexity requirements. The database does not verify the complexity of the ciphertext password. Instead, the security of the ciphertext password is ensured by the user. * Be enclosed by single or double quotation marks. Value range: a character string that cannot be empty. * **EXPIRED** When creating a user, you can specify the **EXPIRED** parameter to create a user whose password is invalid. The user cannot perform simple or extended queries. The statement can be executed only after the password is changed. * **DISABLE** By default, you can change your password unless it is disabled. To disable the password of a user, use this parameter. After the password of a user is disabled, the password will be deleted from the system. The user can connect to the database only through external authentication, for example, Kerberos authentication. Only administrators can enable or disable a password. Common users cannot disable the password of an initial user. To enable a password, run **ALTER USER** and specify the password. * **ENCRYPTED | UNENCRYPTED** Controls whether the password is stored encrypted in the system catalogs. According to product security requirement, the password must be stored encrypted. Therefore, **UNENCRYPTED** is forbidden in openGauss. If the password string has already been encrypted in the SHA256 format, it is stored encrypted as it was, regardless of whether **ENCRYPTED** or **UNENCRYPTED** is specified (since the system cannot decrypt the specified encrypted password string). This allows reloading of encrypted passwords during dump/restore. * **SYSADMIN | NOSYSADMIN** Determines whether a new role is a system administrator. Roles having the **SYSADMIN** attribute have the highest permission. Value range: If not specified, **NOSYSADMIN** is the default. * **MONADMIN | NOMONADMIN** Determines whether a role is a monitoring administrator. Value range: If not specified, **NOMONADMIN** is the default. * **OPRADMIN | NOOPRADMIN** Determines whether a role is an O\&M administrator. Value range: If not specified, **NOOPRADMIN** is the default. * **POLADMIN | NOPOLADMIN** Determines whether a role is a security policy administrator. Value range: If not specified, **NOPOLADMIN** is the default. * **AUDITADMIN | NOAUDITADMIN** Determines whether a role has the audit and management attributes. If not specified, **NOAUDITADMIN** is the default. * **CREATEDB | NOCREATEDB** Determines a role's permission to create databases. A new role does not have the permission to create databases. Value range: If not specified, **NOCREATEDB** is the default. * **USEFT | NOUSEFT** This parameter is reserved and not used in this version. * **CREATEROLE | NOCREATEROLE** Determines whether a role will be permitted to create new roles (that is, execute **CREATE ROLE** and **CREATE USER**). A role with the **CREATEROLE** permission can also modify and delete other roles. Value range: If not specified, **NOCREATEROLE** is the default. * **INHERIT | NOINHERIT** Determines whether a role "inherits" the permissions of roles in the same group. It is not recommended. * **LOGIN | NOLOGIN** Determines whether a role is allowed to log in to a database. A role having the **LOGIN** attribute can be considered as a user. Value range: If not specified, **NOLOGIN** is the default. * **REPLICATION | NOREPLICATION** Determines whether a role is allowed to initiate streaming replication or put the system in and out of backup mode. A role having the **REPLICATION** attribute is specific to replication. If not specified, **NOREPLICATION** is the default. * **INDEPENDENT | NOINDEPENDENT** Defines private, independent roles. For a role with the **INDEPENDENT** attribute, administrators' permissions to control and access this role are separated. The rules are as follows: * Administrators have no permission to add, delete, query, modify, copy, or authorize the corresponding table objects without the authorization from the **INDEPENDENT** role. * If permissions related to private user tables are granted to non-private users, the system administrator will obtain the same permissions. * System administrators and security administrators with the **CREATEROLE** attribute have no permission to modify the inheritance relationship of the **INDEPENDENT** role without the authorization of the **INDEPENDENT** role. * System administrators have no permission to modify the owner of the table objects for the **INDEPENDENT** role. * System administrators and security administrators with the **CREATEROLE** attribute have no permission to remove the **INDEPENDENT** attribute of the **INDEPENDENT** role. * System administrators and security administrators with the **CREATEROLE** attribute have no permission to change the database password of the **INDEPENDENT** role. The **INDEPENDENT** role must manage its own password. If the password is lost, it cannot be reset. * The **SYSADMIN** attribute of a user cannot be changed to the **INDEPENDENT** attribute. * **VCADMIN | NOVCADMIN** This parameter has no actual meaning. * **PERSISTENCE | NOPERSISTENCE** Defines a permanent user. Only the initial user is allowed to create, modify, and delete permanent users with the **PERSISTENCE** attribute. * **CONNECTION LIMIT** Specifies how many concurrent connections the role can make. > \[!TIP]NOTICE > > * The system administrator is not restricted by this parameter. > * The number of concurrent connections of each primary database node is calculated separately (which is the value of **connlimit**). The number of all connections of openGauss = Value of **connlimit** x Number of normal primary database nodes. Value range: an integer greater than or equal to -1. The default value is **-1**, which means unlimited. * **VALID BEGIN** Sets a date and time when the role's password takes effect. If this clause is omitted, the password takes effect immediately. * **VALID UNTIL** Sets a date and time after which the role's password is no longer valid. If this clause is omitted, the password will be valid for all time. * **RESOURCE POOL** Sets the name of resource pool used by the role. The name belongs to the system catalog **pg\_resource\_pool**. * **USER GROUP** Creates a sub-user. This function is not supported in the current version. * **PERM SPACE** Sets the space available for a user. * **TEMP SPACE** Sets the space allocated to the temporary table of a user. * **SPILL SPACE** Sets the operator disk flushing space of a user. * **NODE GROUP** Specifies the name of the logical cluster associated with a user. This function is not supported in the current version. * **IN ROLE** Lists one or more existing roles to which the new role will be immediately added as a new member. It is not recommended. * **IN GROUP** Specifies an obsolete spelling of **IN ROLE**. It is not recommended. * **ROLE** Lists one or more existing roles which are automatically added as members of the new role. * **ADMIN** Similar to **ROLE**. However, **ADMIN** grants permissions of new roles to other roles. * **USER** Specifies an obsolete spelling of the **ROLE** clause. * **SYSID** The **SYSID** clause is ignored. * **DEFAULT TABLESPACE** The **DEFAULT TABLESPACE** clause is ignored. * **PROFILE** The **PROFILE** clause is ignored. * **PGUSER** In the current version, this attribute is reserved only for forward compatibility. ## Examples ``` -- Create role manager whose password is xxxxxxxxx. openGauss=# CREATE ROLE manager IDENTIFIED BY 'xxxxxxxxx'; -- Create a role with its validity from January 1, 2015 to January 1, 2026. openGauss=# CREATE ROLE miriam WITH LOGIN PASSWORD 'xxxxxxxxx' VALID BEGIN '2015-01-01' VALID UNTIL '2026-01-01'; -- Change the password of role manager to abcd@123. openGauss=# ALTER ROLE manager IDENTIFIED BY 'abcd@123' REPLACE 'xxxxxxxxx'; -- Change role manager to the system administrator. openGauss=# ALTER ROLE manager SYSADMIN; -- Delete role manager. openGauss=# DROP ROLE manager; -- Delete role miriam. openGauss=# DROP ROLE miriam; ``` ## Helpful Links [SET ROLE](set_role.md), [ALTER ROLE](alter_role.md), [DROP ROLE](drop_role.md), and [GRANT](grant.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_role.md --- # CREATE ROLE ## 功能描述 创建角色。 角色是拥有数据库对象和权限的实体。在不同的环境中角色可以认为是一个用户,一个组或者兼顾两者。 ## 注意事项 * 在数据库中添加一个新角色,角色无登录权限。 * 创建角色的用户必须具备CREATE ROLE的权限或者是系统管理员。 ## 语法格式 ``` CREATE ROLE role_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [EXPIRED] | DISABLE }; ``` 其中角色信息设置子句option语法为: ``` {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN rol e_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## 参数说明 * **role\_name** 角色名称。 取值范围:字符串,要符合标识符的命名规范,且最多为63个字符。若超过63个字符,数据库会截断并保留前63个字符当做角色名称。在创建角色时,超过63个字符的时候数据库会给出提示信息。 > \[!NOTE]说明 > > 标识符需要为字母、下划线、数字(0-9)或美元符号($),且必须以字母(a-z)或下划线(\_)开头。 * **password** 登录密码。 密码规则如下: * 密码默认不少于8个字符。 * 不能与用户名及用户名倒序相同。 * 至少包含大写字母(A-Z),小写字母(a-z),数字(0-9),非字母数字字符(限定为~!@#$%^&\*()-\_=+\\|\[{}];:,<.>/?)四类字符中的三类字符。 * 密码也可以是符合格式要求的密文字符串,这种情况主要用于用户数据导入场景,不推荐用户直接使用。如果直接使用密文密码,用户需要知道密文密码对应的明文,并且保证明文密码复杂度,数据库不会校验密文密码复杂度,直接使用密文密码的安全性由用户保证。 * 创建角色时,应当使用双引号或单引号将用户密码括起来。 取值范围:不为空的字符串。 * **EXPIRED** 在创建用户时可指定EXPIRED参数,即创建密码失效用户,该用户不允许执行简单查询和扩展查询。只有在修改自身密码后才可正常执行语句。 * **DISABLE** 默认情况下,用户可以更改自己的密码,除非密码被禁用。要禁用用户的密码,请指定DISABLE。禁用某个用户的密码后,将从系统中删除该密码,此类用户只能通过外部认证来连接数据库,例如:kerberos认证。只有管理员才能启用或禁用密码。普通用户不能禁用初始用户的密码。要启用密码,请运行ALTER USER并指定密码。 > \[!NOTE]说明 > > 轻量版场景下,openGauss中kerberos相关功能不可用。 * **ENCRYPTED | UNENCRYPTED** 控制密码存储在系统表里的口令是否加密。按照产品安全要求,密码必须加密存储,所以,UNENCRYPTED在openGauss中禁止使用。因为系统无法对指定的加密口令字符串进行解密,所以如果目前的口令字符串已经是用SHA256加密的格式,则会继续照此存放,而不管是否声明了ENCRYPTED或UNENCRYPTED。这样就允许在dump/restore的时候重新加载加密的口令。 * **SYSADMIN | NOSYSADMIN** 决定一个新角色是否为“系统管理员”,具有SYSADMIN属性的角色拥有系统最高权限。 缺省为NOSYSADMIN。 * **MONADMIN | NOMONADMIN** 定义角色是否是监控管理员。 缺省为NOMONADMIN。 * **OPRADMIN | NOOPRADMIN** 定义角色是否是运维管理员。 缺省为NOOPRADMIN。 * **POLADMIN | NOPOLADMIN** 定义角色是否是安全策略管理员。 缺省为NOPOLADMIN。 * **AUDITADMIN | NOAUDITADMIN** 定义角色是否有审计管理属性。 缺省为NOAUDITADMIN。 * **CREATEDB | NOCREATEDB** 决定一个新角色是否能创建数据库。 新角色没有创建数据库的权限。 缺省为NOCREATEDB。 * **USEFT | NOUSEFT** 该参数为保留参数,暂未启用。 * **CREATEROLE | NOCREATEROLE** 决定一个角色是否可以创建新角色(也就是执行CREATE ROLE和CREATE USER)。 一个拥有CREATEROLE权限的角色也可以修改和删除其他角色。 缺省为NOCREATEROLE。 * **INHERIT | NOINHERIT** 这些子句决定一个角色是否“继承”它所在组的角色的权限。不推荐使用。 * **LOGIN | NOLOGIN** 具有LOGIN属性的角色才可以登录数据库。一个拥有LOGIN属性的角色可以认为是一个用户。 缺省为NOLOGIN。 * **REPLICATION | NOREPLICATION** 定义角色是否允许流复制或设置系统为备份模式。REPLICATION属性是特定的角色,仅用于复制。 缺省为NOREPLICATION。 * **INDEPENDENT | NOINDEPENDENT** 定义私有、独立的角色。具有INDEPENDENT属性的角色,管理员对其进行的控制、访问的权限被分离,具体规则如下: * 未经INDEPENDENT角色授权,系统管理员无权对其表对象进行增、删、查、改、拷贝、授权操作。 * 若将私有用户表的相关权限授予其他非私有用户,系统管理员也会获得同样的权限。 * 未经INDEPENDENT角色授权,系统管理员和拥有CREATEROLE属性的安全管理员无权修改INDEPENDENT角色的继承关系。 * 系统管理员无权修改INDEPENDENT角色的表对象的属主。 * 系统管理员和拥有CREATEROLE属性的安全管理员无权去除INDEPENDENT角色的INDEPENDENT属性。 * 系统管理员和拥有CREATEROLE属性的安全管理员无权修改INDEPENDENT角色的数据库口令,INDEPENDENT角色需管理好自身口令,口令丢失无法重置。 * 管理员属性用户不允许定义修改为INDEPENDENT属性。 * **CONNECTION LIMIT** 声明该角色可以使用的并发连接数量。 > \[!TIP]须知 > > * 系统管理员不受此参数的限制。 > * connlimit数据库主节点单独统计,openGauss整体的连接数 = connlimit \* 当前正常数据库主节点个数。 取值范围:整数,>=-1,缺省值为-1,表示没有限制。 * **VALID BEGIN** 设置角色生效的时间戳。如果省略了该子句,角色无有效开始时间限制。 * **VALID UNTIL** 设置角色失效的时间戳。如果省略了该子句,角色无有效结束时间限制。 * **RESOURCE POOL** 设置角色使用的resource pool名称,该名称属于系统表:pg\_resource\_pool。 * **USER GROUP** 创建一个user的子用户。当前版本暂不支持。 * **PERM SPACE** 设置用户使用空间的大小。 * **TEMP SPACE** 设置用户临时表存储空间限额。 * **SPILL SPACE** 设置用户算子落盘空间限额。 * **NODE GROUP** 设置用户关联的逻辑集群名称。当前版本暂不支持。 * **IN ROLE** 新角色立即拥有IN ROLE子句中列出的一个或多个现有角色拥有的权限。不推荐使用。 * **IN GROUP** IN GROUP是IN ROLE过时的拼法。不推荐使用。 * **ROLE** ROLE子句列出一个或多个现有的角色,它们将自动添加为这个新角色的成员,拥有新角色所有的权限。 * **ADMIN** ADMIN子句类似ROLE子句,不同的是ADMIN后的角色可以把新角色的权限赋给其他角色。 * **USER** USER子句是ROLE子句过时的拼法。 * **SYSID** SYSID子句将被忽略,无实际意义。 * **DEFAULT TABLESPACE** DEFAULT TABLESPACE子句将被忽略,无实际意义。 * **PROFILE** PROFILE子句将被忽略,无实际意义。 * **PGUSER** 当前版本该属性没有实际意义,仅为了语法的前向兼容而保留。 ## 示例 ``` --创建一个角色,名为manager,密码为xxxxxxxxx。 openGauss=# CREATE ROLE manager IDENTIFIED BY 'xxxxxxxxx'; --创建一个角色,从2015年1月1日开始生效,到2026年1月1日失效。 openGauss=# CREATE ROLE miriam WITH LOGIN PASSWORD 'xxxxxxxxx' VALID BEGIN '2015-01-01' VALID UNTIL '2026-01-01'; --修改角色manager的密码为abcd@123。 openGauss=# ALTER ROLE manager IDENTIFIED BY '$$$$$$$$' REPLACE 'xxxxxxxxx'; --修改角色manager为系统管理员。 openGauss=# ALTER ROLE manager SYSADMIN; --删除角色manager。 openGauss=# DROP ROLE manager; --删除角色miriam。 openGauss=# DROP ROLE miriam; ``` ## 相关链接 [SET ROLE](set_role.md),[ALTER ROLE](alter_role.md),[DROP ROLE](drop_role.md),[GRANT](grant.md) --- --- url: /zh/docs/latest/ograc/sql_reference/ddl/create_role.md --- # CREATE ROLE ## 功能描述 该语句主要用来创建数据库角色。 角色是一组权限的集合,包括对象权限和系统权限。数据库初始化完成后,系统会自动创建一组预定义角色,这些角色本质上是权限的集合,具体角色如下: **DBA** 该角色不可删除,且具有所有的系统权限。 **RESOURCE** 拥有创建表、序列、存储过程、函数、触发器的权限。 **CONNECT** 拥有连接数据库的权限。 ## 注意事项 \-- 相关用户需要被授予CREATE ROLE的系统权限才可以执行本语句。 \-- 角色名称不允许和数据库中已有的角色名称、用户名称重复,否则会报错。 ## 语法格式 CREATE ROLE role\_name \[ IDENTIFIED BY password \[ ENCRYPTED ]] ## 参数说明 * **role\_name**: 如果角色名称包括 #$\_ 以外的空格或者特殊字符,那么角色名称应使用反引号(\`\`)或双引号("")括起来。 * **IDENTIFIED BY**: 创建的角色使用密码。IDENTIFIED BY 后面为具体的密码内容。 * **password**: 暂未使用的预留属性。 * **ENCRYPTED**: 标识指定的密码是否为密文,如果为密文则不需要校验密码规范。 使用 ENCRYPTED 创建的角色需要使用明文密码登录,因此不建议采用该种方式创建角色。 ## 示例 \--删除角色role\_explorer。 DROP ROLE role\_explorer; \--创建角色role\_explorer。 CREATE ROLE role\_explorer; --- --- url: /zh/docs/latest/sql_reference/create_role.md --- # CREATE ROLE ## 功能描述 创建角色。 角色是拥有数据库对象和权限的实体。在不同的环境中角色可以认为是一个用户,一个组或者兼顾两者。 ## 注意事项 * 在数据库中添加一个新角色,角色无登录权限。 * 创建角色的用户必须具备CREATE ROLE的权限或者是系统管理员。 ## 语法格式 ``` CREATE ROLE role_name [ [ WITH ] option [ ... ] ] [ ENCRYPTED | UNENCRYPTED ] { PASSWORD | IDENTIFIED BY } { 'password' [EXPIRED] | DISABLE }; ``` 其中角色信息设置子句option语法为: ``` {SYSADMIN | NOSYSADMIN} | {MONADMIN | NOMONADMIN} | {OPRADMIN | NOOPRADMIN} | {POLADMIN | NOPOLADMIN} | {AUDITADMIN | NOAUDITADMIN} | {CREATEDB | NOCREATEDB} | {USEFT | NOUSEFT} | {CREATEROLE | NOCREATEROLE} | {INHERIT | NOINHERIT} | {LOGIN | NOLOGIN} | {REPLICATION | NOREPLICATION} | {INDEPENDENT | NOINDEPENDENT} | {VCADMIN | NOVCADMIN} | {PERSISTENCE | NOPERSISTENCE} | CONNECTION LIMIT connlimit | VALID BEGIN 'timestamp' | VALID UNTIL 'timestamp' | RESOURCE POOL 'respool' | USER GROUP 'groupuser' | PERM SPACE 'spacelimit' | TEMP SPACE 'tmpspacelimit' | SPILL SPACE 'spillspacelimit' | NODE GROUP logic_cluster_name | IN ROLE role_name [, ...] | IN GROUP role_name [, ...] | ROLE role_name [, ...] | ADMIN rol e_name [, ...] | USER role_name [, ...] | SYSID uid | DEFAULT TABLESPACE tablespace_name | PROFILE DEFAULT | PROFILE profile_name | PGUSER ``` ## 参数说明 * **role\_name** 角色名称。 取值范围:字符串,要符合标识符的命名规范,且最多为63个字符。若超过63个字符,数据库会截断并保留前63个字符当做角色名称。在创建角色时,超过63个字符的时候数据库会给出提示信息。 > \[!NOTE]说明 > > 标识符需要为字母、下划线、数字(0-9)或美元符号($),且必须以字母(a-z)或下划线(\_)开头。 * **password** 登录密码。 密码规则如下: * 密码默认不少于8个字符。 * 不能与用户名及用户名倒序相同。 * 至少包含大写字母(A-Z)、小写字母(a-z)、数字(0-9)、非字母数字字符(限定为~!@#$%^&\*()-\_=+\\|\[{}];:,<.>/?)四类字符中的三类字符。 * 密码也可以是符合格式要求的密文字符串,这种情况主要用于用户数据导入场景,不推荐用户直接使用。如果直接使用密文密码,用户需要知道密文密码对应的明文,并且保证明文密码复杂度,数据库不会校验密文密码复杂度,直接使用密文密码的安全性由用户保证。 * 创建角色时,应当使用双引号或单引号将用户密码括起来。 取值范围:不为空的字符串。 * **EXPIRED** 在创建用户时可指定EXPIRED参数,即创建密码失效用户,该用户不允许执行简单查询和扩展查询。只有在修改自身密码后才可正常执行语句。 * **DISABLE** 默认情况下,用户可以更改自己的密码,除非密码被禁用。要禁用用户的密码,请指定DISABLE。禁用某个用户的密码后,将从系统中删除该密码,此类用户只能通过外部认证来连接数据库,例如:kerberos认证。只有管理员才能启用或禁用密码。普通用户不能禁用初始用户的密码。要启用密码,请运行ALTER USER并指定密码。 * **ENCRYPTED | UNENCRYPTED** 控制密码存储在系统表里的口令是否加密。按照产品安全要求,密码必须加密存储,所以,UNENCRYPTED在openGauss中禁止使用。因为系统无法对指定的加密口令字符串进行解密,所以如果目前的口令字符串已经是用SHA256加密的格式,则会继续照此存放,而不管是否声明了ENCRYPTED或UNENCRYPTED。这样就允许在dump/restore的时候重新加载加密的口令。 * **SYSADMIN | NOSYSADMIN** 决定一个新角色是否为“系统管理员”,具有SYSADMIN属性的角色拥有系统最高权限。 缺省为NOSYSADMIN。 * **MONADMIN | NOMONADMIN** 定义角色是否是监控管理员。 缺省为NOMONADMIN。 * **OPRADMIN | NOOPRADMIN** 定义角色是否是运维管理员。 缺省为NOOPRADMIN。 * **POLADMIN | NOPOLADMIN** 定义角色是否是安全策略管理员。 缺省为NOPOLADMIN。 * **AUDITADMIN | NOAUDITADMIN** 定义角色是否有审计管理属性。 缺省为NOAUDITADMIN。 * **CREATEDB | NOCREATEDB** 决定一个新角色是否能创建数据库。 新角色没有创建数据库的权限。 缺省为NOCREATEDB。 * **USEFT | NOUSEFT** 该参数为保留参数,暂未启用。 * **CREATEROLE | NOCREATEROLE** 决定一个角色是否可以创建新角色(也就是执行CREATE ROLE和CREATE USER)。 一个拥有CREATEROLE权限的角色也可以修改和删除其他角色。 缺省为NOCREATEROLE。 * **INHERIT | NOINHERIT** 这些子句决定一个角色是否“继承”它所在组的角色的权限。不推荐使用。 * **LOGIN | NOLOGIN** 具有LOGIN属性的角色才可以登录数据库。一个拥有LOGIN属性的角色可以认为是一个用户。 缺省为NOLOGIN。 * **REPLICATION | NOREPLICATION** 定义角色是否允许流复制或设置系统为备份模式。REPLICATION属性是特定的角色,仅用于复制。 缺省为NOREPLICATION。 * **INDEPENDENT | NOINDEPENDENT** 定义私有、独立的角色。具有INDEPENDENT属性的角色,管理员对其进行的控制、访问的权限被分离,具体规则如下: * 未经INDEPENDENT角色授权,系统管理员无权对其表对象进行增、删、查、改、拷贝、授权操作。 * 若将私有用户表的相关权限授予其他非私有用户,系统管理员也会获得同样的权限。 * 未经INDEPENDENT角色授权,系统管理员和拥有CREATEROLE属性的安全管理员无权修改INDEPENDENT角色的继承关系。 * 系统管理员无权修改INDEPENDENT角色的表对象的属主。 * 系统管理员和拥有CREATEROLE属性的安全管理员无权去除INDEPENDENT角色的INDEPENDENT属性。 * 系统管理员和拥有CREATEROLE属性的安全管理员无权修改INDEPENDENT角色的数据库口令,INDEPENDENT角色需管理好自身口令,口令丢失无法重置。 * 管理员属性用户不允许定义修改为INDEPENDENT属性。 * **VCADMIN | NOVCADMIN** 该版本没有实际意义。 * **PERSISTENCE | NOPERSISTENCE** 定义永久用户。仅允许初始用户创建、修改和删除具有PERSISTENCE属性的永久用户。 * **CONNECTION LIMIT** 声明该角色可以使用的并发连接数量。 > \[!TIP]须知 > > * 系统管理员不受此参数的限制。 > * connlimit数据库主节点单独统计,openGauss整体的连接数 = connlimit \* 当前正常数据库主节点个数。 取值范围:整数,>=-1,缺省值为-1,表示没有限制。 * **VALID BEGIN** 设置角色生效的时间戳。如果省略了该子句,角色无有效开始时间限制。 * **VALID UNTIL** 设置角色失效的时间戳。如果省略了该子句,角色无有效结束时间限制。 * **RESOURCE POOL** 设置角色使用的resource pool名称,该名称属于系统表:pg\_resource\_pool。 * **USER GROUP** 创建一个user的子用户。当前版本暂不支持。 * **PERM SPACE** 设置用户使用空间的大小。 * **TEMP SPACE** 设置用户临时表存储空间限额。 * **SPILL SPACE** 设置用户算子落盘空间限额。 * **NODE GROUP** 设置用户关联的逻辑集群名称。当前版本暂不支持。 * **IN ROLE** 新角色立即拥有IN ROLE子句中列出的一个或多个现有角色拥有的权限。不推荐使用。 * **IN GROUP** IN GROUP是IN ROLE过时的拼法。不推荐使用。 * **ROLE** ROLE子句列出一个或多个现有的角色,它们将自动添加为这个新角色的成员,拥有新角色所有的权限。 * **ADMIN** ADMIN子句类似ROLE子句,不同的是ADMIN后的角色可以把新角色的权限赋给其他角色。 * **USER** USER子句是ROLE子句过时的拼法。 * **SYSID** SYSID子句将被忽略,无实际意义。 * **DEFAULT TABLESPACE** DEFAULT TABLESPACE子句将被忽略,无实际意义。 * **PROFILE** PROFILE子句将被忽略,无实际意义。 * **PGUSER** 当前版本该属性没有实际意义,仅为了语法的前向兼容而保留。 ## 示例 ``` --创建一个角色,名为manager,密码为xxxxxxxxx。 openGauss=# CREATE ROLE manager IDENTIFIED BY 'xxxxxxxxx'; --创建一个角色,从2015年1月1日开始生效,到2026年1月1日失效。 openGauss=# CREATE ROLE miriam WITH LOGIN PASSWORD 'xxxxxxxxx' VALID BEGIN '2015-01-01' VALID UNTIL '2026-01-01'; --修改角色manager的密码为abcd@123。 openGauss=# ALTER ROLE manager IDENTIFIED BY '$$$$$$$$' REPLACE 'xxxxxxxxx'; --修改角色manager为系统管理员。 openGauss=# ALTER ROLE manager SYSADMIN; --删除角色manager。 openGauss=# DROP ROLE manager; --删除角色miriam。 openGauss=# DROP ROLE miriam; ``` ## 相关链接 [SET ROLE](set_role.md),[ALTER ROLE](alter_role.md),[DROP ROLE](drop_role.md),[GRANT](grant.md) --- --- url: /en/docs/latest-lite/sql_reference/create_row_level_security_policy.md --- # CREATE ROW LEVEL SECURITY POLICY ## Function **CREATE ROW LEVEL SECURITY POLICY** creates a row-level access control policy for a table. The policy takes effect only after row-level access control is enabled (by running **ALTER TABLE... ENABLE ROW LEVEL SECURITY**). Otherwise, this statement does not take effect. Currently, row-level access control affects the read (**SELECT**, **UPDATE**, **DELETE**) of data tables and does not affect the write (**INSERT** and **MERGE INTO**) of data tables. The table owner or system administrators can create an expression in the **USING** clause. When the client reads the data table, the database server combines the expressions that meet the condition and applies it to the execution plan in the statement rewriting phase of a query. For each tuple in a data table, if the expression returns **TRUE**, the tuple is visible to the current user; if the expression returns **FALSE** or **NULL**, the tuple is invisible to the current user. A row-level access control policy name is specific to a table. A data table cannot have row-level access control policies with the same name. Different data tables can have the same row-level access control policy. Row-level access control policies can be applied to specified operations (**SELECT**, **UPDATE**, **DELETE**, and **ALL**). **ALL** indicates that **SELECT**, **UPDATE**, and **DELETE** will be affected. For a new row-level access control policy, the default value **ALL** will be used if you do not specify the operations that will be affected. Row-level access control policies can be applied to a specified user (role) or to all users (**PUBLIC**). For a new row-level access control policy, the default value **PUBLIC** will be used if you do not specify the user that will be affected. ## Precautions * Row-level access control policies can be defined for row-store tables, row-store partitioned tables, column-store tables, column-store partitioned tables, unlogged tables, and hash tables. * Row-level access control policies cannot be defined for foreign tables and local temporary tables. * Row-level access control policies cannot be defined for views. * A maximum of 100 row-level access control policies can be defined for a table. * System administrators are not affected by row-level access control policies and can view all data in a table. * Tables queried by using SQL statements, views, functions, and stored procedures are affected by row-level access control policies. ## Syntax ``` CREATE [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ AS { PERMISSIVE | RESTRICTIVE } ] [ FOR { ALL | SELECT | UPDATE | DELETE } ] [ TO { role_name | PUBLIC | CURRENT_USER | SESSION_USER } [, ...] ] USING ( using_expression ) ``` ## Parameter Description * **policy\_name** Specifies the name of a row-level access control policy to be created. The names of row-level access control policies for a table must be unique. * **table\_name** Specifies the name of a table to which a row-level access control policy is applied. * **PERMISSIVE | RESTRICTIVE** **PERMISSIVE** enables the permissive policy for row-level access control. The conditions of the permissive policy are joined through the OR expression. **RESTRICTIVE** enables the restrictive policy for row-level access control. The conditions of the restrictive policy are joined through the AND expression. The join methods are as follows: ``` (using_expression_permissive_1 OR using_expression_permissive_2 ...) AND (using_expression_restrictive_1 AND using_expression_restrictive_2 ...) ``` The default value is **PERMISSIVE**. * **command** Specifies the SQL operations affected by a row-level access control policy, including **ALL**, **SELECT**, **UPDATE**, and **DELETE**. If this parameter is not specified, the default value **ALL** will be used, covering **SELECT**, **UPDATE**, and **DELETE**. If *command* is set to **SELECT**, only tuple data that meets the condition (the return value of *using\_expression* is **TRUE**) can be queried. The operations that are affected include **SELECT**, **UPDATE.... RETURNING**, and **DELETE... RETURNING**. If *command* is set to **UPDATE**, only tuple data that meets the condition (the return value of *using\_expression* is **TRUE**) can be updated. The operations that are affected include **UPDATE**, **UPDATE ... RETURNING**, and **SELECT ... FOR UPDATE/SHARE**. If *command* is set to **DELETE**, only tuple data that meets the condition (the return value of *using\_expression* is **TRUE**) can be deleted. The operations that are affected include **DELETE** and **DELETE ... RETURNING**. The following table describes the relationship between row-level access control policies and SQL statements. **Table 1** Relationship between row-level access control policies and SQL statements * **role\_name** Specifies database users affected by a row-level access control policy. If this parameter is not specified, the default value **PUBLIC** will be used, indicating that all database users will be affected. You can specify multiple affected database users. > \[!TIP]NOTICE > System administrators are not affected by row access control. * **using\_expression** Specifies an expression defined for a row-level access control policy (return type: boolean). The expression cannot contain aggregate functions or window functions. In the statement rewriting phase of a query, if row-level access control for a data table is enabled, the expressions that meet the specified conditions will be added to the plan tree. The expression is calculated for each tuple in the data table. For **SELECT**, **UPDATE**, and **DELETE**, row data is visible to the current user only when the return value of the expression is **TRUE**. If the expression returns **FALSE**, the tuple is invisible to the current user. In this case, the user cannot view the tuple through the **SELECT** statement, update the tuple through the **UPDATE** statement, or delete the tuple through the **DELETE** statement. ## Examples ``` -- Create user alice. openGauss=# CREATE USER alice PASSWORD 'xxxxxxxxx'; -- Create user bob. openGauss=# CREATE USER bob PASSWORD 'xxxxxxxxx'; -- Create the data table all_data. openGauss=# CREATE TABLE all_data(id int, role varchar(100), data varchar(100)); -- Insert data into the data table. openGauss=# INSERT INTO all_data VALUES(1, 'alice', 'alice data'); openGauss=# INSERT INTO all_data VALUES(2, 'bob', 'bob data'); openGauss=# INSERT INTO all_data VALUES(3, 'peter', 'peter data'); -- Grant the read permission on the all_data table to users alice and bob. openGauss=# GRANT SELECT ON all_data TO alice, bob; -- Enable row-level access control. openGauss=# ALTER TABLE all_data ENABLE ROW LEVEL SECURITY; -- Create a row-level access control policy to specify that the current user can view only their own data. openGauss=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING(role = CURRENT_USER); -- View information about the all_data table. openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_rls" USING (((role)::name = "current_user"())) Has OIDs: no Options: orientation=row, compression=no, enable_rowsecurity=true -- Run SELECT. openGauss=# SELECT * FROM all_data; id | role | data ----+-------+------------ 1 | alice | alice data 2 | bob | bob data 3 | peter | peter data (3 rows) openGauss=# EXPLAIN(COSTS OFF) SELECT * FROM all_data; QUERY PLAN ---------------------- Seq Scan on all_data (1 row) -- Switch to user alice and run SELECT. openGauss=# SELECT * FROM all_data; id | role | data ----+-------+------------ 1 | alice | alice data (1 row) openGauss=# EXPLAIN(COSTS OFF) SELECT * FROM all_data; QUERY PLAN ---------------------------------------------------------------- Seq Scan on all_data Filter: ((role)::name = 'alice'::name) Notice: This query is influenced by row level security feature (3 rows) ``` ## Helpful Links [DROP ROW LEVEL SECURITY POLICY](drop_row_level_security_policy.md), [ALTER ROW LEVEL SECURITY POLICY](alter_row_level_security_policy.md) --- --- url: /en/docs/latest/sql_reference/create_row_level_security_policy.md --- # CREATE ROW LEVEL SECURITY POLICY ## Function **CREATE ROW LEVEL SECURITY POLICY** creates a row-level access control policy for a table. The policy takes effect only after row-level access control is enabled (by running **ALTER TABLE... ENABLE ROW LEVEL SECURITY**). Otherwise, this statement does not take effect. Currently, row-level access control affects the read (**SELECT**, **UPDATE**, **DELETE**) of data tables and does not affect the write (**INSERT** and **MERGE INTO**) of data tables. The table owner or system administrators can create an expression in the **USING** clause. When the client reads the data table, the database server combines the expressions that meet the condition and applies it to the execution plan in the statement rewriting phase of a query. For each tuple in a data table, if the expression returns **TRUE**, the tuple is visible to the current user; if the expression returns **FALSE** or **NULL**, the tuple is invisible to the current user. A row-level access control policy name is specific to a table. A data table cannot have row-level access control policies with the same name. Different data tables can have the same row-level access control policy. Row-level access control policies can be applied to specified operations (**SELECT**, **UPDATE**, **DELETE**, and **ALL**). **ALL** indicates that **SELECT**, **UPDATE**, and **DELETE** will be affected. For a new row-level access control policy, the default value **ALL** will be used if you do not specify the operations that will be affected. Row-level access control policies can be applied to a specified user (role) or to all users (**PUBLIC**). For a new row-level access control policy, the default value **PUBLIC** will be used if you do not specify the user that will be affected. ## Precautions * Row-level access control policies can be defined for row-store tables, row-store partitioned tables, column-store tables, column-store partitioned tables, unlogged tables, and hash tables. * Row-level access control policies cannot be defined for foreign tables and local temporary tables. * Row-level access control policies cannot be defined for views. * A maximum of 100 row-level access control policies can be defined for a table. * System administrators are not affected by row-level access control policies and can view all data in a table. * Tables queried by using SQL statements, views, functions, and stored procedures are affected by row-level access control policies. ## Syntax ``` CREATE [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ AS { PERMISSIVE | RESTRICTIVE } ] [ FOR { ALL | SELECT | UPDATE | DELETE } ] [ TO { role_name | PUBLIC | CURRENT_USER | SESSION_USER } [, ...] ] USING ( using_expression ) ``` ## Parameter Description * **policy\_name** Specifies the name of a row-level access control policy to be created. The names of row-level access control policies for a table must be unique. * **table\_name** Specifies the name of a table to which a row-level access control policy is applied. * **PERMISSIVE | RESTRICTIVE** **PERMISSIVE** enables the permissive policy for row-level access control. The conditions of the permissive policy are joined through the OR expression. **RESTRICTIVE** enables the restrictive policy for row-level access control. The conditions of the restrictive policy are joined through the AND expression. The join methods are as follows: ``` (using_expression_permissive_1 OR using_expression_permissive_2 ...) AND (using_expression_restrictive_1 AND using_expression_restrictive_2 ...) ``` The default value is **PERMISSIVE**. * **command** Specifies the SQL operations affected by a row-level access control policy, including **ALL**, **SELECT**, **UPDATE**, and **DELETE**. If this parameter is not specified, the default value **ALL** will be used, covering **SELECT**, **UPDATE**, and **DELETE**. If *command* is set to **SELECT**, only tuple data that meets the condition (the return value of *using\_expression* is **TRUE**) can be queried. The operations that are affected include **SELECT**, **UPDATE.... RETURNING**, and **DELETE... RETURNING**. If *command* is set to **UPDATE**, only tuple data that meets the condition (the return value of *using\_expression* is **TRUE**) can be updated. The operations that are affected include **UPDATE**, **UPDATE ... RETURNING**, and **SELECT ... FOR UPDATE/SHARE**. If *command* is set to **DELETE**, only tuple data that meets the condition (the return value of *using\_expression* is **TRUE**) can be deleted. The operations that are affected include **DELETE** and **DELETE ... RETURNING**. The following table describes the relationship between row-level access control policies and SQL statements. **Table 1** Relationship between row-level access control policies and SQL statements * **role\_name** Specifies database users affected by a row-level access control policy. If this parameter is not specified, the default value **PUBLIC** will be used, indicating that all database users will be affected. You can specify multiple affected database users. > \[!TIP]NOTICE > System administrators are not affected by row access control. * **using\_expression** Specifies an expression defined for a row-level access control policy (return type: boolean). The expression cannot contain aggregate functions or window functions. In the statement rewriting phase of a query, if row-level access control for a data table is enabled, the expressions that meet the specified conditions will be added to the plan tree. The expression is calculated for each tuple in the data table. For **SELECT**, **UPDATE**, and **DELETE**, row data is visible to the current user only when the return value of the expression is **TRUE**. If the expression returns **FALSE**, the tuple is invisible to the current user. In this case, the user cannot view the tuple through the **SELECT** statement, update the tuple through the **UPDATE** statement, or delete the tuple through the **DELETE** statement. ## Examples ``` -- Create user alice. openGauss=# CREATE USER alice PASSWORD 'xxxxxxxxx'; -- Create user bob. openGauss=# CREATE USER bob PASSWORD 'xxxxxxxxx'; -- Create the data table all_data. openGauss=# CREATE TABLE all_data(id int, role varchar(100), data varchar(100)); -- Insert data into the data table. openGauss=# INSERT INTO all_data VALUES(1, 'alice', 'alice data'); openGauss=# INSERT INTO all_data VALUES(2, 'bob', 'bob data'); openGauss=# INSERT INTO all_data VALUES(3, 'peter', 'peter data'); -- Grant the read permission on the all_data table to users alice and bob. openGauss=# GRANT SELECT ON all_data TO alice, bob; -- Enable row-level access control. openGauss=# ALTER TABLE all_data ENABLE ROW LEVEL SECURITY; -- Create a row-level access control policy to specify that the current user can view only their own data. openGauss=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING(role = CURRENT_USER); -- View information about the all_data table. openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_rls" USING (((role)::name = "current_user"())) Has OIDs: no Options: orientation=row, compression=no, enable_rowsecurity=true -- Run SELECT. openGauss=# SELECT * FROM all_data; id | role | data ----+-------+------------ 1 | alice | alice data 2 | bob | bob data 3 | peter | peter data (3 rows) openGauss=# EXPLAIN(COSTS OFF) SELECT * FROM all_data; QUERY PLAN ---------------------- Seq Scan on all_data (1 row) -- Switch to user alice and run SELECT. openGauss=# SELECT * FROM all_data; id | role | data ----+-------+------------ 1 | alice | alice data (1 row) openGauss=# EXPLAIN(COSTS OFF) SELECT * FROM all_data; QUERY PLAN ---------------------------------------------------------------- Seq Scan on all_data Filter: ((role)::name = 'alice'::name) Notice: This query is influenced by row level security feature (3 rows) ``` ## Helpful Links [DROP ROW LEVEL SECURITY POLICY](drop_row_level_security_policy.md), [ALTER ROW LEVEL SECURITY POLICY](alter_row_level_security_policy.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_row_level_security_policy.md --- # CREATE ROW LEVEL SECURITY POLICY ## 功能描述 对表创建行访问控制策略。 当对表创建了行访问控制策略,只有打开该表的行访问控制开关(ALTER TABLE ... ENABLE ROW LEVEL SECURITY),策略才能生效。否则不生效。 当前行访问控制影响数据表的读取操作(SELECT、UPDATE、DELETE),暂不影响数据表的写入操作(INSERT、MERGE INTO)。表所有者或系统管理员可以在USING子句中创建表达式,在客户端执行数据表读取操作时,数据库后台在查询重写阶段会将满足条件的表达式拼接并应用到执行计划中。针对数据表的每一条元组,当USING表达式返回TRUE时,元组对当前用户可见,当USING表达式返回FALSE或NULL时,元组对当前用户不可见。 行访问控制策略名称是针对表的,同一个数据表上不能有同名的行访问控制策略;对不同的数据表,可以有同名的行访问控制策略。 行访问控制策略可以应用到指定的操作(SELECT、UPDATE、DELETE、ALL),ALL表示会影响SELECT、UPDATE、DELETE三种操作;定义行访问控制策略时,若未指定受影响的相关操作,默认为ALL。 行访问控制策略可以应用到指定的用户(角色),也可应用到全部用户(PUBLIC);定义行访问控制策略时,若未指定受影响的用户,默认为PUBLIC。 ## 注意事项 * 支持对行存表、行存分区表、列存表、列存分区表、unlogged表、hash表定义行访问控制策略。 * 不支持外表、本地临时表定义行访问控制策略。 * 不支持对视图定义行访问控制策略。 * 同一张表上可以创建多个行访问控制策略,一张表最多创建100个行访问控制策略。 * 系统管理员不受行访问控制影响,可以查看表的全量数据。 * 通过SQL语句、视图、函数、存储过程查询包含行访问控制策略的表,都会受影响。 ## 语法格式 ``` CREATE [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ AS { PERMISSIVE | RESTRICTIVE } ] [ FOR { ALL | SELECT | UPDATE | DELETE } ] [ TO { role_name | PUBLIC | CURRENT_USER | SESSION_USER } [, ...] ] USING ( using_expression ) ``` ## 参数说明 * **policy\_name** 行访问控制策略名称,同一个数据表上行访问控制策略名称不能相同。 * **table\_name** 行访问控制策略的表名。 * **PERMISSIVE | RESTRICTIVE** PERMISSIVE指定行访问控制策略为宽容性策略,宽容性策略的条件用OR表达式拼接。 RESTRICTIVE指定行访问控制策略为限制性策略,限制性策略的条件用AND表达式拼接。拼接方式如下: ``` (using_expression_permissive_1 OR using_expression_permissive_2 ...) AND (using_expression_restrictive_1 AND using_expression_restrictive_2 ...) ``` 缺省值为PERMISSIVE。 * **command** 当前行访问控制影响的SQL操作,可指定操作包括:ALL、SELECT、UPDATE、DELETE。当未指定时,ALL为默认值,涵盖SELECT、UPDATE、DELETE操作。 当command为SELECT时,SELECT类操作受行访问控制的影响,只能查看到满足条件(using\_expression返回值为TRUE)的元组数据,受影响的操作包括SELECT, SELECT FOR UPDATE/SHARE,UPDATE ... RETURNING,DELETE ... RETURNING。不允许修改、删除受到访问限制的数据。 当command为UPDATE时,UPDATE类操作受行访问控制的影响,只能更新满足条件(using\_expression返回值为TRUE)的元组数据,受影响的操作包括UPDATE, UPDATE ... RETURNING, SELECT ... FOR UPDATE/SHARE。 当command为DELETE时,DELETE类操作受行访问控制的影响,只能删除满足条件(using\_expression返回值为TRUE)的元组数据,受影响的操作包括DELETE, DELETE ... RETURNING。 行访问控制策略与适配的SQL语法关系参加下表: **表 1** ROW LEVEL SECURITY策略与适配SQL语法关系 * **role\_name** 行访问控制影响的数据库用户。 当未指定时,PUBLIC为默认值,PUBLIC表示影响所有数据库用户,可以指定多个受影响的数据库用户。 > \[!TIP]须知 > 系统管理员不受行访问控制特性影响。 * **using\_expression** 行访问控制的表达式(返回boolean值)。 条件表达式中不能包含AGG函数和窗口(WINDOW)函数。在查询重写阶段,如果数据表的行访问控制开关打开,满足条件的表达式会添加到计划树中。针对数据表的每条元组,会进行表达式计算,只有表达式返回值为TRUE时,行数据对用户才可见(SELECT、UPDATE、DELETE);当表达式返回FALSE时,该元组对当前用户不可见,用户无法通过SELECT语句查看此元组,无法通过UPDATE语句更新此元组,无法通过DELETE语句删除此元组。 ## 示例 ``` --创建用户alice openGauss=# CREATE USER alice PASSWORD 'xxxxxxxxx'; --创建用户bob openGauss=# CREATE USER bob PASSWORD 'xxxxxxxxx'; --创建数据表all_data openGauss=# CREATE TABLE all_data(id int, role varchar(100), data varchar(100)); --向数据表插入数据 openGauss=# INSERT INTO all_data VALUES(1, 'alice', 'alice data'); openGauss=# INSERT INTO all_data VALUES(2, 'bob', 'bob data'); openGauss=# INSERT INTO all_data VALUES(3, 'peter', 'peter data'); --将表all_data的读取权限赋予alice和bob用户 openGauss=# GRANT SELECT ON all_data TO alice, bob; --打开行访问控制策略开关 openGauss=# ALTER TABLE all_data ENABLE ROW LEVEL SECURITY; --创建行访问控制策略,当前用户只能查看用户自身的数据 openGauss=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING(role = CURRENT_USER); --查看表all_data相关信息 openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_rls" FOR ALL To public USING (((role)::name = "current_user"())) Has OIDs: no Options: orientation=row, compression=no, enable_rowsecurity=true --当前用户执行SELECT操作 openGauss=# SELECT * FROM all_data; id | role | data ----+-------+------------ 1 | alice | alice data 2 | bob | bob data 3 | peter | peter data (3 rows) openGauss=# EXPLAIN(COSTS OFF) SELECT * FROM all_data; QUERY PLAN ---------------------- Seq Scan on all_data (1 row) --切换至alice用户执行SELECT操作 openGauss=# SELECT * FROM all_data; id | role | data ----+-------+------------ 1 | alice | alice data (1 row) openGauss=# EXPLAIN(COSTS OFF) SELECT * FROM all_data; QUERY PLAN ---------------------------------------------------------------- Seq Scan on all_data Filter: ((role)::name = 'alice'::name) Notice: This query is influenced by row level security feature (3 rows) ``` ## 相关链接 [DROP ROW LEVEL SECURITY POLICY](drop_row_level_security_policy.md),[ALTER ROW LEVEL SECURITY POLICY](alter_row_level_security_policy.md) --- --- url: /zh/docs/latest/sql_reference/create_row_level_security_policy.md --- # CREATE ROW LEVEL SECURITY POLICY ## 功能描述 对表创建行访问控制策略。 当对表创建了行访问控制策略,只有打开该表的行访问控制开关(ALTER TABLE ... ENABLE ROW LEVEL SECURITY),策略才能生效。否则不生效。 当前行访问控制影响数据表的读取操作(SELECT、UPDATE、DELETE),暂不影响数据表的写入操作(INSERT、MERGE INTO)。表所有者或系统管理员可以在USING子句中创建表达式,在客户端执行数据表读取操作时,数据库后台在查询重写阶段会将满足条件的表达式拼接并应用到执行计划中。针对数据表的每一条元组,当USING表达式返回TRUE时,元组对当前用户可见,当USING表达式返回FALSE或NULL时,元组对当前用户不可见。 行访问控制策略名称是针对表的,同一个数据表上不能有同名的行访问控制策略;对不同的数据表,可以有同名的行访问控制策略。 行访问控制策略可以应用到指定的操作(SELECT、UPDATE、DELETE、ALL),ALL表示会影响SELECT、UPDATE、DELETE三种操作;定义行访问控制策略时,若未指定受影响的相关操作,默认为ALL。 行访问控制策略可以应用到指定的用户(角色),也可应用到全部用户(PUBLIC);定义行访问控制策略时,若未指定受影响的用户,默认为PUBLIC。 ## 注意事项 * 支持对行存表、行存分区表、列存表、列存分区表、unlogged表、hash表定义行访问控制策略。 * 不支持外表、本地临时表定义行访问控制策略。 * 不支持对视图定义行访问控制策略。 * 同一张表上可以创建多个行访问控制策略,一张表最多创建100个行访问控制策略。 * 系统管理员不受行访问控制影响,可以查看表的全量数据。 * 通过SQL语句、视图、函数、存储过程查询包含行访问控制策略的表,都会受影响。 ## 语法格式 ``` CREATE [ ROW LEVEL SECURITY ] POLICY policy_name ON table_name [ AS { PERMISSIVE | RESTRICTIVE } ] [ FOR { ALL | SELECT | UPDATE | DELETE } ] [ TO { role_name | PUBLIC | CURRENT_USER | SESSION_USER } [, ...] ] USING ( using_expression ) ``` ## 参数说明 * **policy\_name** 行访问控制策略名称,同一个数据表上行访问控制策略名称不能相同。 * **table\_name** 行访问控制策略的表名。 * **PERMISSIVE | RESTRICTIVE** PERMISSIVE指定行访问控制策略为宽容性策略,宽容性策略的条件用OR表达式拼接。 RESTRICTIVE指定行访问控制策略为限制性策略,限制性策略的条件用AND表达式拼接。拼接方式如下: ``` (using_expression_permissive_1 OR using_expression_permissive_2 ...) AND (using_expression_restrictive_1 AND using_expression_restrictive_2 ...) ``` 缺省值为PERMISSIVE。 * **command** 当前行访问控制影响的SQL操作,可指定操作包括:ALL、SELECT、UPDATE、DELETE。当未指定时,ALL为默认值,涵盖SELECT、UPDATE、DELETE操作。 当command为SELECT时,SELECT类操作受行访问控制的影响,只能查看到满足条件(using\_expression返回值为TRUE)的元组数据,受影响的操作包括SELECT、SELECT FOR UPDATE/SHARE、UPDATE ... RETURNING、DELETE ... RETURNING。不允许修改、删除受到访问限制的数据。 当command为UPDATE时,UPDATE类操作受行访问控制的影响,只能更新满足条件(using\_expression返回值为TRUE)的元组数据,受影响的操作包括UPDATE、 UPDATE ... RETURNING、 SELECT ... FOR UPDATE/SHARE。 当command为DELETE时,DELETE类操作受行访问控制的影响,只能删除满足条件(using\_expression返回值为TRUE)的元组数据,受影响的操作包括DELETE、 DELETE ... RETURNING。 行访问控制策略与适配的SQL语法关系参加下表: **表 1** ROW LEVEL SECURITY策略与适配SQL语法关系 * **role\_name** 行访问控制影响的数据库用户。 当未指定时,PUBLIC为默认值,PUBLIC表示影响所有数据库用户,可以指定多个受影响的数据库用户。 > \[!TIP]须知 > 系统管理员不受行访问控制特性影响。 * **using\_expression** 行访问控制的表达式(返回boolean值)。 条件表达式中不能包含AGG函数和窗口(WINDOW)函数。在查询重写阶段,如果数据表的行访问控制开关打开,满足条件的表达式会添加到计划树中。针对数据表的每条元组,会进行表达式计算,只有表达式返回值为TRUE时,行数据对用户才可见(SELECT、UPDATE、DELETE);当表达式返回FALSE时,该元组对当前用户不可见,用户无法通过SELECT语句查看此元组,无法通过UPDATE语句更新此元组,无法通过DELETE语句删除此元组。 ## 示例 ``` --创建用户alice openGauss=# CREATE USER alice PASSWORD 'xxxxxxxxx'; --创建用户bob openGauss=# CREATE USER bob PASSWORD 'xxxxxxxxx'; --创建数据表all_data openGauss=# CREATE TABLE all_data(id int, role varchar(100), data varchar(100)); --向数据表插入数据 openGauss=# INSERT INTO all_data VALUES(1, 'alice', 'alice data'); openGauss=# INSERT INTO all_data VALUES(2, 'bob', 'bob data'); openGauss=# INSERT INTO all_data VALUES(3, 'peter', 'peter data'); --将表all_data的读取权限赋予alice和bob用户 openGauss=# GRANT SELECT ON all_data TO alice, bob; --打开行访问控制策略开关 openGauss=# ALTER TABLE all_data ENABLE ROW LEVEL SECURITY; --创建行访问控制策略,当前用户只能查看用户自身的数据 openGauss=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING(role = CURRENT_USER); --查看表all_data相关信息 openGauss=# \d+ all_data Table "public.all_data" Column | Type | Modifiers | Storage | Stats target | Description --------+------------------------+-----------+----------+--------------+------------- id | integer | | plain | | role | character varying(100) | | extended | | data | character varying(100) | | extended | | Row Level Security Policies: POLICY "all_data_rls" FOR ALL To public USING (((role)::name = "current_user"())) Has OIDs: no Options: orientation=row, compression=no, enable_rowsecurity=true --当前用户执行SELECT操作 openGauss=# SELECT * FROM all_data; id | role | data ----+-------+------------ 1 | alice | alice data 2 | bob | bob data 3 | peter | peter data (3 rows) openGauss=# EXPLAIN(COSTS OFF) SELECT * FROM all_data; QUERY PLAN ---------------------- Seq Scan on all_data (1 row) --切换至alice用户执行SELECT操作 openGauss=# SELECT * FROM all_data; id | role | data ----+-------+------------ 1 | alice | alice data (1 row) openGauss=# EXPLAIN(COSTS OFF) SELECT * FROM all_data; QUERY PLAN ---------------------------------------------------------------- Seq Scan on all_data Filter: ((role)::name = 'alice'::name) Notice: This query is influenced by row level security feature (3 rows) ``` ## 相关链接 [DROP ROW LEVEL SECURITY POLICY](drop_row_level_security_policy.md),[ALTER ROW LEVEL SECURITY POLICY](alter_row_level_security_policy.md) --- --- url: /en/docs/latest-lite/sql_reference/create_rule.md --- # CREATE RULE ## Function **CREATE RULE** defines a new rewriting rule. ## Precautions * To define or modify rules for a table, you must be the owner of the table. * If multiple rules of the same type are defined for the same table, the rules are triggered one by one by name in alphabetical order. * In the view, the **RETURNING** clause can be added to the **INSERT**, **UPDATE**, and **DELETE** rules to return columns by view. If a rule is triggered by the **INSERT RETURNING**, **UPDATE RETURNING**, or **DELETE RETURNING** command, these clauses are used to calculate the output result. If a rule is triggered by a command without **RETURNING**, the **RETURNING** clause of the rule is ignored. Currently, only unconditional **INSTEAD** rules can contain the **RETURNING** clause, and only one **RETURNING** clause can exist in all rules of one event. This ensures that only one **RETURNING** clause can be used for result calculation. If the **RETURNING** clause does not exist in any valid rule, the **RETURNING** query in this view will be rejected. * Currently, **ON SELECT** rules must be unconditional **INSTEAD** rules and must have actions consisting of a single **SELECT** command. Therefore, an **ON SELECT** rule actually turns a table into a view whose visible content is the content returned by the **SELECT** command of the rule, rather than the content in the table (if any). * You are not advised to use column-store tables in rules, especially for write operations. The architecture implementation and transaction processing of column-store tables are greatly different from those of row-store tables. Therefore, the rule performance of column-store tables is different from that of row-store tables. ## Syntax ``` CREATE [ OR REPLACE ] RULE name AS ON event TO table_name [ WHERE condition ] DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) } ``` Events include: ``` SELECT INSERT DELETE UPDATE ``` ## Parameter Description * name Name of the created rule. It must be unique among all the rules for the same table. Value range: a string, which complies with the identifier naming convention and contains a maximum of 63 characters. * event One of the **SELECT**, **INSERT**, **UPDATE**, and **DELETE** events. * table\_name Name (optionally schema-qualified) of the table or view to which the rule applies. * condition SQL condition expression that returns a Boolean value, which determines whether to execute the rule. Expressions cannot reference any table except **NEW** and **OLD**, and cannot have aggregate functions. You are not advised to use numeric types such as int for **condition**, because such types can be implicitly converted to bool values (non-zero values are implicitly converted to **true** and **0** is implicitly converted to **false**), which may cause unexpected results. * INSTEAD **INSTEAD** indicates that the initial event is replaced with this command. * ALSO **ALSO** indicates that the command should be executed after the initial event. If neither **ALSO** nor **INSTEAD** is specified, **ALSO** is the default value. * command Command that composes the rule action. A valid command is one of the **SELECT**, **INSERT**, **UPDATE**, and **DELETE** statements. ## Examples ``` CREATE RULE "_RETURN" AS ON SELECT TO t1 DO INSTEAD SELECT * FROM t2; ``` --- --- url: /en/docs/latest/sql_reference/create_rule.md --- # CREATE RULE ## Function **CREATE RULE** defines a new rewriting rule. ## Precautions * To define or modify rules for a table, you must be the owner of the table. * If multiple rules of the same type are defined for the same table, the rules are triggered one by one by name in alphabetical order. * In the view, the **RETURNING** clause can be added to the **INSERT**, **UPDATE**, and **DELETE** rules to return columns by view. If a rule is triggered by the **INSERT RETURNING**, **UPDATE RETURNING**, or **DELETE RETURNING** command, these clauses are used to calculate the output result. If a rule is triggered by a command without **RETURNING**, the **RETURNING** clause of the rule is ignored. Currently, only unconditional **INSTEAD** rules can contain the **RETURNING** clause, and only one **RETURNING** clause can exist in all rules of one event. This ensures that only one **RETURNING** clause can be used for result calculation. If the **RETURNING** clause does not exist in any valid rule, the **RETURNING** query in this view will be rejected. * Currently, **ON SELECT** rules must be unconditional **INSTEAD** rules and must have actions consisting of a single **SELECT** command. Therefore, an **ON SELECT** rule actually turns a table into a view whose visible content is the content returned by the **SELECT** command of the rule, rather than the content in the table (if any). * You are not advised to use column-store tables in rules, especially for write operations. The architecture implementation and transaction processing of column-store tables are greatly different from those of row-store tables. Therefore, the rule performance of column-store tables is different from that of row-store tables. ## Syntax ``` CREATE [ OR REPLACE ] RULE name AS ON event TO table_name [ WHERE condition ] DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) } ``` Events include: ``` SELECT INSERT DELETE UPDATE ``` ## Parameter Description * name Name of the created rule. It must be unique among all the rules for the same table. Value range: a string, which complies with the identifier naming convention and contains a maximum of 63 characters. * event One of the **SELECT**, **INSERT**, **UPDATE**, and **DELETE** events. * table\_name Name (optionally schema-qualified) of the table or view to which the rule applies. * condition SQL condition expression that returns a Boolean value, which determines whether to execute the rule. Expressions cannot reference any table except **NEW** and **OLD**, and cannot have aggregate functions. You are not advised to use numeric types such as int for **condition**, because such types can be implicitly converted to bool values (non-zero values are implicitly converted to **true** and **0** is implicitly converted to **false**), which may cause unexpected results. * INSTEAD **INSTEAD** indicates that the initial event is replaced with this command. * ALSO **ALSO** indicates that the command should be executed after the initial event. If neither **ALSO** nor **INSTEAD** is specified, **ALSO** is the default value. * command Command that composes the rule action. A valid command is one of the **SELECT**, **INSERT**, **UPDATE**, and **DELETE** statements. ## Examples ``` CREATE RULE "_RETURN" AS ON SELECT TO t1 DO INSTEAD SELECT * FROM t2; ``` --- --- url: /zh/docs/latest-lite/sql_reference/create_rule.md --- # CREATE RULE ## 功能描述 定义一个新的重写规则。 ## 注意事项 * 为了在表上定义或修改规则,你必须是该表的拥有者。 * 如果在同一个表定义了多个相同类型的规则,则按规则的名称字母顺序触发它们。 * 在视图上用于INSERT、UPDATE、DELETE的规则中可以添加RETURNING子句基于视图的字段返回。如果规则被INSERT RETURNING、UPDATE RETURNING、DELETE RETURNING命令触发,这些子句将用来计算输出结果。如果规则被不带RETURNING的命令触发,那么规则的RETURNING子句将被忽略。目前仅允许无条件的INSTEAD规则包含RETURNING子句,而且在同一个事件内的所有规则中最多只能有一个RETURNING子句。这样就确保只有一个RETURNING子句可以用于计算结果。如果在任何有效规则中都不存在RETURNING子句,该视图上的RETURNING查询将被拒绝。 * 目前,ON SELECT规则必须是无条件的INSTEAD规则并且必须有一个由单独一条SELECT查询组成的动作。因此,一条ON SELECT规则实际上把表变成了一个视图,它的可见内容是由该规则的SELECT命令返回,而不是直接存在该表中的内容(如果有)。 * 不建议在rule内使用列存表,尤其是一些写操作。因为列存表与行存表的架构实现、事务处理等存在很大差异,因此rule的表现也会有很多与行存表不同的地方。 ## 语法格式 ``` CREATE [ OR REPLACE ] RULE name AS ON event TO table_name [ WHERE condition ] DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) } ``` 其中event包含以下几种: ``` SELECT INSERT DELETE UPDATE ``` ## 参数说明 * name 创建的规则名。它必须在同一个表上的所有规则名字中唯一。 取值范围:符合标识符命名规范的字符串,且最大长度不超过63个字符。 * event SELECT、INSERT、UPDATE、DELETE事件之一。 * table\_name 规则作用的表或者视图的名字(可以有模式修饰)。 * condition 返回boolean的SQL条件表达式,决定是否实际执行规则。表达式除了引用NEW和OLD之外不能引用任何表,并且不能有聚合函数。不建议使用int等数值类型作为condition,因为int等数值类型可以隐式转换为bool值(非0值隐式转换为true,0转换为false),可能导致非预期的结果。 * INSTEAD INSTEAD指示使用该命令替换初始事件。 * ALSO ALSO指示该命令应该在初始事件执行之后执行。如果既没有声明ALSO也没有声明INSTEAD, 那么ALSO为缺省值。 * command 组成规则动作的命令。有效的命令是SELECT、 INSERT、UPDATE、 DELETE语句之一。 ## 示例 ``` CREATE RULE "_RETURN" AS ON SELECT TO t1 DO INSTEAD SELECT * FROM t2; ``` > \[!TIP]须知 > > * `ON SELECT`后指定的规则名必须为`"_RETURN"` > * 目前,`ON SELECT`规则必须是`INSTEAD SELECT`,而且`TO`所指定的表会被转为视图,这个前提是该表**为空**且不带有触发器、索引、子表等限制,也即必须为一张**初始的空表**。 > 因此,一般不建议采用这种写法,而是直接创建视图。 --- --- url: /zh/docs/latest/sql_reference/create_rule.md --- # CREATE RULE ## 功能描述 定义一个新的重写规则。 ## 注意事项 * 为了在表上定义或修改规则,你必须是该表的拥有者。 * 如果在同一个表定义了多个相同类型的规则,则按规则的名称字母顺序触发它们。 * 在视图上用于INSERT、UPDATE、DELETE的规则中可以添加RETURNING子句基于视图的字段返回。如果规则被INSERT RETURNING、UPDATE RETURNING、DELETE RETURNING命令触发,这些子句将用来计算输出结果。如果规则被不带RETURNING的命令触发,那么规则的RETURNING子句将被忽略。目前仅允许无条件的INSTEAD规则包含RETURNING子句,而且在同一个事件内的所有规则中最多只能有一个RETURNING子句。这样就确保只有一个RETURNING子句可以用于计算结果。如果在任何有效规则中都不存在RETURNING子句,该视图上的RETURNING查询将被拒绝。 * 不建议在rule内使用列存表,尤其是一些写操作。因为列存表与行存表的架构实现、事务处理等存在很大差异,因此rule的表现也会有很多与行存表不同的地方。 ## 语法格式 ``` CREATE [ OR REPLACE ] RULE name AS ON event TO table_name [ WHERE condition ] DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) } ``` 其中event包含以下几种: ``` SELECT INSERT DELETE UPDATE ``` ## 参数说明 * name 创建的规则名。它必须在同一个表上的所有规则名字中唯一。 取值范围:符合标识符命名规范的字符串,且最大长度不超过63个字符。 * table\_name 规则作用的表或者视图的名字(可以有模式修饰)。 * condition 返回boolean的SQL条件表达式,决定是否实际执行规则。表达式除了引用NEW和OLD之外不能引用任何表, 并且不能有聚合函数。 * INSTEAD INSTEAD指示使用该命令替换初始事件。 * ALSO ALSO指示该命令应该在初始事件执行之后执行。如果既没有声明ALSO也没有声明INSTEAD, 那么ALSO为缺省值。 * command 组成规则动作的命令。有效的命令是SELECT、 INSERT、UPDATE、 DELETE语句之一。 ## 示例 ``` CREATE RULE "_RETURN" AS ON SELECT TO t1 DO INSTEAD SELECT * FROM t2; ``` > \[!TIP]须知 > > * `ON SELECT`后指定的规则名必须为`"_RETURN"` > * 目前,`ON SELECT`规则必须是`INSTEAD SELECT`,而且`TO`所指定的表会被转为视图,这个前提是该表**为空**且不带有触发器、索引、子表等限制,也即必须为一张**初始的空表**。 > 因此,一般不建议采用这种写法,而是直接创建视图。 --- --- url: /en/docs/latest-lite/sql_reference/create_schema.md --- # CREATE SCHEMA ## Function **CREATE SCHEMA** creates a schema. Named objects are accessed either by "qualifying" their names with the schema name as a prefix, or by setting a search path that includes the desired schema. When creating named objects, you can also use the schema name as a prefix. Optionally, **CREATE SCHEMA** can include sub-commands to create objects within the new schema. The sub-commands are treated essentially the same as separate commands issued after creating the schema. If the **AUTHORIZATION** clause is used, all the created objects are owned by this user. ## Precautions * Only a user with the **CREATE** permission on the current database can perform this operation. * The owner of an object created by a system administrator in a schema with the same name as a common user is the common user, not the system administrator. ## Syntax * Create a schema based on a specified name. ``` CREATE SCHEMA [IF NOT EXISTS] schema_name [ AUTHORIZATION user_name ] [WITH BLOCKCHAIN] [ schema_element [ ... ] ]; ``` * Create a schema based on a username. ``` CREATE SCHEMA AUTHORIZATION user_name [ schema_element [ ... ] ]; ``` ## Parameter Description * **schema\_name** Specifies the schema name. > \[!TIP]NOTICE > The name must be unique. > The schema name cannot start with **pg\_**. Value range: a string. It must comply with the naming convention rule. * **AUTHORIZATION user\_name** Specifies the owner of a schema. If **schema\_name** is not specified, **user\_name** will be used as the schema name. In this case, **user\_name** can only be a role name. Value range: an existing username or role name * **WITH BLOCKCHAIN** Specifies the tamper-proof attribute of a schema. In this mode, a row-store common user table is automatically extended to tamper-proof user table. * **schema\_element** Specifies an SQL statement defining an object to be created within the schema. Currently, only the **CREATE TABLE**, **CREATE VIEW**, **CREATE INDEX**, **CREATE PARTITION**, **CREATE SEQUENCE**, **CREATE TRIGGER** and **GRANT** clauses are supported. Objects created by sub-commands are owned by the user specified by **AUTHORIZATION**. > \[!NOTE]NOTE > If objects in the schema on the current search path are with the same name, specify the schemas for different objects. You can run **SHOW SEARCH\_PATH** to check the schemas on the current search path. ## Examples ``` -- Create the role1 role. openGauss=# CREATE ROLE role1 IDENTIFIED BY 'xxxxxxxxx'; -- Create a schema named role1 for the role1 role. The owner of the films and winners tables created by the clause is role1. openGauss=# CREATE SCHEMA AUTHORIZATION role1 CREATE TABLE films (title text, release date, awards text[]) CREATE VIEW winners AS SELECT title, release FROM films WHERE awards IS NOT NULL; -- Delete the schema. openGauss=# DROP SCHEMA role1 CASCADE; -- Delete the user. openGauss=# DROP USER role1 CASCADE; ``` ## Helpful Links [ALTER SCHEMA](alter_schema.md) and [DROP SCHEMA](drop_schema.md) --- --- url: /en/docs/latest/sql_reference/create_schema.md --- # CREATE SCHEMA ## Function **CREATE SCHEMA** creates a schema. Named objects are accessed either by "qualifying" their names with the schema name as a prefix, or by setting a search path that includes the desired schema. When creating named objects, you can also use the schema name as a prefix. Optionally, **CREATE SCHEMA** can include sub-commands to create objects within the new schema. The sub-commands are treated essentially the same as separate commands issued after creating the schema. If the **AUTHORIZATION** clause is used, all the created objects are owned by this user. ## Precautions * Only a user with the **CREATE** permission on the current database can perform this operation. * The owner of an object created by a system administrator in a schema with the same name as a common user is the common user, not the system administrator. ## Syntax * Create a schema based on a specified name. ``` CREATE SCHEMA schema_name [ AUTHORIZATION user_name ] [WITH BLOCKCHAIN] [ schema_element [ ... ] ]; ``` * Create a schema based on a username. ``` CREATE SCHEMA AUTHORIZATION user_name [ schema_element [ ... ] ]; ``` ## Parameter Description * **schema\_name** Specifies the schema name. > \[!TIP]NOTICE > The name must be unique. > The schema name cannot start with **pg\_**. Value range: a string. It must comply with the naming convention rule. * **AUTHORIZATION user\_name** Specifies the owner of a schema. If **schema\_name** is not specified, **user\_name** will be used as the schema name. In this case, **user\_name** can only be a role name. Value range: an existing username or role name * **WITH BLOCKCHAIN** Specifies the tamper-proof attribute of a schema. In this mode, a row-store common user table is automatically extended to tamper-proof user table. * **schema\_element** Specifies an SQL statement defining an object to be created within the schema. Currently, only the **CREATE TABLE**, **CREATE VIEW**, **CREATE INDEX**, **CREATE PARTITION**, **CREATE SEQUENCE**, **CREATE TRIGGER** and **GRANT** clauses are supported. Objects created by sub-commands are owned by the user specified by **AUTHORIZATION**. > \[!NOTE]NOTE > If objects in the schema on the current search path are with the same name, specify the schemas for different objects. You can run **SHOW SEARCH\_PATH** to check the schemas on the current search path. ## Examples ``` -- Create the role1 role. openGauss=# CREATE ROLE role1 IDENTIFIED BY 'xxxxxxxxx'; -- Create a schema named role1 for the role1 role. The owner of the films and winners tables created by the clause is role1. openGauss=# CREATE SCHEMA AUTHORIZATION role1 CREATE TABLE films (title text, release date, awards text[]) CREATE VIEW winners AS SELECT title, release FROM films WHERE awards IS NOT NULL; -- Delete the schema. openGauss=# DROP SCHEMA role1 CASCADE; -- Delete the user. openGauss=# DROP USER role1 CASCADE; ``` ## Helpful Links [ALTER SCHEMA](alter_schema.md) and [DROP SCHEMA](drop_schema.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_schema.md --- # CREATE SCHEMA ## 功能描述 创建模式。 访问命名对象时可以使用模式名作为前缀进行访问,如果无模式名前缀,则访问当前模式下的命名对象。创建命名对象时也可用模式名作为前缀修饰。 另外,CREATE SCHEMA可以包括在新模式中创建对象的子命令,这些子命令和那些在创建完模式后发出的命令没有任何区别。如果使用了AUTHORIZATION子句,则所有创建的对象都将被该用户所拥有。 ## 注意事项 * 只要用户对当前数据库有CREATE权限,就可以创建模式。 * 系统管理员在普通用户同名schema下创建的对象,所有者为schema的同名用户(非系统管理员)。 ## 语法格式 * 根据指定的名称创建模式。 ``` CREATE SCHEMA schema_name [ AUTHORIZATION user_name ] [WITH BLOCKCHAIN] [ schema_element [ ... ] ]; ``` * 根据用户名创建模式。 ``` CREATE SCHEMA AUTHORIZATION user_name [ schema_element [ ... ] ]; ``` - 创建模式并指定默认字符集和字符序。 ``` CREATE SCHEMA schema_name [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ]; ``` ## 参数说明 * **schema\_name** 模式名称。 > \[!TIP]须知 > > 模式名不能和当前数据库里其他的模式重名。 > 模式的名称不可以“pg\_”开头。设置support\_extended\_features参数为on后,可以“pg\_temp\_”或“pg\_toast\_temp\_”开头,但是不建议用户这样使用,可能导致临时表无法被正常清理。 取值范围:字符串,要符合标识符的命名规范。 * **AUTHORIZATION user\_name** 指定模式的所有者。当不指定schema\_name时,把user\_name当作模式名,此时user\_name只能是角色名。 取值范围:已存在的用户名/角色名。 * **WITH BLOCKCHAIN** 指定模式的防篡改属性,防篡改模式下的行存普通用户表将自动扩展为防篡改用户表。 * **schema\_element** 在模式里创建对象的SQL语句。目前仅支持CREATE TABLE、CREATE VIEW、CREATE INDEX、CREATE PARTITION、CREATE SEQUENCE、CREATE TRIGGER、GRANT子句。 子命令所创建的对象都被AUTHORIZATION子句指定的用户所拥有。 * **default\_charset** 仅在sql\_compatibility='B'时支持该语法。指定模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **default\_collation** 仅在sql\_compatibility='B'时支持该语法。指定模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 支持字符序参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](create_table_1.md#table8163190152)。 > \[!NOTE]说明 > > 如果当前搜索路径上的模式中存在同名对象时,需要明确指定引用对象所在的模式。可以通过命令SHOW SEARCH\_PATH来查看当前搜索路径上的模式。 ## 示例 ``` --创建一个角色role1。 openGauss=# CREATE ROLE role1 IDENTIFIED BY 'xxxxxxxxx'; -- 为用户role1创建一个同名schema,子命令创建的表films和winners的拥有者为role1。 openGauss=# CREATE SCHEMA AUTHORIZATION role1 CREATE TABLE films (title text, release date, awards text[]) CREATE VIEW winners AS SELECT title, release FROM films WHERE awards IS NOT NULL; -- 创建一个schema ds,指定schema的默认字符集为utf8mb4,默认字符序为utf8mb4_bin。 openGauss=# CREATE SCHEMA ds CHARACTER SET utf8mb4 COLLATE utf8mb4_bin; --删除schema。 openGauss=# DROP SCHEMA role1 CASCADE; --删除用户。 openGauss=# DROP USER role1 CASCADE; ``` ## 相关链接 [ALTER SCHEMA](alter_schema.md),[DROP SCHEMA](drop_schema.md) --- --- url: /zh/docs/latest/sql_reference/create_schema.md --- # CREATE SCHEMA ## 功能描述 创建模式。 访问命名对象时可以使用模式名作为前缀进行访问,如果无模式名前缀,则访问当前模式下的命名对象。创建命名对象时也可用模式名作为前缀修饰。 另外,CREATE SCHEMA可以包括在新模式中创建对象的子命令,这些子命令和那些在创建完模式后发出的命令没有任何区别。如果使用了AUTHORIZATION子句,则所有创建的对象都将被该用户所拥有。 ## 注意事项 * 只要用户对当前数据库有CREATE权限,就可以创建模式。 * 系统管理员在普通用户同名schema下创建的对象,所有者为schema的同名用户(非系统管理员)。 ## 语法格式 * 根据指定的名称创建模式。 ``` CREATE SCHEMA schema_name [ AUTHORIZATION user_name ] [WITH BLOCKCHAIN] [ schema_element [ ... ] ]; ``` * 根据用户名创建模式。 ``` CREATE SCHEMA AUTHORIZATION user_name [ schema_element [ ... ] ]; ``` - 创建模式并指定默认字符集和字符序。 ``` CREATE SCHEMA schema_name [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ]; ``` ## 参数说明 * **schema\_name** 模式名称。 > \[!TIP]须知 > > 模式名不能和当前数据库里其他的模式重名。 > 模式的名称不可以“pg\_”开头,设置support\_extended\_features参数为on后,可以“pg\_temp\_”或“pg\_toast\_temp\_”开头,但是不建议用户这样使用,可能导致临时表无法被正常清理。 取值范围:字符串,要符合标识符的命名规范。 * **AUTHORIZATION user\_name** 指定模式的所有者。当不指定schema\_name时,把user\_name当作模式名,此时user\_name只能是角色名。 取值范围:已存在的用户名/角色名。 * **WITH BLOCKCHAIN** 指定模式的防篡改属性,防篡改模式下的行存普通用户表将自动扩展为防篡改用户表。 * **schema\_element** 在模式里创建对象的SQL语句。目前仅支持CREATE TABLE、CREATE VIEW、CREATE INDEX、CREATE PARTITION、CREATE SEQUENCE、CREATE TRIGGER、GRANT子句。 子命令所创建的对象都被AUTHORIZATION子句指定的用户所拥有。 * **default\_charset** 仅在sql\_compatibility='B'时支持该语法。指定模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **default\_collation** 仅在sql\_compatibility='B'时支持该语法。指定模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 支持字符序参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](create_table.md#table8163190152)。 > \[!NOTE]说明 > > 如果当前搜索路径上的模式中存在同名对象时,需要明确指定引用对象所在的模式。可以通过命令SHOW SEARCH\_PATH来查看当前搜索路径上的模式。 ## 示例 ``` --创建一个角色role1。 openGauss=# CREATE ROLE role1 IDENTIFIED BY 'xxxxxxxxx'; -- 为用户role1创建一个同名schema,子命令创建的表films和winners的拥有者为role1。 openGauss=# CREATE SCHEMA AUTHORIZATION role1 CREATE TABLE films (title text, release date, awards text[]) CREATE VIEW winners AS SELECT title, release FROM films WHERE awards IS NOT NULL; -- 创建一个schema ds,指定schema的默认字符集为utf8mb4,默认字符序为utf8mb4_bin。 openGauss=# CREATE SCHEMA ds CHARACTER SET utf8mb4 COLLATE utf8mb4_bin; --删除schema。 openGauss=# DROP SCHEMA role1 CASCADE; --删除用户。 openGauss=# DROP USER role1 CASCADE; ``` ## 相关链接 [ALTER SCHEMA](alter_schema.md),[DROP SCHEMA](drop_schema.md) --- --- url: /en/docs/latest-lite/sql_reference/create_sequence.md --- # CREATE SEQUENCE ## Function **CREATE SEQUENCE** adds a sequence to the current database. The owner of a sequence is the user who creates the sequence. ## Precautions * A sequence is a special table that stores arithmetic progressions. It has no actual meaning and is usually used to generate unique identifiers for rows or tables. * If a schema name is given, the sequence is created in the specified schema; otherwise, it is created in the current schema. The sequence name must be different from the names of other sequences, tables, indexes, views in the same schema. * After the sequence is created, functions **nextval()** and **generate\_series(1,N)** insert data to the table. Make sure that the number of times for invoking **nextval** is greater than or equal to N+1. Otherwise, errors will be reported because the number of times for invoking function **generate\_series()** is N+1. * By default, the maximum value of **Sequence** is 2^63 – 1. If a large identifier is used, the maximum value can be 2^127 – 1. * A user granted with the **CREATE ANY SEQUENCE** permission can create sequences in the public and user schemas. ## Syntax ``` CREATE [ LARGE ] SEQUENCE [ IF NOT EXISTS ] name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE ] [ OWNED BY { table_name.column_name | NONE } ]; ``` ## Parameter Description * **IF NOT EXISTS** If a sequence with the same name already exists, no error will be reported, but a notification will be issued to inform that the sequence already exists. * **name** Specifies the name of a sequence to be created. Value range: a sting containing only lowercase letters, uppercase letters, special characters #\_$, and digits. * **increment** Specifies the step for a sequence. A positive number generates an ascending sequence, and a negative number generates a decreasing sequence. The default value is **1**. * **MINVALUE minvalue | NO MINVALUE| NOMINVALUE** Specifies the minimum value of the sequence. If **MINVALUE** is not declared, or **NO MINVALUE** is declared, the default value of the ascending sequence is **1**, and that of the descending sequence is **-263-1**. **NOMINVALUE** is equivalent to **NO MINVALUE**. * **MAXVALUE maxvalue | NO MAXVALUE| NOMAXVALUE** Specifies the maximum value of the sequence. If **MAXVALUE** is not declared, or **NO MAXVALUE** is declared, the default value of the ascending sequence is **263-1**, and that of the descending sequence is **-1**. **NOMAXVALUE** is equivalent to **NO MAXVALUE**. * **start** Specifies the start value of the sequence. The default value for an ascending sequence is **minvalue** and that for a descending sequence is **maxvalue**. * **cache** Specifies the number of sequences stored in the memory for quick access purposes. Default value **1** indicates that one sequence can be generated each time. > \[!NOTE]NOTE > It is not recommended that you define **cache** and **maxvalue** or **minvalue** at the same time. The continuity of sequences cannot be ensured after **cache** is defined because unacknowledged sequences may be generated, causing waste of sequences. * **CYCLE** Recycles sequences after the number of sequences reaches **maxvalue** or **minvalue**. If **NO CYCLE** is specified, any invocation of **nextval** would return an error after the number of sequences reaches **maxvalue** or **minvalue**. **NOCYCLE** is equivalent to **NO CYCLE**. The default value is **NO CYCLE**. If **CYCLE** is specified, the sequence uniqueness cannot be ensured. * **OWNED BY** Associates a sequence with a specified column included in a table. In this way, the sequence will be deleted when you delete its associated column or the table where the column belongs to. The associated table and sequence must be owned by the same user and in the same schema. **OWNED BY** only establishes the association between a table column and the sequence. Sequences on the column do not increase automatically when data is inserted. The default value **OWNED BY NONE** indicates that such association does not exist. > \[!TIP]NOTICE > You are not advised to use the sequence created using **OWNED BY** in other tables. If multiple tables need to share a sequence, the sequence must not belong to a specific table. ## Examples Create an ascending sequence named **serial**, which starts from 101. ``` openGauss=# CREATE SEQUENCE serial START 101 CACHE 20; ``` Select the next number from the sequence. ``` openGauss=# SELECT nextval('serial'); nextval --------- 101 ``` Select the next number from the sequence. ``` openGauss=# SELECT nextval('serial'); nextval --------- 102 ``` Create a sequence associated with the table. ``` openGauss=# CREATE TABLE customer_address ( ca_address_sk integer not null, ca_address_id char(16) not null, ca_street_number char(10) , ca_street_name varchar(60) , ca_street_type char(15) , ca_suite_number char(10) , ca_city varchar(60) , ca_county varchar(30) , ca_state char(2) , ca_zip char(10) , ca_country varchar(20) , ca_gmt_offset decimal(5,2) , ca_location_type char(20) ); openGauss=# CREATE SEQUENCE serial1 START 101 CACHE 20 OWNED BY customer_address.ca_address_sk; -- Delete a table and sequences. openGauss=# DROP TABLE customer_address; openGauss=# DROP SEQUENCE serial cascade; openGauss=# DROP SEQUENCE serial1 cascade; ``` ## Helpful Links [DROP SEQUENCE](drop_sequence.md) and [ALTER SEQUENCE](alter_sequence.md) --- --- url: /en/docs/latest/sql_reference/create_sequence.md --- # CREATE SEQUENCE ## Function **CREATE SEQUENCE** adds a sequence to the current database. The owner of a sequence is the user who creates the sequence. ## Precautions * A sequence is a special table that stores arithmetic progressions. It has no actual meaning and is usually used to generate unique identifiers for rows or tables. * If a schema name is given, the sequence is created in the specified schema; otherwise, it is created in the current schema. The sequence name must be different from the names of other sequences, tables, indexes, views in the same schema. * After the sequence is created, functions **nextval()** and **generate\_series(1,N)** insert data to the table. Make sure that the number of times for invoking **nextval** is greater than or equal to N+1. Otherwise, errors will be reported because the number of times for invoking function **generate\_series()** is N+1. * By default, the maximum value of **Sequence** is 2^63 – 1. If a large identifier is used, the maximum value can be 2^127 – 1. * A user granted with the **CREATE ANY SEQUENCE** permission can create sequences in the public and user schemas. ## Syntax ``` CREATE [ LARGE ] SEQUENCE [ IF NOT EXISTS ] name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE ] [ GLOBAL | SESSION ] [ OWNED BY { table_name.column_name | NONE } ]; ``` ## Parameter Description * **IF NOT EXISTS** If a sequence with the same name already exists, no error will be reported, but a notification will be issued to inform that the sequence already exists. * **name** Specifies the name of a sequence to be created. Value range: a sting containing only lowercase letters, uppercase letters, special characters #\_$, and digits. * **increment** Specifies the step for a sequence. A positive number generates an ascending sequence, and a negative number generates a decreasing sequence. The default value is **1**. * **MINVALUE minvalue | NO MINVALUE| NOMINVALUE** Specifies the minimum value of the sequence. If **MINVALUE** is not declared, or **NO MINVALUE** is declared, the default value of the ascending sequence is **1**, and that of the descending sequence is **-263+1**. **NOMINVALUE** is equivalent to **NO MINVALUE**. * **MAXVALUE maxvalue | NO MAXVALUE| NOMAXVALUE** Specifies the maximum value of the sequence. If **MAXVALUE** is not declared, or **NO MAXVALUE** is declared, the default value of the ascending sequence is **263-1**, and that of the descending sequence is **-1**. **NOMAXVALUE** is equivalent to **NO MAXVALUE**. * **start** Specifies the start value of the sequence. The default value for an ascending sequence is **minvalue** and that for a descending sequence is **maxvalue**. * **cache** Specifies the number of sequences stored in the memory for quick access purposes. Default value **1** indicates that one sequence can be generated each time. > \[!NOTE]NOTE > It is not recommended that you define **cache** and **maxvalue** or **minvalue** at the same time. The continuity of sequences cannot be ensured after **cache** is defined because unacknowledged sequences may be generated, causing waste of sequences. * **CYCLE** Recycles sequences after the number of sequences reaches **maxvalue** or **minvalue**. If **NO CYCLE** is specified, any invocation of **nextval** would return an error after the number of sequences reaches **maxvalue** or **minvalue**. **NOCYCLE** is equivalent to **NO CYCLE**. The default value is **NO CYCLE**. If **CYCLE** is specified, the sequence uniqueness cannot be ensured. * **GLOBAL** GLOBAL specifies that the **sequence** cache is a global cache, and the cache is shared by all sessions. * **SESSION** SESSION specifies that the sequence cache is a session-level cache, the cache is private to each session, and the default is session-level. * **OWNED BY** Associates a sequence with a specified column included in a table. In this way, the sequence will be deleted when you delete its associated column or the table where the column belongs to. The associated table and sequence must be owned by the same user and in the same schema. **OWNED BY** only establishes the association between a table column and the sequence. Sequences on the column do not increase automatically when data is inserted. The default value **OWNED BY NONE** indicates that such association does not exist. > \[!TIP]NOTICE > You are not advised to use the sequence created using **OWNED BY** in other tables. If multiple tables need to share a sequence, the sequence must not belong to a specific table. ## Examples Create an ascending sequence named **serial**, which starts from 101. ``` openGauss=# CREATE SEQUENCE serial START 101 CACHE 20; ``` Select the next number from the sequence. ``` openGauss=# SELECT nextval('serial'); nextval --------- 101 ``` Select the next number from the sequence. ``` openGauss=# SELECT nextval('serial'); nextval --------- 102 ``` Create a sequence associated with the table. ``` openGauss=# CREATE TABLE customer_address ( ca_address_sk integer not null, ca_address_id char(16) not null, ca_street_number char(10) , ca_street_name varchar(60) , ca_street_type char(15) , ca_suite_number char(10) , ca_city varchar(60) , ca_county varchar(30) , ca_state char(2) , ca_zip char(10) , ca_country varchar(20) , ca_gmt_offset decimal(5,2) , ca_location_type char(20) ); openGauss=# CREATE SEQUENCE serial1 START 101 CACHE 20 OWNED BY customer_address.ca_address_sk; -- Delete a table and sequences. openGauss=# DROP TABLE customer_address; openGauss=# DROP SEQUENCE serial cascade; openGauss=# DROP SEQUENCE serial1 cascade; -- Create a sequence with a global cache. openGauss=# CREATE SEQUENCE seq1 START 1 CACHE 100 GLOBAL; -- Create a sequence specifying a session-level cache. openGauss=# CREATE SEQUENCE seq2 START 1 CACHE 100 SESSION; -- Or sequence with a SESSION-level cache created by default. openGauss=# CREATE SEQUENCE seq3 START 1 CACHE 100; ``` ## Helpful Links [DROP SEQUENCE](drop_sequence.md) and [ALTER SEQUENCE](alter_sequence.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_sequence.md --- # CREATE SEQUENCE ## 功能描述 CREATE SEQUENCE用于向当前数据库里增加一个新的序列。序列的Owner为创建此序列的用户。 ## 注意事项 * Sequence是一个存放等差数列的特殊表。这个表没有实际意义,通常用于为行或者表生成唯一的标识符。 * 如果给出一个模式名,则该序列就在给定的模式中创建,否则会在当前模式中创建。序列名必须和同一个模式中的其他序列、表、索引、视图或外表的名称不同。 * 创建序列后,在表中使用序列的nextval()函数和generate\_series(1,N)函数对表插入数据,请保证nextval的可调用次数大于等于N+1次,否则会因为generate\_series()函数会调用N+1次而导致报错。 * Sequence默认最大值为2^63-1,如果使用了Large标识则最大值可以支持到2^127-1。 * 被授予CREATE ANY SEQUENCE权限的用户,可以在public模式和用户模式下创建序列。 ## 语法格式 ``` CREATE [ LARGE ] SEQUENCE [ IF NOT EXISTS ] name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE ] [ OWNED BY { table_name.column_name | NONE } ]; ``` ## 参数说明 * **IF NOT EXISTS** 如果已经存在相同名称的序列,不会报出错误,而会发出通知,通知此序列已存在。 * **name** 将要创建的序列名称。 取值范围: 仅可以使用小写字母(a~z)、 大写字母(A~Z),数字和特殊字符"#","\_","$"的组合。 * **increment** 指定序列的步长。一个正数将生成一个递增的序列,一个负数将生成一个递减的序列。 缺省值为1。 * **MINVALUE minvalue | NO MINVALUE| NOMINVALUE** 执行序列的最小值。如果没有声明minvalue或者声明了NO MINVALUE,则递增序列的缺省值为1,递减序列的缺省值为-263-1。NOMINVALUE等价于NO MINVALUE * **MAXVALUE maxvalue | NO MAXVALUE| NOMAXVALUE** 执行序列的最大值。如果没有声明maxvalue或者声明了NO MAXVALUE,则递增序列的缺省值为263-1,递减序列的缺省值为-1。NOMAXVALUE等价于NO MAXVALUE * **start** 指定序列的起始值。缺省值:对于递增序列为minvalue,递减序列为maxvalue。 * **cache** 为了快速访问,而在内存中预先存储序列号的个数。 缺省值为1,表示一次只能生成一个值,也就是没有缓存。 > \[!NOTE]说明 > > 不建议同时定义cache和maxvalue或minvalue。因为定义cache后不能保证序列的连续性,可能会产生空洞,造成序列号段浪费。 * **CYCLE** 用于使序列达到maxvalue或者minvalue后可循环并继续下去。 如果声明了NO CYCLE,则在序列达到其最大值后任何对nextval的调用都会返回一个错误。 NOCYCLE的作用等价于NO CYCLE。 缺省值为NO CYCLE。 若定义序列为CYCLE,则不能保证序列的唯一性。 * **OWNED BY** 将序列和一个表的指定字段进行关联。这样,在删除那个字段或其所在表的时候会自动删除已关联的序列。关联的表和序列的所有者必须是同一个用户,并且在同一个模式中。需要注意的是,通过指定OWNED BY,仅仅是建立了表的对应列和sequence之间关联关系,并不会在插入数据时在该列上产生自增序列。 缺省值为OWNED BY NONE,表示不存在这样的关联。 > \[!TIP]须知 > > 通过OWNED BY创建的Sequence不建议用于其他表,如果希望多个表共享Sequence,该Sequence不应该从属于特定表。 ## 示例 创建一个名为serial的递增序列,从101开始: ``` openGauss=# CREATE SEQUENCE serial START 101 CACHE 20; ``` 从序列中选出下一个数字: ``` openGauss=# SELECT nextval('serial'); nextval --------- 101 ``` 从序列中选出下一个数字: ``` openGauss=# SELECT nextval('serial'); nextval --------- 102 ``` 创建与表关联的序列: ``` openGauss=# CREATE TABLE customer_address ( ca_address_sk integer not null, ca_address_id char(16) not null, ca_street_number char(10) , ca_street_name varchar(60) , ca_street_type char(15) , ca_suite_number char(10) , ca_city varchar(60) , ca_county varchar(30) , ca_state char(2) , ca_zip char(10) , ca_country varchar(20) , ca_gmt_offset decimal(5,2) , ca_location_type char(20) ); openGauss=# CREATE SEQUENCE serial1 START 101 CACHE 20 OWNED BY customer_address.ca_address_sk; --删除表和序列 openGauss=# DROP TABLE customer_address; openGauss=# DROP SEQUENCE serial cascade; openGauss=# DROP SEQUENCE serial1 cascade; ``` ## 相关链接 [DROP SEQUENCE](drop_sequence.md),[ALTER SEQUENCE](alter_sequence.md) --- --- url: /zh/docs/latest/ograc/sql_reference/create_sequence.md --- # CREATE SEQUENCE ## 功能描述 序列(Sequence)是数据库中一种特殊对象,用于生成唯一、递增或递减的数值序列。 CREATE SEQUENCE用于向当前数据库中增加一个新的序列生成器。序列的Owner为创建此序列的用户。 ## 注意事项 * 序列创建后,可通过 NEXTVAL 和 CURRVAL 获取序列值。 * 同一模式内序列名称必须唯一。 * 使用 CACHE 选项可在内存中预分配序列号,提升性能,但异常退出时可能导致部分序列号丢失。 ## 语法格式 ```sql CREATE SEQUENCE [schema.]sequence_name [INCREMENT BY INCREMENT_VALUE] | [ START WITH START_VALUE ] | [{MINVALUE MIN_VALUE} | {NOMINVALUE}] [{MAXVALUE MAX_VALUE} | {NOMAXVALUE}] [{CYCLE} | {NOCYCLE}] [{CACHE CACHE_SIZE} | {NOCACHE}] [{ORDER} | {NOORDER}]; ``` ## 参数说明 * **\[schema.]sequence\_name**: 将要创建的序列名称。如果指定了模式名,则序列将在该模式中创建,否则将在当前模式中创建。 * **INCREMENT BY INCREMENT\_VALUE**: 指定序列的步长。一个正数将生成一个递增的序列,一个负数将生成一个递减的序列。缺省值默认为1。 * **START WITH START\_VALUE**: 指定序列的起始值。缺省值:对于递增序列为MIN\_VALUE,递减序列为MAX\_VALUE。 * **\[{MINVALUE MIN\_VALUE} | {NOMINVALUE}]**: 指定序列的最小值。 * 如果没有声明MINVALUE或者声明了NOMINVALUE,则递增序列的缺省值为1,递减序列的缺省值为-2^63+1。 * **\[{MAXVALUE MAX\_VALUE} | {NOMAXVALUE}]**: 指定序列的最大值。 * 如果没有声明MAXVALUE或者声明了NOMAXVALUE,则递增序列的缺省值为2^63-1,递减序列的缺省值为-1。 * **\[{CYCLE} | {NOCYCLE}]**: 用于使序列达到MAX\_VALUE或者MIN\_VALUE后可循环并继续下去。 * 如果声明了NOCYCLE,则在序列达到其最大值后任何对NEXTVAL的调用都会返回一个错误。 * 若定义序列为CYCLE,则不能保证序列的唯一性。 * 缺省值为NOCYCLE。 * **\[{CACHE CACHE\_SIZE} | {NOCACHE}]**: 为了快速访问,而在内存中预先存储序列号的个数。 * 如果声明了CACHE,则在内存中缓存CACHE\_SIZE个序列号,每次调用nextval()函数时,会从缓存中返回一个序列号。如果缓存为空,则会从数据库中读取序列号。 * 如果声明了CACHE,CACHE\_SIZE的默认值为20,最小为2。 * 如果声明了NOCACHE,则每次调用nextval()函数时,都会从数据库中读取序列号。 * **\[{ORDER} | {NOORDER}]**: 用于指定序列是否按顺序生成。 * 如果声明了ORDER,则保证序列号按照请求顺序生成。 * 如果声明了NOORDER,则序列不按顺序生成。 * 缺省值为NOORDER。 ## 示例 ``` -- 最基础的序列创建示例 -- 序列名称 MY_SEQUENCE MIN_VALUE 1 MAX_VALUE 2^63-1 INCREMENT_BY 1 CYCLE_FLAG 0 ORDER_FLAG 0 CACHE_SIZE 20 SQL> CREATE SEQUENCE my_sequence; Succeed. SQL> SELECT * FROM ADM_SEQUENCES where SEQUENCE_NAME = 'MY_SEQUENCE'; SEQUENCE_OWNER SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY CYCLE_FLAG ORDER_FLAG CACHE_SIZE LAST_NUMBER ---------------------------------------------------------------- ---------------------------------------------------------------- -------------------- -------------------- -------------------- ------------ ------------ -------------------- -------------------- SYS MY_SEQUENCE 1 9223372036854775807 1 0 0 20 1 1 rows fetched. -- 递增序列创建 序列名称 MY_SEQUENCE -- 最小值 10 最大值 1000 -- 递增步长 5 是否循环 TRUE 是否有序 TRUE -- 缓存数量 50 SQL> CREATE SEQUENCE my_sequence 2 INCREMENT BY 5 3 START WITH 100 4 MINVALUE 10 5 MAXVALUE 1000 6 CYCLE 7 CACHE 50 8 ORDER; Succeed. SQL> SELECT * FROM ADM_SEQUENCES where SEQUENCE_NAME = 'MY_SEQUENCE'; SEQUENCE_OWNER SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY CYCLE_FLAG ORDER_FLAG CACHE_SIZE LAST_NUMBER ---------------------------------------------------------------- ---------------------------------------------------------------- -------------------- -------------------- -------------------- ------------ ------------ -------------------- -------------------- SYS MY_SEQUENCE 10 1000 5 1 1 50 100 1 rows fetched. -- 创建递减序列 序列名称 MY_SEQUENCE -- 最小值 -2^63+1 最大值 10000 -- 递减步长 -10 是否循环 FALSE 是否有序 FALSE -- 缓存数量 50 SQL> CREATE SEQUENCE my_sequence 2 INCREMENT BY -10 3 START WITH 10000 4 NOMINVALUE 5 MAXVALUE 10000 6 NOCYCLE 7 CACHE 50 8 NOORDER; Succeed. SQL> SELECT * FROM ADM_SEQUENCES where SEQUENCE_NAME = 'MY_SEQUENCE'; SEQUENCE_OWNER SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY CYCLE_FLAG ORDER_FLAG CACHE_SIZE LAST_NUMBER ---------------------------------------------------------------- ---------------------------------------------------------------- -------------------- -------------------- -------------------- ------------ ------------ -------------------- -------------------- SYS MY_SEQUENCE -9223372036854775808 10000 -10 0 0 50 10000 1 rows fetched. ``` --- --- url: /zh/docs/latest/sql_reference/create_sequence.md --- # CREATE SEQUENCE ## 功能描述 CREATE SEQUENCE用于向当前数据库里增加一个新的序列。序列的Owner为创建此序列的用户。 ## 注意事项 * Sequence是一个存放等差数列的特殊表。这个表没有实际意义,通常用于为行或者表生成唯一的标识符。 * 如果给出一个模式名,则该序列就在给定的模式中创建,否则会在当前模式中创建。序列名必须和同一个模式中的其他序列、表、索引、视图或外表的名称不同。 * 创建序列后,在表中使用序列的nextval()函数和generate\_series(1,N)函数对表插入数据,请保证nextval的可调用次数大于等于N+1次,否则会因为generate\_series()函数会调用N+1次而导致报错。 * Sequence默认最大值为2^63-1,如果使用了Large标识则最大值可以支持到2^127-1。 * 被授予CREATE ANY SEQUENCE权限的用户,可以在public模式和用户模式下创建序列。 ## 语法格式 ``` CREATE [ LARGE ] SEQUENCE [ IF NOT EXISTS ] name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE | NOMINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE | NOMAXVALUE] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE | NOCYCLE ] [ GLOBAL | SESSION ] [ OWNED BY { table_name.column_name | NONE } ]; ``` ## 参数说明 * **IF NOT EXISTS** 如果已经存在相同名称的序列,不会报出错误,而会发出通知,通知此序列已存在。 * **name** 将要创建的序列名称。 取值范围: 仅可以使用小写字母(a~z)、 大写字母(A~Z)、数字和特殊字符“#”,“\_”,“$”的组合。 * **increment** 指定序列的步长。一个正数将生成一个递增的序列,一个负数将生成一个递减的序列。 缺省值为1。 * **MINVALUE minvalue | NO MINVALUE| NOMINVALUE** 执行序列的最小值。如果没有声明minvalue或者声明了NO MINVALUE,则递增序列的缺省值为1,递减序列的缺省值为-263+1。NOMINVALUE等价于NO MINVALUE * **MAXVALUE maxvalue | NO MAXVALUE| NOMAXVALUE** 执行序列的最大值。如果没有声明maxvalue或者声明了NO MAXVALUE,则递增序列的缺省值为263-1,递减序列的缺省值为-1。NOMAXVALUE等价于NO MAXVALUE * **start** 指定序列的起始值。缺省值:对于递增序列为minvalue,递减序列为maxvalue。 * **cache** 为了快速访问,而在内存中预先存储序列号的个数。 缺省值为1,表示一次只能生成一个值,也就是没有缓存。 > \[!NOTE]说明 > > 不建议同时定义cache和maxvalue或minvalue。因为定义cache后不能保证序列的连续性,可能会产生空洞,造成序列号段浪费。 * **CYCLE** 用于使序列达到maxvalue或者minvalue后可循环并继续下去。 如果声明了NO CYCLE,则在序列达到其最大值后任何对nextval的调用都会返回一个错误。 NOCYCLE的作用等价于NO CYCLE。 缺省值为NO CYCLE。 若定义序列为CYCLE,则不能保证序列的唯一性。 * **GLOBAL** GLOBAL指定序列缓存是全局缓存,是所有session共享的。 * **SESSION** SESSION指定序列缓存是session级别缓存,缓存是各session私有的,默认为session级别。 * **OWNED BY** 将序列和一个表的指定字段进行关联。这样,在删除那个字段或其所在表的时候会自动删除已关联的序列。关联的表和序列的所有者必须是同一个用户,并且在同一个模式中。需要注意的是,通过指定OWNED BY,仅仅是建立了表的对应列和sequence之间关联关系,并不会在插入数据时在该列上产生自增序列。 缺省值为OWNED BY NONE,表示不存在这样的关联。 > \[!TIP]须知 > > 通过OWNED BY创建的Sequence不建议用于其他表,如果希望多个表共享Sequence,该Sequence不应该从属于特定表。 ## 示例 创建一个名为serial的递增序列,从101开始: ``` openGauss=# CREATE SEQUENCE serial START 101 CACHE 20; ``` 从序列中选出下一个数字: ``` openGauss=# SELECT nextval('serial'); nextval --------- 101 ``` 从序列中选出下一个数字: ``` openGauss=# SELECT nextval('serial'); nextval --------- 102 ``` 创建与表关联的序列: ``` openGauss=# CREATE TABLE customer_address ( ca_address_sk integer not null, ca_address_id char(16) not null, ca_street_number char(10) , ca_street_name varchar(60) , ca_street_type char(15) , ca_suite_number char(10) , ca_city varchar(60) , ca_county varchar(30) , ca_state char(2) , ca_zip char(10) , ca_country varchar(20) , ca_gmt_offset decimal(5,2) , ca_location_type char(20) ); openGauss=# CREATE SEQUENCE serial1 START 101 CACHE 20 OWNED BY customer_address.ca_address_sk; --删除表和序列 openGauss=# DROP TABLE customer_address; openGauss=# DROP SEQUENCE serial cascade; openGauss=# DROP SEQUENCE serial1 cascade; --创建带全局缓存的序列 openGauss=# CREATE SEQUENCE seq1 START 1 CACHE 100 GLOBAL; --显式创建session级别缓存的序列 openGauss=# CREATE SEQUENCE seq2 START 1 CACHE 100 SESSION; --默认创建session级别缓存的序列 openGauss=# CREATE SEQUENCE seq3 START 1 CACHE 100; ``` ## 相关链接 [DROP SEQUENCE](drop_sequence.md),[ALTER SEQUENCE](alter_sequence.md) --- --- url: /en/docs/latest-lite/sql_reference/create_server.md --- # CREATE SERVER ## Function Defines a new foreign server. ## Syntax ``` CREATE SERVER server_name [ TYPE ' server_type ' ] [ VERSION ' server_version ' ] FOREIGN DATA WRAPPER fdw_name [ OPTIONS ( { option_name ' value ' } [, ...] ) ] ; ``` ## Parameter Description * **server\_name** Specifies the server name. Value range: a string containing no more than 63 characters * **server\_type** Optional server type, which may be useful for foreign data wrappers. * **server\_version** Optional server version, which may be useful for foreign data wrappers. * **fdw\_name** Specifies the name of the foreign data wrapper. Value range: dist\_fdw, hdfs\_fdw, log\_fdw, file\_fdw, mot\_fdw, oracle\_fdw, mysql\_fdw, postgres\_fdw. * **OPTIONS ( { option\_name ' value ' } \[, ...] )** Specifies options for the server. These options typically define the connection details of the server, but the actual names and values depend on the foreign data wrapper of the server. * Options supported by **oracle\_fdw** are as follows: * **dbserver** Connection string of the remote Oracle database. * **isolation\_level** (default value: **serializable**) Oracle database transaction isolation level. Value range: **serializable**, **read\_committed**, and **read\_only** * The options supported by **mysql\_fdw** are as follows: * **host** (default value: **127.0.0.1**) IP address of the MySQL server or MariaDB. * **port** (default value: **3306**) Listening port number of the MySQL server or MariaDB. * The options supported by **postgres\_fdw**are the same as those supported by libpq. For details, see *Connection Character Strings*. Note that the following options cannot be set: * **user** and **password** The user name and password are specified when the user mapping is created. * **client\_encoding** The encoding mode of the local server is automatically obtained and set. * **application\_name** This option is always set to **postgres\_fdw**. * Specifies the parameters for the foreign server. The detailed parameter description is as follows: * encrypt Specifies whether data is encrypted. This parameter is available only when **type** is **OBS**. The default value is **on**. Value range: * **on** indicates that data is encrypted and HTTPS is used for communication. * **off** indicates that data is not encrypted and HTTP is used for communication. * access\_key Specifies the access key (AK) (obtained by users from the OBS console) used for the OBS access protocol. When you create a foreign table, the AK value is encrypted and saved to the metadata table of the database. This parameter is available only when **type** is set to **OBS**. * secret\_access\_key Specifies the secret key (SK) value (obtained by users from the OBS console) used for the OBS access protocol. When you create a foreign table, the SK value is encrypted and saved to the metadata table of the database. This parameter is available only when **type** is set to **OBS**. > \[!NOTE]NOTE > In the Lite edition, openGauss does not support obs\_server in the CREATE SERVER syntax. In addition to the connection parameters supported by libpq, the following options are provided: * **use\_remote\_estimate** Controls whether **postgres\_fdw** issues the EXPLAIN command to obtain the estimated run time. The default value is **false**. * **fdw\_startup\_cost** Estimates the startup time required for a foreign table scan. This value usually contains the time taken to establish a connection, analyze the request at the remote end, and generate a plan. The default value is **100**. * **fdw\_typle\_cost** Specifies the additional consumption when each tuple is scanned on a remote server. The value specifies the extra consumption of data transmission between servers. The default value is **0.01**. ## Examples Create a server. ``` openGauss=* create server my_server foreign data wrapper log_fdw; CREATE SERVER ``` ## Helpful Links [ALTER SERVER](alter_server.md) and [DROP SERVER](drop_server.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-create-server.md --- # CREATE SERVER ## Function Defines a new foreign server. ## Precautions * This section describes only the new syntax of Dolphin. The original syntax of openGauss is not deleted or modified. * Compared with the original openGauss, Dolphin modifies the `CREATE SERVER` syntax as follows: 1. The optional value **mysql** of fdw\_name is added. Its function is the same as that of mysql\_fdw. 2. If **fdw\_name** is set to **mysql\_fdw**, the following **OPTIONS** values are added: DATABASE, USER, PASSWORD, SOCKET, and OWNER. ## Syntax ``` CREATE SERVER server_name FOREIGN DATA WRAPPER fdw_name OPTIONS ( { option_name ' value ' } [, ...] ) ; ``` ## Parameter Description * **fdw\_name** Specifies the name of the foreign data wrapper. Value range: dist\_fdw, hdfs\_fdw, log\_fdw, file\_fdw, mot\_fdw, oracle\_fdw, mysql\_fdw, mysql, postgres\_fdw. * **OPTIONS ( { option\_name ' value ' } \[, ...] )** Specifies options for the server. These options typically define the connection details of the server, but the actual names and values depend on the foreign data wrapper of the server. * The options supported by **mysql\_fdw** are as follows: * **host** (default value: **127.0.0.1**) IP address of the MySQL server or MariaDB. * **port** (default value: **3306**) Listening port number of the MySQL server or MariaDB. * **user** (default value: empty) User name for connecting to MySQL Server or MariaDB. If this option is specified, openGauss automatically creates a user mapping from the current user to the new server. * **password** (default value: empty) Password for connecting to MySQL Server or MariaDB. If this option is specified, openGauss automatically creates a user mapping from the current user to the new server. * **database** (default value: empty) This option has no actual meaning and is used only for syntax compatibility. You can specify the database to be connected to MySQL Server or MariaDB by referring to [CREATE FOREIGN TABLE](https://docs.opengauss.org/en/docs/latest/sql_reference/create_foreign_table.html) and [ALTER FOREIGN TABLE](https://docs.opengauss.org/en/docs/latest/sql_reference/alter_foreign_table.html). * **owner** (default value: empty) This option has no actual meaning and is used only for syntax compatibility. * **socket** (default value: empty) This option has no actual meaning and is used only for syntax compatibility. ## Examples Create a server. ``` openGauss=# create server server_test foreign data wrapper mysql options(host '192.108.0.1', port '3306', user 'foreign_server_test', password 'password@123', database 'my_db', owner 'test_user'); WARNING: Option database will be deprecated for CREATE SERVER. WARNING: Option owner will be deprecated for CREATE SERVER. WARNING: USER MAPPING for current user to server server_test created. CREATE SERVER ``` ## Helpful Links [ALTER SERVER](dolphin-alter-server.md), [DROP SERVER](https://docs.opengauss.org/en/docs/latest/sql_reference/drop_server.html) --- --- url: /en/docs/latest/sql_reference/create_server.md --- # CREATE SERVER ## Function **CREATE SERVER** defines a new foreign server. ## Syntax ``` CREATE SERVER server_name [ TYPE ' server_type ' ] [ VERSION ' server_version ' ] FOREIGN DATA WRAPPER fdw_name [ OPTIONS ( { option_name ' value ' } [, ...] ) ] ; ``` ## Parameter Description * **server\_name** Specifies the server name. Value range: a string containing no more than 63 characters * **server\_type** Optional server type, which may be useful for foreign data wrappers. * **server\_version** Optional server version, which may be useful for foreign data wrappers. * **fdw\_name** Specifies the name of the foreign data wrapper. Value range: **dist\_fdw**, **hdfs\_fdw**, **log\_fdw**, **mot\_fdw**, **file\_fdw**, **oracle\_fdw**, **mysql\_fdw**, and **postgres\_fdw**. * **OPTIONS ( { option\_name ' value ' } \[, ...] )** Specifies options for the server. These options typically define the connection details of the server, but the actual names and values depend on the foreign data wrapper of the server. * Options supported by **oracle\_fdw** are as follows: * **dbserver** Connection string of the remote Oracle database. * **isolation\_level** (default value: **serializable**) Oracle database transaction isolation level. Value range: **serializable**, **read\_committed**, and **read\_only** * Options supported by **mysql\_fdw** are as follows: * **host** (default value: **127.0.0.1**) IP address of the MySQL server or MariaDB. * **port** (default value: **3306**) Listening port number of the MySQL server or MariaDB. * The options supported by postgres\_fdw are the same as those supported by libpq. For details, see *Connection Character Strings*. Note that the following options cannot be set: * **user** and **password** The user name and password are specified when the user mapping is created. * **client\_encoding** The encoding mode of the local server is automatically obtained and set. * **application\_name** This option is always set to **postgres\_fdw**. * Specifies the parameters for the foreign server. The detailed parameter description is as follows: * encrypt Specifies whether data is encrypted. This parameter is available only when **type** is **OBS**. The default value is **on**. Value range: * **on** indicates that data is encrypted and HTTPS is used for communication. * **off** indicates that data is not encrypted and HTTP is used for communication. * access\_key Specifies the access key (AK) (obtained by users from the OBS console) used for the OBS access protocol. When you create a foreign table, the AK value is encrypted and saved to the metadata table of the database. This parameter is available only when **type** is set to **OBS**. * secret\_access\_key Specifies the secret key (SK) value (obtained by users from the OBS console) used for the OBS access protocol. When you create a foreign table, the SK value is encrypted and saved to the metadata table of the database. This parameter is available only when **type** is set to **OBS**. In addition to the connection parameters supported by libpq, the following options are provided: * **use\_remote\_estimate** Controls whether **postgres\_fdw** issues the EXPLAIN command to obtain the estimated run time. The default value is **false**. * **fdw\_startup\_cost** Estimates the startup time required for a foreign table scan, including the time to establish a connection, analyzes the request at the remote server, and generates a plan. The default value is **100**. * **fdw\_typle\_cost** Specifies the additional consumption when each tuple is scanned on a remote server. The value specifies the extra consumption of data transmission between servers. The default value is **0.01**. ## Examples Create a server. ``` openGauss=* create server my_server foreign data wrapper log_fdw; CREATE SERVER ``` ## Helpful Links [ALTER SERVER](alter_server.md) and [DROP SERVER](drop_server.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CREATE-SERVER.md --- # CREATE SERVER ## 功能描述 定义一个新的外部服务器。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 * 相比于原始的openGauss,dolphin对于`CREATE SERVER`语法的修改主要为: 1. 新增fdw\_name可选值mysql,其功能与mysql\_fdw一致。 2. 对于fdw\_name为mysql\_fdw时,增加可选OPTIONS:DATABASE, USER, PASSWORD, SOCKET, OWNER。 ## 语法格式 ``` CREATE SERVER server_name FOREIGN DATA WRAPPER fdw_name OPTIONS ( { option_name ' value ' } [, ...] ) ; ``` ## 参数说明 * **fdw\_name** 指定外部数据封装器的名称。 取值范围:dist\_fdw,hdfs\_fdw,log\_fdw,file\_fdw,mot\_fdw,oracle\_fdw,mysql\_fdw,mysql, postgres\_fdw。 * **OPTIONS ( { option\_name ' value ' } \[, ...] )** 这个子句为服务器指定选项。这些选项通常定义该服务器的连接细节,但是实际的名称和值取决于该服务器的外部数据包装器。 * mysql\_fdw支持的options包括: * **host** (默认值为 127.0.0.1) MySQL Server/MariaDB的地址。 * **port** (默认值为 3306) MySQL Server/MariaDB侦听的端口号。 * **user** (默认为空) MySQL Server/MariaDB用于连接的用户名。若OPTIONS指定此选项,openGauss将自动创建当前用户到新建server的用户映射。 * **password** (默认为空) MySQL Server/MariaDB用于连接的用户密码。若OPTIONS指定此选项,openGauss将自动创建当前用户到新建server的用户映射。 * **database** (默认为空) 无实际意义,仅做语法兼容。指定MySQL Server/MariaDB连接的数据库请在[CREATE FOREIGN TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_foreign_table.html)或[ALTER FOREIGN TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_foreign_table.html)中完成。 * **owner** (默认为空) 无实际意义,仅做语法兼容。 * **socket** (默认为空) 无实际意义,仅做语法兼容。 ## 示例 创建server。 ``` openGauss=# create server server_test foreign data wrapper mysql options(host '192.108.0.1', port '3306', user 'foreign_server_test', password 'password@123', database 'my_db', owner 'test_user'); WARNING: Option database will be deprecated for CREATE SERVER. WARNING: Option owner will be deprecated for CREATE SERVER. WARNING: USER MAPPING for current user to server server_test created. CREATE SERVER ``` ## 相关链接 [ALTER SERVER](dolphin-ALTER-SERVER.md),[DROP SERVER](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/drop_server.html) --- --- url: /zh/docs/latest-lite/sql_reference/create_server.md --- # CREATE SERVER ## 功能描述 定义一个新的外部服务器。 ## 语法格式 ``` CREATE SERVER server_name [ TYPE ' server_type ' ] [ VERSION ' server_version ' ] FOREIGN DATA WRAPPER fdw_name [ OPTIONS ( { option_name ' value ' } [, ...] ) ] ; ``` ## 参数说明 * **server\_name** server的名称。 取值范围:长度必须小于等于63。 * **server\_type** 可选的服务器类型,可能对外部数据包装器有用。 * **server\_version** 可选的服务器版本,可能对外部数据包装器有用。 * **fdw\_name** 指定外部数据封装器的名称。 取值范围:dist\_fdw,hdfs\_fdw,log\_fdw,file\_fdw,mot\_fdw,oracle\_fdw,mysql\_fdw,postgres\_fdw。 * **OPTIONS ( { option\_name ' value ' } \[, ...] )** 这个子句为服务器指定选项。这些选项通常定义该服务器的连接细节,但是实际的名称和值取决于该服务器的外部数据包装器。 * oracle\_fdw支持的options包括: * **dbserver** 远端Oracle数据库的连接字符串。 * **isolation\_level** (默认值为serializable) oracle数据库的事务隔离级别。 取值范围:serializable, read\_committed , read\_only * mysql\_fdw支持的options包括: * **host** (默认值为 127.0.0.1) MySQL Server/MariaDB的地址。 * **port** (默认值为 3306) MySQL Server/MariaDB侦听的端口号。 * postgres\_fdw支持的options同libpq支持的连接参数一致,可参考 **链接字符** 。需要注意的是,以下几个options不支持设置: * **user**和**password** 用户名和密码将在创建user mapping时指定。 * **client\_encoding** 将自动获取本地server的编码方式并设置该值。 * **application\_name** 总是设置成postgres\_fdw。 * 用于指定外部服务器的各类参数,详细的参数说明如下所示。 * encrypt 是否对数据进行加密,该参数仅支持type为OBS时设置。默认值为on。 取值范围: * on表示对数据进行加密,使用HTTPS协议通信。 * off表示不对数据进行加密,使用HTTP协议通信。 * access\_key OBS访问协议对应的AK值(OBS云服务界面由用户获取),创建外表时AK值会加密保存到数据库的元数据表中。该参数仅支持type为OBS时设置。 * secret\_access\_key OBS访问协议对应的SK值(OBS云服务界面由用户获取),创建外表时SK值会加密保存到数据库的元数据表中。该参数仅支持type为OBS时设置。 > \[!NOTE]说明 > 轻量版场景下,openGauss不支持CREATE SERVER语法中obs\_server。 除了libpq支持的连接参数外,还额外提供3个options: * **use\_remote\_estimate** 控制postgres\_fdw是否发出EXPLAIN命令以获取运行消耗估算。默认值为false。 * **fdw\_startup\_cost** 执行一个外表扫描时的启动耗时估算。这个值通常包含建立连接、远端对请求的分析和生成计划的耗时。默认值为100。 * **fdw\_typle\_cost** 在远端服务器上对每一个元组进行扫描时的额外消耗。这个值通常表示数据在server间传输的额外消耗。默认值为0.01。 ## 示例 创建server。 ``` openGauss=* create server my_server foreign data wrapper log_fdw; CREATE SERVER ``` ## 相关链接 [ALTER SERVER](alter_server.md),[DROP SERVER](drop_server.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CREATE-SERVER.md --- # CREATE SERVER ## 功能描述 定义一个新的外部服务器。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 * 相比于原始的openGauss,dolphin对于`CREATE SERVER`语法的修改主要为: 1. 新增fdw\_name可选值mysql,其功能与mysql\_fdw一致。 2. 对于fdw\_name为mysql\_fdw时,增加可选OPTIONS:DATABASE, USER, PASSWORD, SOCKET, OWNER。 ## 语法格式 ``` CREATE SERVER server_name FOREIGN DATA WRAPPER fdw_name OPTIONS ( { option_name ' value ' } [, ...] ) ; ``` ## 参数说明 * **fdw\_name** 指定外部数据封装器的名称。 取值范围:dist\_fdw,hdfs\_fdw,log\_fdw,file\_fdw,mot\_fdw,oracle\_fdw,mysql\_fdw,mysql, postgres\_fdw。 * **OPTIONS ( { option\_name ' value ' } \[, ...] )** 这个子句为服务器指定选项。这些选项通常定义该服务器的连接细节,但是实际的名称和值取决于该服务器的外部数据包装器。 * mysql\_fdw支持的options包括: * **host** (默认值为 127.0.0.1) MySQL Server/MariaDB的地址。 * **port** (默认值为 3306) MySQL Server/MariaDB侦听的端口号。 * **user** (默认为空) MySQL Server/MariaDB用于连接的用户名。若OPTIONS指定此选项,openGauss将自动创建当前用户到新建server的用户映射。 * **password** (默认为空) MySQL Server/MariaDB用于连接的用户密码。若OPTIONS指定此选项,openGauss将自动创建当前用户到新建server的用户映射。 * **database** (默认为空) 无实际意义,仅做语法兼容。指定MySQL Server/MariaDB连接的数据库请在[CREATE FOREIGN TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_foreign_table.html)或[ALTER FOREIGN TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_foreign_table.html)中完成。 * **owner** (默认为空) 无实际意义,仅做语法兼容。 * **socket** (默认为空) 无实际意义,仅做语法兼容。 ## 示例 创建server。 ``` openGauss=# create server server_test foreign data wrapper mysql options(host '192.108.0.1', port '3306', user 'foreign_server_test', password 'password@123', database 'my_db', owner 'test_user'); WARNING: Option database will be deprecated for CREATE SERVER. WARNING: Option owner will be deprecated for CREATE SERVER. WARNING: USER MAPPING for current user to server server_test created. CREATE SERVER ``` ## 相关链接 [ALTER SERVER](dolphin-ALTER-SERVER.md),[DROP SERVER](https://docs.opengauss.org/zh/docs/latest/sql_reference/drop_server.html) --- --- url: /zh/docs/latest/sql_reference/create_server.md --- # CREATE SERVER ## 功能描述 定义一个新的外部服务器。 ## 语法格式 ``` CREATE SERVER server_name [ TYPE ' server_type ' ] [ VERSION ' server_version ' ] FOREIGN DATA WRAPPER fdw_name [ OPTIONS ( { option_name ' value ' } [, ...] ) ] ; ``` ## 参数说明 * **server\_name** server的名称。 取值范围:长度必须小于等于63。 * **server\_type** 可选的服务器类型,可能对外部数据包装器有用。 * **server\_version** 可选的服务器版本,可能对外部数据包装器有用。 * **fdw\_name** 指定外部数据封装器的名称。 取值范围:dist\_fdw,hdfs\_fdw,log\_fdw,file\_fdw,mot\_fdw,oracle\_fdw,mysql\_fdw,postgres\_fdw。 * **OPTIONS ( { option\_name ' value ' } \[, ...] )** 这个子句为服务器指定选项。这些选项通常定义该服务器的连接细节,但是实际的名称和值取决于该服务器的外部数据包装器。 * oracle\_fdw支持的options包括: * **dbserver** 远端Oracle数据库的连接字符串。 * **isolation\_level** (默认值为serializable) oracle数据库的事务隔离级别。 取值范围:serializable、 read\_committed 、 read\_only * mysql\_fdw支持的options包括: * **host** (默认值为 127.0.0.1) MySQL Server/MariaDB的地址。 * **port** (默认值为 3306) MySQL Server/MariaDB侦听的端口号。 * postgres\_fdw支持的options同libpq支持的连接参数一致,可参考 **链接字符** 。需要注意的是,以下几个options不支持设置: * **user**和**password** 用户名和密码将在创建user mapping时指定。 * **client\_encoding** 将自动获取本地server的编码方式并设置该值。 * **application\_name** 总是设置成postgres\_fdw。 * 用于指定外部服务器的各类参数,详细的参数说明如下所示。 * encrypt 是否对数据进行加密,该参数仅支持type为OBS时设置。默认值为on。 取值范围: * on表示对数据进行加密,使用HTTPS协议通信。 * off表示不对数据进行加密,使用HTTP协议通信。 * access\_key OBS访问协议对应的AK值(OBS云服务界面由用户获取),创建外表时AK值会加密保存到数据库的元数据表中。该参数仅支持type为OBS时设置。 * secret\_access\_key OBS访问协议对应的SK值(OBS云服务界面由用户获取),创建外表时SK值会加密保存到数据库的元数据表中。该参数仅支持type为OBS时设置。 除了libpq支持的连接参数外,还额外提供3个options: * **use\_remote\_estimate** 控制postgres\_fdw是否发出EXPLAIN命令以获取运行消耗估算。默认值为false。 * **fdw\_startup\_cost** 执行一个外表扫描时的启动耗时估算。这个值通常包含建立连接、远端对请求的分析和生成计划的耗时。默认值为100。 * **fdw\_typle\_cost** 在远端服务器上对每一个元组进行扫描时的额外消耗。这个值通常表示数据在server间传输的额外消耗。默认值为0.01。 ## 示例 创建server。 ``` openGauss=* create server my_server foreign data wrapper log_fdw; CREATE SERVER ``` ## 相关链接 [ALTER SERVER](alter_server.md),[DROP SERVER](drop_server.md) --- --- url: /en/docs/latest-lite/sql_reference/create_subscription.md --- # CREATE SUBSCRIPTION ## Function Description **CREATE SUBSCRIPTION** adds a new subscription to the current database. The subscription name must be different from that of any existing subscription in the database. A subscription represents a replication connection to a publisher. Therefore, this command not only adds definitions to the local system catalog, but also creates replication slots on the publication side. When the transaction that runs this command is committed, the logical replication thread is started to replicate the newly subscribed data. ## Precautions When a replication slot is created (default behavior), **CREATE SUBSCRIPTION** cannot be executed in a transaction block. ## Syntax ``` CREATE SUBSCRIPTION subscription_name CONNECTION 'conninfo' PUBLICATION publication_name [, ...] [ WITH ( subscription_parameter [= value] [, ... ] ) ] ``` ## Parameter Description * **subscription\_name** Specifies the name of a new subscription. * **CONNECTION 'conninfo'** Specifies the character string for connecting to the publication side. For example, **'host=1.1.1.1,2.2.2.2 port=10000,20000 dbname=postgres user=repusr1 password=password\_123'**. * **host** IP address of the publisher. You can specify the IP addresses of the primary and standby nodes of the publisher at the same time. If multiple IP addresses are specified, separate them with commas (,). * **port** The port number of the publication side cannot be the primary port number. The port number must be the primary port number plus 1. Otherwise, the port number conflicts with the thread pool. You can specify the ports of the primary and standby nodes of the publisher at the same time. If multiple ports are specified, separate them with commas (,). > \[!TIP]NOTICE\ > The number of hosts must be the same as that of ports. * **dbname** Specifies the database where a publication is located. * **user** and **password** Specify the username and password used to connect to the publication side. The user has the system administrator permission (**SYSADMIN**) or O\&M administrator permission (**OPRADMIN**). The password must be encrypted. Before creating a subscription, run the **gs\_guc generate -S xxxxxx -D $GAUSSHOME/bin -o subscription** command on the subscription side. * **PUBLICATION publication\_name** Specifies the name of the publication to be subscribed to on the publication side. A subscription can correspond to multiple publications. * **WITH ( subscription\_parameter \[= value] \[, ... ] )** Specifies the optional parameters for a subscription. The following parameters are supported: * **copy\_data (boolean)** Determines whether to copy existing data in the publication that is being subscribed to after copy starts. The default value is **true**. * **enabled (boolean)** Specifies whether a subscription should be actively replicated, or whether it should be just set but not started. The default value is **true**. * **slot\_name (string)** Specifies the name of the replication slot to be used. By default, the subscription name is used as the replication slot name. If **enable** is set to **false** during subscription creation, **slot\_name** is forcibly set to **NONE** which indicates a null value. In this case, the replication slot does not exist even if the value of **slot\_name** is specified. * **synchronous\_commit (enum)** The value of this parameter overwrites the value of **synchronous\_commit**. The default value is **off**. It is safe to use the value **off** for logical replication. If the subscription side loses the transaction due to a lack of synchronization, the data is sent again from the publisher. A different setting may be appropriate for synchronous logical replication. The logical replication thread reports the locations of WRITE and REFRESH operations to the publication side. When synchronous replication is used, the publication side waits for the actual REFRESH operations. This means that setting the subscriber's **synchronous\_commit** to **off** when the subscription is used for synchronous replication may increase the latency of **COMMIT** on the publication server. In this case, it is advantageous to set **synchronous\_commit** to **local** or a higher value. * **binary (boolean)** Specifies whether the subscription is sent by the publisher in binary format. The value **true** indicates that the data is sent in binary format, and the value **false** indicates that the data is sent in the default text format. Default value: **false** ## Example ``` --Create a subscription to a remote server, replicate tables in the mypublication and insert_only publications, and start replication immediately upon commit. CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb password=xxxx' PUBLICATION mypublication, insert_only; --Create a subscription to a remote server, replicate the tables in the insert_only publication, and do not start replication immediately until it is enabled later. CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb password=xxxx ' PUBLICATION insert_only WITH (enabled = false); --Modify the connection information of a subscription. ALTER SUBSCRIPTION mysub CONNECTION 'host=192.168.1.51 port=5432 user=foo dbname=foodb password=xxxx'; --Enable a subscription. ALTER SUBSCRIPTION mysub SET(enabled=true); --Delete a subscription. DROP SUBSCRIPTION mysub; ``` ## Helpful Links [ALTER SUBSCRIPTION](alter_subscription.md), [DROP SUBSCRIPTION](drop_subscription.md) --- --- url: /en/docs/latest/sql_reference/create_subscription.md --- # CREATE SUBSCRIPTION ## Function **CREATE SUBSCRIPTION** adds a new subscription to the current database. Only the system administrator can create a subscription. The subscription name must be different from that of any existing subscription in the database. A subscription represents a replication connection to a publisher. Therefore, this command not only adds definitions to the local system catalog, but also creates replication slots on the publication side. When the transaction that runs this command is committed, the logical replication thread is started to replicate the newly subscribed data. ## Precautions When a replication slot is created (default behavior), **CREATE SUBSCRIPTION** cannot be executed in a transaction block. Currently, a maximum of 65,534 subscriptions (including enabled and disabled subscriptions) are supported. ## Syntax ``` CREATE SUBSCRIPTION subscription_name CONNECTION 'conninfo' PUBLICATION publication_name [, ...] [ WITH ( subscription_parameter [= value] [, ... ] ) ] ``` ## Parameter Description * **subscription\_name** Specifies the name of a new subscription. * **CONNECTION 'conninfo'** Specifies the character string for connecting to the publication side. For example, **'host=1.1.1.1,2.2.2.2 port=10000,20000 dbname=postgres user=repusr1 password=password\_123'**. * **host** IP address of the publisher. You can specify the IP addresses of the primary and standby nodes of the publisher at the same time. If multiple IP addresses are specified, separate them with commas (,). * **port** The port number of the publication side cannot be the primary port number. The port number must be the primary port number plus 1. Otherwise, the port number conflicts with the thread pool. > \[!WARNING]CAUTION > The number of hosts must be the same as that of ports. * **dbname** Specifies the database where a publication is located. * **user** and **password** Specify the username and password used to connect to the publication side. The user has the system administrator permission (**SYSADMIN**) or O\&M administrator permission (**OPRADMIN**). The password must be encrypted. Before creating a subscription, run the **gs\_guc generate -S xxxxxx -D $GAUSSHOME/bin -o subscription** command on the subscription side. * **PUBLICATION publication\_name** Specifies the name of the publication to be subscribed to on the publication side. A subscription can correspond to multiple publications. * **WITH ( subscription\_parameter \[= value] \[, ... ] )** Specifies the optional parameters for a subscription. The following parameters are supported: * **copy\_data (boolean)** Determines whether to copy existing data in the publication that is being subscribed to after copy starts. The default value is **true**. * **enabled (boolean)** Specifies whether a subscription should be actively replicated, or whether it should be just set but not started. The default value is **true**. * **slot\_name (string)** Specifies the name of the replication slot to be used. By default, the subscription name is used as the replication slot name. If **enabled** is set to **false** during subscription creation, **slot\_name** is forcibly set to **NONE** which indicates a null value. In this case, the replication slot does not exist even if the value of **slot\_name** is specified. * **synchronous\_commit (enum)** The value of this parameter overwrites the value of **synchronous\_commit**. The default value is **off**. It is safe to use the value **off** for logical replication. If the subscription side loses the transaction due to a lack of synchronization, the data is sent again from the publisher. A different setting may be appropriate for synchronous logical replication. The logical replication thread reports the locations of WRITE and REFRESH operations to the publication side. When synchronous replication is used, the publication side waits for the actual REFRESH operations. This means that setting the subscriber's **synchronous\_commit** to **off** when the subscription is used for synchronous replication may increase the latency of **COMMIT** on the publication server. In this case, it is advantageous to set **synchronous\_commit** to **local** or a higher value. * **binary (boolean)** Specifies whether the subscription is sent by the publisher in binary format. The value **true** indicates that the data is sent in binary format, and the value **false** indicates that the data is sent in the default text format. Default value: **false** * **connect (boolean)** Specifies whether to connect to the publisher during CREATE SUBSCRIPTION. If this parameter is set to **false**, **enabled** and **copy\_data** are also set to **false** by default. The default value is **true**. Do not set **enabled** or **copy\_data** to **true** when **connect** is set to **false**. When this option is set to **false**, no connection is established and the table is not subscribed to. Therefore, when subscription is enabled, no content is copied. You need to run the ALTER SUBSCRIPTION... REFRESH PUBLICATION statement to subscribe to tables. ## Examples ``` -- Create a subscription to a remote server, replicate tables in the mypublication and insert_only publications, and start replication immediately upon commit. CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb password=xxxx' PUBLICATION mypublication, insert_only; -- Create a subscription to a remote server, replicate the tables in the insert_only publication, and do not start replication immediately until it is enabled later. CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb password=xxxx ' PUBLICATION insert_only WITH (enabled = false); -- Modify the connection information of a subscription. ALTER SUBSCRIPTION mysub CONNECTION 'host=192.168.1.51 port=5432 user=foo dbname=foodb password=xxxx'; -- Enable a subscription. ALTER SUBSCRIPTION mysub SET(enabled=true); -- Delete a subscription. DROP SUBSCRIPTION mysub; ``` ## Helpful Links [ALTER SUBSCRIPTION](alter_subscription.md) and [DROP SUBSCRIPTION](drop_subscription.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_subscription.md --- # CREATE SUBSCRIPTION ## 功能描述 为当前数据库添加一个新的订阅。订阅名称必须与数据库中任何现有的订阅不同。 订阅表示到发布者的复制连接。因此,此命令不仅在本地系统表中添加定义,还会在发布端创建复制槽。 在运行此命令的事务提交时,将启动逻辑复制线程以复制新订阅的数据。 ## 注意事项 创建复制槽时(默认行为),CREATE SUBSCRIPTION不能在事务块内部执行。 ## 语法格式 ``` CREATE SUBSCRIPTION subscription_name CONNECTION 'conninfo' PUBLICATION publication_name [, ...] [ WITH ( subscription_parameter [= value] [, ... ] ) ] ``` ## 参数说明 * **subscription\_name** 新订阅的名称。 * **CONNECTION 'conninfo'** 连接发布端的字符串。 如'host=1.1.1.1,2.2.2.2 port=10000,20000 dbname=postgres user=repusr1 password=password\_123'。 * **host** 发布端IP地址,可以同时指定发布端主机和备机的IP地址,如果同时指定了多个IP,以英文逗号分隔。 * **port** 发布端端口,此处的端口不能使用主端口,而应该使用主端口+1端口,否则会与线程池冲突。可以同时指定发布端主机和备机的端口,如果同时指定了多个端口,以英文逗号分隔。 > \[!WARNING]注意\ > host和port的数量要一致,并且要一一对应。 * **dbname** 发布所在的数据库。 * **user和password** 用于连接发布端且具有系统管理员权限(SYSADMIN)或者运维管理员权限(OPRADMIN)的用户名和密码。password需要加密,创建订阅前需要在订阅端执行gs\_guc generate -S xxxxxx -D $GAUSSHOME/bin -o subscription。 * **PUBLICATION publication\_name** 要订阅的发布端的发布名称,一个订阅可以对应多个发布。 * **WITH ( subscription\_parameter \[= value] \[, ... ] )** 该子句指定订阅的可选参数。支持的参数有: * **copy\_data (boolean)** 指定在复制启动后是否应复制正在订阅的发布中的现有数据。默认值是true。 * **enabled (boolean)** 指定订阅是否应该主动复制,或者是否应该只是设置,但尚未启动。默认值是true。 * **slot\_name (string)** 要使用的复制插槽的名称。默认使用订阅名称作为复制槽的名称。 如果创建订阅时设置enable为false,则slot\_name将被强制设置为NONE,即空值,即使用户指定了slot\_name的值,表示复制槽不存在。 * **synchronous\_commit (enum)** 该参数的值会覆盖synchronous\_commit设置。 默认值是off。 对于逻辑复制使用off是安全的,如果订阅端由于缺少同步而丢失事务,数据将从发布者再次发送。进行同步逻辑复制时,一个不同的设置可能是合适的。逻辑复制线程向发布端报告写入和刷新的位置,当使用同步复制时,发布端将等待订阅端的事务日志完成实际刷新。这意味着,当订阅用于同步复制时,将订阅者的synchronous\_commit设置为off可能会增加发布端服务器上COMMIT的延迟,原因是off可能会增加事务日志刷盘的延迟,从而导致发布端可能需要花费更多的时间等待订阅者完成事务日志刷盘。在这种情况下,将synchronous\_commit设置为local或更高是有利的。 * **binary (boolean)** 该参数指定是否需要该订阅对应的发布端以二进制格式发送数据,为true表示需要以二进制发送,为false表示不以二进制格式而知以默认的文本格式发送。默认值false。 * **matchddlowner (boolean)** 指定订阅端在应用DDL操作时,是否切换到DDL日志信息中指定owner用户。 * **syncconninfo(bolean)** 指定订阅端在服务端主备切换后,是否会进行同步发布端连接信息,为true表示会同步发布端连接信息。false则不会同步发布端连接信息。默认值是true。 ## 示例 ``` --创建一个到远程服务器的订阅,复制发布mypublication和insert_only中的表,并在提交时立即开始复制。 CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb password=xxxx' PUBLICATION mypublication, insert_only; --创建一个到远程服务器的订阅,复制insert_only发布中的表, 并且不开始复制直到稍后启用复制。 CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb password=xxxx ' PUBLICATION insert_only WITH (enabled = false); --修改订阅的连接信息。 ALTER SUBSCRIPTION mysub CONNECTION 'host=192.168.1.51 port=5432 user=foo dbname=foodb password=xxxx'; --激活订阅。 ALTER SUBSCRIPTION mysub SET(enabled=true); --删除订阅。 DROP SUBSCRIPTION mysub; ``` ## 相关链接 [ALTER SUBSCRIPTION](alter_subscription.md),[DROP SUBSCRIPTION](drop_subscription.md) --- --- url: /zh/docs/latest/sql_reference/create_subscription.md --- # CREATE SUBSCRIPTION ## 功能描述 为当前数据库添加一个新的订阅。订阅名称必须与数据库中任何现有的订阅不同。 订阅表示到发布者的复制连接。因此,此命令不仅在本地系统表中添加定义,还会在发布端创建复制槽。 在运行此命令的事务提交时,将启动逻辑复制线程以复制新订阅的数据。 ## 注意事项 创建复制槽时(默认行为),CREATE SUBSCRIPTION不能在事务块内部执行。 ## 语法格式 ``` CREATE SUBSCRIPTION subscription_name CONNECTION 'conninfo' PUBLICATION publication_name [, ...] [ WITH ( subscription_parameter [= value] [, ... ] ) ] ``` ## 参数说明 * **subscription\_name** 新订阅的名称。 * **CONNECTION 'conninfo'** 连接发布端的字符串。 如'host=1.1.1.1,2.2.2.2 port=10000,20000 dbname=postgres user=repusr1 password=password\_123'。 * **host** 发布端IP地址,可以同时指定发布端主机和备机的IP地址,如果同时指定了多个IP,以英文逗号分隔。 * **port** 发布端端口,此处的端口不能使用主端口,而应该使用主端口+1端口,否则会与线程池冲突。可以同时指定发布端主机和备机的端口,如果同时指定了多个端口,以英文逗号分隔。 > \[!WARNING]注意\ > host和port的数量要一致,并且要一一对应。 * **dbname** 发布所在的数据库。 * **user和password** 用于连接发布端且具有系统管理员权限(SYSADMIN)或者运维管理员权限(OPRADMIN)的用户名和密码。password需要加密,创建订阅前需要在订阅端执行gs\_guc generate -S xxxxxx -D $GAUSSHOME/bin -o subscription。 * **PUBLICATION publication\_name** 要订阅的发布端的发布名称,一个订阅可以对应多个发布。 * **WITH ( subscription\_parameter \[= value] \[, ... ] )** 该子句指定订阅的可选参数。支持的参数有: * **copy\_data (boolean)** 指定在复制启动后是否应复制正在订阅的发布中的现有数据。默认值是true。 * **enabled (boolean)** 指定订阅是否应该主动复制,或者是否应该只是设置,但尚未启动。默认值是true。 * **slot\_name (string)** 要使用的复制插槽的名称。默认使用订阅名称作为复制槽的名称。 如果创建订阅时设置enable为false,则slot\_name将被强制设置为NONE,即空值,即使用户指定了slot\_name的值,表示复制槽不存在。 * **synchronous\_commit (enum)** 该参数的值会覆盖synchronous\_commit设置。 默认值是off。 对于逻辑复制使用off是安全的,如果订阅端由于缺少同步而丢失事务,数据将从发布者再次发送。进行同步逻辑复制时,一个不同的设置可能是合适的。逻辑复制线程向发布端报告写入和刷新的位置,当使用同步复制时,发布端将等待订阅端的事务日志完成实际刷新。这意味着,当订阅用于同步复制时,将订阅者的synchronous\_commit设置为off可能会增加发布端服务器上COMMIT的延迟,原因是off可能会增加事务日志刷盘的延迟,从而导致发布端可能需要花费更多的时间等待订阅者完成事务日志刷盘。在这种情况下,将synchronous\_commit设置为local或更高是有利的。 * **binary (boolean)** 该参数指定是否需要该订阅对应的发布端以二进制格式发送数据,为true表示需要以二进制发送,为false表示不以二进制格式而知以默认的文本格式发送。默认值false。 * **connect (boolean)** 指定CREATE SUBSCRIPTION是否应该连接到发布者。设置为false会默认将enabled和copy\_data也设置为false。默认值true。 不允许将connect设置为false的同时将enabled或copy\_data设置为true。 因为该选项设置为false时不会建立连接,因此表没有被订阅,所以当启用订阅后,不会复制任何内容。需要执行ALTER SUBSCRIPTION ... REFRESH PUBLICATION才能订阅表。 * **matchddlowner (boolean)** 指定订阅端在应用DDL操作时,是否切换到DDL日志信息中指定owner用户。 * **syncconninfo(bolean)** 指定订阅端在服务端主备切换后,是否会进行同步发布端连接信息,为true表示会同步发布端连接信息。false则不会同步发布端连接信息。默认值是true。 ## 示例 ``` --创建一个到远程服务器的订阅,复制发布mypublication和insert_only中的表,并在提交时立即开始复制。 CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb password=xxxx' PUBLICATION mypublication, insert_only; --创建一个到远程服务器的订阅,复制insert_only发布中的表, 并且不开始复制直到稍后启用复制。 CREATE SUBSCRIPTION mysub CONNECTION 'host=192.168.1.50 port=5432 user=foo dbname=foodb password=xxxx ' PUBLICATION insert_only WITH (enabled = false); --修改订阅的连接信息。 ALTER SUBSCRIPTION mysub CONNECTION 'host=192.168.1.51 port=5432 user=foo dbname=foodb password=xxxx'; --激活订阅。 ALTER SUBSCRIPTION mysub SET(enabled=true); --删除订阅。 DROP SUBSCRIPTION mysub; ``` ## 相关链接 [ALTER SUBSCRIPTION](alter_subscription.md),[DROP SUBSCRIPTION](drop_subscription.md) --- --- url: /en/docs/latest-lite/sql_reference/create_synonym.md --- # CREATE SYNONYM ## Function **CREATE SYNONYM** creates a synonym object. A synonym is an alias of a database object and is used to record the mapping between database object names. You can use synonyms to access associated database objects. ## Precautions * The user of a synonym should be its owner. * If the schema name is specified, create a synonym in the specified schema. Otherwise create a synonym in the current schema. * Database objects that can be accessed using synonyms include tables, views, functions, and stored procedures. * To use synonyms, you must have the required permissions on associated objects. * The following DML statements support synonyms: **SELECT**, **INSERT**, **UPDATE**, **DELETE**, **EXPLAIN**, and **CALL**. * You are not advised to create synonyms for temporary tables. To create a synonym, you need to specify the schema name of the target temporary table. Otherwise, the synonym cannot be used normally. In addition, you need to run the **DROP SYNONYM** command before the current session ends. * After an original object is deleted, the synonym associated with the object will not be deleted in cascading mode. If you continue to access the synonym, an error message is displayed, indicating that the synonym has expired. * Users granted the CREATE ANY SYNONYM permission can create synonyms in user schemas. * Users granted the CREATE ANY SYNONYM permission can create synonyms in user schemas. * When creating a synonym, if **PUBLIC** is specified, the schema name of synonym cannot be specified. ## Syntax ``` CREATE [ OR REPLACE ] [ PUBLIC ] SYNONYM synonym_name FOR object_name; ``` ## Parameter Description * **OR REPLACE** * If the synonym already exists, the existing synonym is replaced. * If the synonym does not exist, a new synonym is created. * **PUBLIC** * Specifies that the synonym is a public synonym. If you do not specify PUBLIC, the synonym is a private synonym. * **synonym** Specifies the name of the synonym to be created, which can contain the schema name. Value range: a string. It must comply with the identifier naming convention. * **object\_name** Specifies the name of an object that is associated (optionally with schema names). Value range: a string. It must comply with the identifier naming convention. > \[!NOTE]NOTE > > **object\_name** can be the name of an object that does not exist. ## Examples ``` -- Create schema ot. openGauss=# CREATE SCHEMA ot; -- Create table ot.t1 and its synonym t1. openGauss=# CREATE TABLE ot.t1(id int, name varchar2(10)); openGauss=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1; -- Use synonym t1. openGauss=# SELECT * FROM t1; openGauss=# INSERT INTO t1 VALUES (1, 'ada'), (2, 'bob'); openGauss=# UPDATE t1 SET t1.name = 'cici' WHERE t1.id = 2; -- Create synonym v1 and its associated view ot.v_t1. openGauss=# CREATE SYNONYM v1 FOR ot.v_t1; openGauss=# CREATE VIEW ot.v_t1 AS SELECT * FROM ot.t1; -- Use synonym v1. openGauss=# SELECT * FROM v1; -- Create overloaded function ot.add and its synonym add. openGauss=# CREATE OR REPLACE FUNCTION ot.add(a integer, b integer) RETURNS integer AS $$ SELECT $1 + $2 $$ LANGUAGE sql; openGauss=# CREATE OR REPLACE FUNCTION ot.add(a decimal(5,2), b decimal(5,2)) RETURNS decimal(5,2) AS $$ SELECT $1 + $2 $$ LANGUAGE sql; openGauss=# CREATE OR REPLACE SYNONYM add FOR ot.add; -- Use synonym add. openGauss=# SELECT add(1,2); openGauss=# SELECT add(1.2,2.3); -- Create stored procedure ot.register and its synonym register. openGauss=# CREATE PROCEDURE ot.register(n_id integer, n_name varchar2(10)) SECURITY INVOKER AS BEGIN INSERT INTO ot.t1 VALUES(n_id, n_name); END; / openGauss=# CREATE OR REPLACE SYNONYM register FOR ot.register; -- Use synonym register to invoke the stored procedure. openGauss=# CALL register(3,'mia'); -- Public synonym -- Create a public synonym. openGauss=# CREATE PUBLIC SYNONYM t1 FOR ot.t1; -- Use the public synonym. openGauss=# SELECT * FROM t1; -- Delete the synonym. openGauss=# DROP SYNONYM t1; openGauss=# DROP SYNONYM IF EXISTS v1; openGauss=# DROP SYNONYM IF EXISTS add; openGauss=# DROP SYNONYM register; openGauss=# DROP PUBLIC SYNONYM t1; openGauss=# DROP SCHEMA ot CASCADE; ``` ## Helpful Links [ALTER SYNONYM](alter_synonym.md) and [DROP SYNONYM](drop_synonym.md) --- --- url: /en/docs/latest/sql_reference/create_synonym.md --- # CREATE SYNONYM ## Function **CREATE SYNONYM** creates a synonym object. A synonym is an alias of a database object and is used to record the mapping between database object names. You can use synonyms to access associated database objects. ## Precautions * The user of a synonym should be its owner. * If the schema name is specified, create a synonym in the specified schema. Otherwise create a synonym in the current schema. * Database objects that can be accessed using synonyms include tables, views, functions, and stored procedures. * To use synonyms, you must have the required permissions on associated objects. * The following DML statements support synonyms: **SELECT**, **INSERT**, **UPDATE**, **DELETE**, **EXPLAIN**, and **CALL**. * You are not advised to create synonyms for temporary tables. To create a synonym, you need to specify the schema name of the target temporary table. Otherwise, the synonym cannot be used normally. In addition, you need to run the **DROP SYNONYM** command before the current session ends. * After an original object is deleted, the synonym associated with the object will not be deleted in cascading mode. If you continue to access the synonym, an error message is displayed, indicating that the synonym has expired. * Users granted the CREATE ANY SYNONYM permission can create synonyms in user schemas. * Users granted the CREATE PUBLIC SYNONYM permission can create public synonyms. * Users granted the DROP PUBLIC SYNONYM permission can delete public synonyms. * When creating a synonym, if **PUBLIC** is specified, the schema name of synonym cannot be specified. ## Syntax ``` CREATE [ OR REPLACE ] [ PUBLIC ] SYNONYM synonym_name FOR object_name; ``` ## Parameter Description * **OR REPLACE** * If the synonym exists, replace the existing synonym. * If the synonym does not exist, create a new synonym. * **PUBLIC** * Specifies that the synonym is a public synonym. If **PUBLIC** is not specified, the synonym is a private synonym. * **synonym** Specifies the name of the synonym to be created, which can contain the schema name. Value range: a string. It must comply with the identifier naming convention. * **object\_name** Specifies the name of an object that is associated (optionally with schema names). Value range: a string. It must comply with the identifier naming convention. > \[!NOTE]NOTE > **object\_name** can be the name of an object that does not exist. ## Examples ``` -- Create schema ot. openGauss=# CREATE SCHEMA ot; -- Create table ot.t1 and its synonym t1. openGauss=# CREATE TABLE ot.t1(id int, name varchar2(10)); openGauss=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1; -- Use synonym t1. openGauss=# SELECT * FROM t1; openGauss=# INSERT INTO t1 VALUES (1, 'ada'), (2, 'bob'); openGauss=# UPDATE t1 SET t1.name = 'cici' WHERE t1.id = 2; -- Create synonym v1 and its associated view ot.v_t1. openGauss=# CREATE SYNONYM v1 FOR ot.v_t1; openGauss=# CREATE VIEW ot.v_t1 AS SELECT * FROM ot.t1; -- Use synonym v1. openGauss=# SELECT * FROM v1; -- Create overloaded function ot.add and its synonym add. openGauss=# CREATE OR REPLACE FUNCTION ot.add(a integer, b integer) RETURNS integer AS $$ SELECT $1 + $2 $$ LANGUAGE sql; openGauss=# CREATE OR REPLACE FUNCTION ot.add(a decimal(5,2), b decimal(5,2)) RETURNS decimal(5,2) AS $$ SELECT $1 + $2 $$ LANGUAGE sql; openGauss=# CREATE OR REPLACE SYNONYM add FOR ot.add; -- Use synonym add. openGauss=# SELECT add(1,2); openGauss=# SELECT add(1.2,2.3); -- Create stored procedure ot.register and its synonym register. openGauss=# CREATE PROCEDURE ot.register(n_id integer, n_name varchar2(10)) SECURITY INVOKER AS BEGIN INSERT INTO ot.t1 VALUES(n_id, n_name); END; / openGauss=# CREATE OR REPLACE SYNONYM register FOR ot.register; -- Use synonym register to invoke the stored procedure. openGauss=# CALL register(3,'mia'); -- Create a public synonym. openGauss=# CREATE PUBLIC SYNONYM t1 FOR ot.t1; -- Use the public synonym. openGauss=# SELECT * FROM t1; -- Delete the synonym. openGauss=# DROP SYNONYM t1; openGauss=# DROP SYNONYM IF EXISTS v1; openGauss=# DROP SYNONYM IF EXISTS add; openGauss=# DROP SYNONYM register; openGauss=# DROP PUBLIC SYNONYM t1; openGauss=# DROP SCHEMA ot CASCADE; ``` ## Helpful Links [ALTER SYNONYM](alter_synonym.md) and [DROP SYNONYM](drop_synonym.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_synonym.md --- # CREATE SYNONYM ## 功能描述 创建一个同义词对象。同义词是数据库对象的别名,用于记录与其他数据库对象名间的映射关系,用户可以使用同义词访问关联的数据库对象。 ## 注意事项 * 定义同义词的用户成为其所有者。 * 若指定模式名称,则同义词在指定模式中创建。否则,在当前模式创建。 * 支持通过同义词访问的数据库对象包括:表、视图、函数和存储过程以及package中的存储过程和函数,不支持package中变量的引用。 * 使用同义词时,用户需要具有对关联对象的相应权限。 * 支持使用同义词的DML语句包括:SELECT、INSERT、UPDATE、DELETE、EXPLAIN、CALL、REFRESH。 * 不建议对临时表创建同义词。如果需要创建的话,需要指定同义词的目标临时表的模式名,否则无法正常使用该同义词,并且在当前会话结束前执行DROP SYNONYM命令。 * 删除原对象后,与之关联同义词不会被级联删除,继续访问该同义词会报错,并提示已失效。 * 被授予了CREATE ANY SYNONYM权限的用户能够在用户模式下创建同义词。 * 被授予了CREATE ANY SYNONYM权限的用户能够在用户模式下创建同义词。 * 不可与同一模式下已存在的表、视图、函数以及存储过程产生命名冲突。 * 被授予了CREATE PUBLIC SYNONYM权限的用户能够创建公共同义词。 * 被授予了DROP PUBLIC SYNONYM权限的用户能够删除公共同义词。 * 创建同义词时,如果指定了PUBLIC,则不能再指定同义词的模式名。 ## 语法格式 ``` CREATE [ OR REPLACE ] [ PUBLIC ] SYNONYM synonym_name FOR object_name; ``` ## 参数说明 * **OR REPLACE** * 如果同义词已存在,则替换现有同义词。 * 如果同义词不存在,则创建新的同义词。 * **PUBLIC** * 指定同义词为公共同义词。如果不指定PUBLIC,则同义词为私有同义词。 * **synonym** 创建的同义词名字,可以带模式名。 取值范围:字符串,要符合标识符的命名规范。 * **object\_name** 关联的对象名字,可以带模式名。 取值范围:字符串,要符合标识符的命名规范。 > \[!NOTE]说明 > object\_name可以是不存在的对象名称。 ## 示例 ``` --创建模式ot。 openGauss=# CREATE SCHEMA ot; --创建表ot.t1及其同义词t1。 openGauss=# CREATE TABLE ot.t1(id int, name varchar2(10)); openGauss=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1; --使用同义词t1。 openGauss=# SELECT * FROM t1; openGauss=# INSERT INTO t1 VALUES (1, 'ada'), (2, 'bob'); openGauss=# UPDATE t1 SET t1.name = 'cici' WHERE t1.id = 2; --创建同义词v1及其关联视图ot.v_t1。 openGauss=# CREATE SYNONYM v1 FOR ot.v_t1; openGauss=# CREATE VIEW ot.v_t1 AS SELECT * FROM ot.t1; --使用同义词v1。 openGauss=# SELECT * FROM v1; --创建重载函数ot.add及其同义词add。 openGauss=# CREATE OR REPLACE FUNCTION ot.add(a integer, b integer) RETURNS integer AS $$ SELECT $1 + $2 $$ LANGUAGE sql; openGauss=# CREATE OR REPLACE FUNCTION ot.add(a decimal(5,2), b decimal(5,2)) RETURNS decimal(5,2) AS $$ SELECT $1 + $2 $$ LANGUAGE sql; openGauss=# CREATE OR REPLACE SYNONYM add FOR ot.add; --使用同义词add。 openGauss=# SELECT add(1,2); openGauss=# SELECT add(1.2,2.3); --创建存储过程ot.register及其同义词register。 openGauss=# CREATE PROCEDURE ot.register(n_id integer, n_name varchar2(10)) SECURITY INVOKER AS BEGIN INSERT INTO ot.t1 VALUES(n_id, n_name); END; / openGauss=# CREATE OR REPLACE SYNONYM register FOR ot.register; --使用同义词register,调用存储过程。 openGauss=# CALL register(3,'mia'); -- 创建公共同义词。 openGauss=# CREATE PUBLIC SYNONYM t1 FOR ot.t1; -- 使用公共同义词。 openGauss=# SELECT * FROM t1; --删除同义词。 openGauss=# DROP SYNONYM t1; openGauss=# DROP SYNONYM IF EXISTS v1; openGauss=# DROP SYNONYM IF EXISTS add; openGauss=# DROP SYNONYM register; openGauss=# DROP PUBLIC SYNONYM t1; openGauss=# DROP SCHEMA ot CASCADE; ``` ## 相关链接 [ALTER SYNONYM](alter_synonym.md),[DROP SYNONYM](drop_synonym.md) --- --- url: /zh/docs/latest/ograc/sql_reference/create_synonym.md --- # CREATE SYNONYM ## 功能描述 `CREATE SYNONYM` 语句用于创建数据库对象的别名,简化SQL语句的编写和使用。同义词可以指向表等数据库对象,提供了一种抽象层来隐藏对象的真实名称和所有者。 ## 注意事项 创建同义词需要对目标对象具有访问权限;公共同义词对所有用户可见,请谨慎使用以避免命名冲突。 ## 语法格式 ### 创建私有同义词 ```sql CREATE [OR REPLACE] SYNONYM synonym_name FOR object_name; ``` ### 创建公共同义词 ``` CREATE [OR REPLACE] PUBLIC SYNONYM synonym_name FOR object_name; ``` ## 参数说明 | 参数名 | 说明 | |--------|-----------------------------------------------| | OR REPLACE | 可选参数。如果同义词已存在,则替换它而不是报错。 | | PUBLIC | 可选参数。创建公共同义词,所有用户都可以访问。如果不指定,则创建私有同义词,仅创建者可见。 | | synonym\_name | 要创建的同义词名称。 | | object\_name | 同义词指向的对象名称。 | ## 示例 ### 示例 1:创建私有同义词 ``` CREATE SYNONYM emp FOR employees; ``` ### 示例 2:替换私有同义词 ``` CREATE OR REPLACE SYNONYM emp FOR employees; ``` ### 示例 3:创建公共同义词 ``` CREATE PUBLIC SYNONYM dept FOR departments; ``` ### 示例 4:替换公共同义词 ``` CREATE OR REPLACE PUBLIC SYNONYM dept FOR departments; ``` ### 示例 5:创建同义词后查询 ``` -- 创建同义词 CREATE SYNONYM emp FOR employees; -- 使用同义词查询 SELECT * FROM emp WHERE department_id = 10; ``` --- --- url: /zh/docs/latest/sql_reference/create_synonym.md --- # CREATE SYNONYM ## 功能描述 创建一个同义词对象。同义词是数据库对象的别名,用于记录与其他数据库对象名间的映射关系,用户可以使用同义词访问关联的数据库对象。 ## 注意事项 * 定义同义词的用户成为其所有者。 * 若指定模式名称,则同义词在指定模式中创建。否则,在当前模式创建。 * 支持通过同义词访问的数据库对象包括:表、视图、函数和存储过程以及package中的存储过程和函数,不支持package中变量的引用。 * 使用同义词时,用户需要具有对关联对象的相应权限。 * 支持使用同义词的DML语句包括:SELECT、INSERT、UPDATE、DELETE、EXPLAIN、CALL、REFRESH。 * 不建议对临时表创建同义词。如果需要创建的话,需要指定同义词的目标临时表的模式名,否则无法正常使用该同义词,并且在当前会话结束前执行DROP SYNONYM命令。 * 删除原对象后,与之关联同义词不会被级联删除,继续访问该同义词会报错,并提示已失效。 * 被授予了CREATE ANY SYNONYM权限的用户能够在用户模式下创建同义词。 * 不可与同一模式下已存在的表、视图、函数以及存储过程产生命名冲突。 * 被授予了CREATE PUBLIC SYNONYM权限的用户能够创建公共同义词。 * 被授予了DROP PUBLIC SYNONYM权限的用户能够删除公共同义词。 * 创建同义词时,如果指定了PUBLIC,则不能再指定同义词的模式名。 ## 语法格式 ``` CREATE [ OR REPLACE ] [ PUBLIC ] SYNONYM synonym_name FOR object_name; ``` ## 参数说明 * **OR REPLACE** * 如果同义词存在,则替换现有同义词。 * 如果同义词不存在,则创建新的同义词。 * **PUBLIC** * 指定同义词为公共同义词。如果不指定PUBLIC,则同义词为私有同义词。 * **synonym** 创建的同义词名字,可以带模式名。 取值范围:字符串,要符合标识符的命名规范。 * **object\_name** 关联的对象名字,可以带模式名。 取值范围:字符串,要符合标识符的命名规范。 > \[!NOTE]说明 > > object\_name可以是不存在的对象名称。 ## 示例 ``` --创建模式ot。 openGauss=# CREATE SCHEMA ot; --创建表ot.t1及其同义词t1。 openGauss=# CREATE TABLE ot.t1(id int, name varchar2(10)); openGauss=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1; --使用同义词t1。 openGauss=# SELECT * FROM t1; openGauss=# INSERT INTO t1 VALUES (1, 'ada'), (2, 'bob'); openGauss=# UPDATE t1 SET t1.name = 'cici' WHERE t1.id = 2; --创建同义词v1及其关联视图ot.v_t1。 openGauss=# CREATE SYNONYM v1 FOR ot.v_t1; openGauss=# CREATE VIEW ot.v_t1 AS SELECT * FROM ot.t1; --使用同义词v1。 openGauss=# SELECT * FROM v1; --创建重载函数ot.add及其同义词add。 openGauss=# CREATE OR REPLACE FUNCTION ot.add(a integer, b integer) RETURNS integer AS $$ SELECT $1 + $2 $$ LANGUAGE sql; openGauss=# CREATE OR REPLACE FUNCTION ot.add(a decimal(5,2), b decimal(5,2)) RETURNS decimal(5,2) AS $$ SELECT $1 + $2 $$ LANGUAGE sql; openGauss=# CREATE OR REPLACE SYNONYM add FOR ot.add; --使用同义词add。 openGauss=# SELECT add(1,2); openGauss=# SELECT add(1.2,2.3); --创建存储过程ot.register及其同义词register。 openGauss=# CREATE PROCEDURE ot.register(n_id integer, n_name varchar2(10)) SECURITY INVOKER AS BEGIN INSERT INTO ot.t1 VALUES(n_id, n_name); END; / openGauss=# CREATE OR REPLACE SYNONYM register FOR ot.register; --使用同义词register,调用存储过程。 openGauss=# CALL register(3,'mia'); -- 创建公共同义词 openGauss=# CREATE PUBLIC SYNONYM t1 FOR ot.t1; -- 使用公共同义词 openGauss=# SELECT * FROM t1; --删除同义词。 openGauss=# DROP SYNONYM t1; openGauss=# DROP SYNONYM IF EXISTS v1; openGauss=# DROP SYNONYM IF EXISTS add; openGauss=# DROP SYNONYM register; openGauss=# DROP PUBLIC SYNONYM t1; openGauss=# DROP SCHEMA ot CASCADE; ``` ## 相关链接 [ALTER SYNONYM](alter_synonym.md),[DROP SYNONYM](drop_synonym.md) --- --- url: /en/docs/latest-lite/sql_reference/create_table.md --- # CREATE TABLE ## Function **CREATE TABLE** creates an initially empty table in the current database. The table will be owned by the creator. ## Precautions * For details about the data types supported by column-store tables, see [Data Types Supported by Column-store Tables](data_types_supported_by_column_store_tables.md). * Column-store tables do not support the array. * Column-store tables do not support column generation. * Column-store tables cannot be created as global temporary tables. * It is recommended that the number of column-store tables do not exceed 1000. * If an error occurs during table creation, after it is fixed, the system may fail to delete the empty disk files created before the last automatic clearance. This problem seldom occurs and does not affect system running of the database. * Only **PARTIAL CLUSTER KEY**, **UNIQUE**, and **PRIAMRY KEY** can be used as the table-level constraint of column-store tables. Table-level foreign key constraints are not supported. * Only the **NULL**, **NOT NULL**, **DEFAULT** constant values, **UNIQUE**, and **PRIMARY KEY** can be used as column-store table constraints. * Whether column-store tables support a delta table is specified by the enable\_delta\_store parameter. The threshold for storing data into a delta table is specified by the **deltarow\_threshold** parameter. * When JDBC is used, the **DEFAULT** value can be set through **PrepareStatement**. * The maximum number of columns on each table is 1600, which depends on the column type. The total size of all columns cannot exceed 8192 bytes, except for the columns of variable data types, such as text, varchar, and char. * A user granted with the **CREATE ANY TABLE** permission can create tables in the public and user schemas. To create a table that contains serial columns, you must also grant the **CREATE ANY SEQUENCE** permission to create sequences. ## Syntax Create a table. ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ]) [ AUTO_INCREMENT [ = ] value ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMMENT {=| } 'text' ]; ``` * **column\_constraint** is as follows: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | AUTO_INCREMENT | UNIQUE index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * **compress\_mode** of a column is as follows: ``` { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } ``` * **table\_constraint** is as follows: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { { column_name | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * **like\_option** is as follows: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | PARTITION | RELOPTIONS | ALL } ``` * **index\_parameters** is as follows: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## Parameter Description * **UNLOGGED** If this keyword is specified, the created table is an unlogged table. Data written to unlogged tables is not written to the WALs, which makes them considerably faster than ordinary tables. However, an unlogged table is automatically truncated after a crash or unclean shutdown, incurring data loss risks. Contents of an unlogged table are also not replicated to standby servers. Any indexes created on an unlogged table are not automatically logged as well. Usage scenario: Unlogged tables do not ensure data security. Users can back up data before using unlogged tables; for example, users should back up the data before a system upgrade. Troubleshooting: If data is missing in the indexes of unlogged tables due to some unexpected operations such as an unclean shutdown, users should re-create the indexes with errors. * **GLOBAL | LOCAL** When creating a temporary table, you can specify the **GLOBAL** or **LOCAL** keyword before **TEMP** or **TEMPORARY**. If the keyword **GLOBAL** is specified, openGauss creates a global temporary table. Otherwise, openGauss creates a local temporary table. * **TEMPORARY | TEMP** If **TEMP** or **TEMPORARY** is specified, the created table is a temporary table. Temporary tables are classified into global temporary tables and local temporary tables. If the keyword **GLOBAL** is specified when a temporary table is created, the table is a global temporary table. Otherwise, the table is a local temporary table. The metadata of the global temporary table is visible to all sessions. After the sessions end, the metadata still exists. The user data, indexes, and statistics of a session are isolated from those of another session. Each session can only view and modify the data submitted by itself. Global temporary tables have two schemas: **ON COMMIT PRESERVE ROWS** and **ON COMMIT PRESERVE ROWS**. In session-based **ON COMMIT PRESERVE ROWS** schema, user data is automatically cleared when a session ends. In transaction-based **ON COMMIT DELETE ROWS** schema, user data is automatically cleared when the commit or rollback operation is performed. If the **ON COMMIT** option is not specified during table creation, the session level is used by default. Different from local temporary tables, you can specify a schema that does not start with **pg\_temp\_** when creating a global temporary table. A local temporary table is automatically dropped at the end of the current session. Therefore, you can create and use temporary tables in the current session as long as the connected database node in the session is normal. Temporary tables are created only in the current session. If a DDL statement involves operations on temporary tables, a DDL error will be generated. Therefore, you are not advised to perform operations on temporary tables in DDL statements. **TEMP** is equivalent to **TEMPORARY**. > \[!TIP]NOTICE > > * Local temporary tables are visible to the current session through the schema starting with **pg\_temp**. Users should not delete schemas starting with **pg\_temp** or **pg\_toast\_temp**. > * If **TEMPORARY** or **TEMP** is not specified when you create a table but its schema is set to that starting with **pg\_temp\_** in the current session, the table will be created as a temporary table. > * If global temporary tables and indexes are being used by other sessions, do not perform **ALTER** or **DROP** (except the **ALTER INDEX index\_name REBUILD** command). > * The DDL of a global temporary table affects only the user data and indexes of the current session. For example, **TRUNCATE**, **REINDEX**, and **ANALYZE** are valid only for the current session. > * You can set the GUC parameter **max\_active\_global\_temporary\_table** to determine whether to enable the global temporary table function. If **max\_active\_global\_temporary\_table** is set to **0**, the global temporary table function is disabled. > * A temporary table is visible only to the current session. Therefore, it cannot be used together with **\parallel on**. > * The temporary table does not support primary/standby switchover. > * The global temporary table does not respond to automatic clearance. In persistent connection scenarios, you are advised to use the global temporary table in the ON COMMIT DELETE ROWS clause or periodically and manually execute the VACUUM statement. Otherwise, Clogs may not be reclaimed. * **IF NOT EXISTS** Sends a notice, but does not throw an error, if a table with the same name exists. * **table\_name** Specifies the name of the table to be created. > \[!TIP]NOTICE > > * Some processing logic of materialized views determines whether a table is the log table of a materialized view or a table associated with a materialized view based on the table name prefix. Therefore, do not create a table whose name prefix is **mlog\_**or **matviewmap\_**. Otherwise, some functions of the table are affected. * **column\_name** Specifies the name of a column to be created in the new table. * **constraint\_name** Specifies the name of the constraint specified during table creation. > \[!TIP]NOTICE > > constraint\_name is optional in B-compatible mode (**sql\_compatibility = 'B'**). For other modes, constraint\_name must be added. * **index\_name** Specifies an index name. > \[!TIP]NOTICE > > * index\_name is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * For foreign key constraints, if constraint\_name and index\_name are specified at the same time, constraint\_name is used as the index name. > * For a unique key constraint, if both constraint\_name and index\_name are specified, index\_name is used as the index name. * **USING method** Specifies the name of the index method to be used. For details about the value range, see [USING method](create_index.md). > \[!TIP]NOTICE > > * The USING method is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * In B-compatible mode, if USING method is not specified, the default index method is btree for ASTORE or ubtree for USTORE. * **ASC | DESC** **ASC** specifies an ascending (default) sort order. **DESC** specifies a descending sort order. > \[!TIP]NOTICE > > ASC|DESC is supported only in B-compatible databases (sql\_compatibility = 'B'). * **expression** > \[!TIP]NOTICE > > Expression indexes are supported only in B-compatible databases (that is, sql\_compatibility = 'B'). * **data\_type** Specifies the data type of the column. * **compress\_mode** Specifies whether to compress a table column. The option specifies the algorithm preferentially used by table columns. Row-store tables do not support compression. Value range: **DELTA**, **PREFIX**, **DICTIONARY**, **NUMSTR**, and **NOCOMPRESS** * **COLLATE collation** Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the **select \* from pg\_collation;** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **LIKE source\_table \[ like\_option ... ]** Specifies a table from which the new table automatically copies all column names, their data types, and their not-null constraints. The new table and the original table are decoupled after creation is complete. Changes to the original table will not be applied to the new table, and it is not possible to include data of the new table in scans of the original table. Columns and constraints copied by **LIKE** are not merged with the same name. If the same name is specified explicitly or in another **LIKE** clause, an error is reported. * The default expressions are copied from the original table to the new table only if **INCLUDING DEFAULTS** is specified. The default behavior is to exclude default expressions, resulting in the copied columns in the new table having default values **NULL**. * The **CHECK** constraints are copied from the original table to the new table only when **INCLUDING CONSTRAINTS** is specified. Other types of constraints are never copied to the new table. Not-null constraints are always copied to the new table. These rules also apply to column constraints and table constraints. * Any indexes on the original table will not be created on the new table, unless the **INCLUDING INDEXES** clause is specified. * **STORAGE** settings for the copied column definitions are copied only if **INCLUDING STORAGE** is specified. The default behavior is to exclude **STORAGE** settings. * If **INCLUDING COMMENTS** is specified, comments for the copied columns, constraints, and indexes are copied. The default behavior is to exclude comments. * If **INCLUDING PARTITION** is specified, the partition definitions of the source table are copied to the new table, and the new table no longer uses the **PARTITION BY** clause. The default behavior is to exclude partition definition of the original table. If the source table has an index, you can use the **INCLUDING PARTITION INCLUDING INDEXES** syntax. If only **INCLUDING INDEXES** is used for a partitioned table, the target table will be defined as an ordinary table, but the index is a partitioned index. In this case, an error will be reported because ordinary tables do not support partitioned indexes. * If **INCLUDING RELOPTIONS** is specified, the new table will copy the storage parameter (that is, **WITH** clause) of the source table. The default behavior is to exclude partition definition of the storage parameter of the original table. * **INCLUDING ALL** contains the meaning of **INCLUDING DEFAULTS**, **INCLUDING CONSTRAINTS**, **INCLUDING INDEXES**, **INCLUDING STORAGE**, **INCLUDING COMMENTS**,**INCLUDING PARTITION**, and **INCLUDING RELOPTIONS**. > \[!TIP]NOTICE > > * If the source table contains a sequence with the **SERIAL**, **BIGSERIAL**, **SMALLSERIAL**, or **LARGESERIAL** data type, or a column in the source table is a sequence by default and the sequence is created for this table by using **CREATE SEQUENCE...** **OWNED BY**, these sequences will not be copied to the new table, and another sequence specific to the new table will be created. This is different from earlier versions. To share a sequence between the source table and new table, create a shared sequence (do not use **OWNED BY**) and set a column in the source table to this sequence. > * You are not advised to set a column in the source table to the sequence specific to another table especially when the table is distributed in specific node groups, because doing so may result in **CREATE TABLE ... LIKE** execution failures. In addition, doing so may cause the sequence to become invalid in the source sequence because the sequence will also be deleted from the source table when it is deleted from the table that the sequence is specific to. To share a sequence among multiple tables, you are advised to create a shared sequence for them. > * **EXCLUDING** of a partitioned table must be used together with **INCLUDING ALL**, for example, **INCLUDING ALL EXCLUDING DEFAULTS**, except for **DEFAULTS** of the source partitioned table. * **AUTO\_INCREMENT \[ = ] value** This clause specifies an initial value for an auto-increment column. The value must be a positive integer and cannot exceed 2127-1. > \[!TIP]NOTICE > > This clause takes effect only when **sql\_compatibility** is set to **B**. * **WITH ( { storage\_parameter = value } \[, ... ] )** Specifies an optional storage parameter for a table or an index. > \[!NOTE]NOTE > > * When using **Numeric** of any precision to define a column, specifies precision **p** and scale **s**.When precision and scale are not specified, the input will be displayed. The description of parameters is as follows: * FILLFACTOR The fill factor of a table is a percentage from 10 to 100.**100** (complete filling) is the default value.When a smaller fill factor is specified, **INSERT** operations pack table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives **UPDATE** a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter has no meaning for column-store tables. Value range: 10–100 * ORIENTATION Specifies the storage mode (row-store or column-store) of table data. This parameter cannot be modified once it is set. Value range: * **ROW** indicates that table data is stored in rows. **ROW** applies to OLTP service and scenarios with a large number of point queries or addition/deletion operations. * **COLUMN** indicates that the data is stored in columns. **COLUMN** applies to the data warehouse service, which has a large amount of aggregation computing, and involves a few column operations. Default value: If an ordinary tablespace is specified, the default is **ROW**. * STORAGE\_TYPE Specifies the storage engine type. This parameter cannot be modified once it is set. Value range: * **USTORE** indicates that tables support the Inplace-Update storage engine. Note that the **track\_counts** and **track\_activities** parameters must be enabled when the Ustore table is used. Otherwise, space expansion may occur. * **ASTORE** indicates that tables support the Append-Only storage engine. Default value: If no table is specified, data is stored in Append-Only mode by default. * INIT\_TD Specifies the number of TDs to be initialized when an Ustore table is created. This parameter is valid only when an Ustore table is created. Value range: 2 to 128. The default value is **4**. * COMPRESSION Specifies the compression level of table data. It determines the compression ratio and time. Generally, the higher the level of compression, the higher the ratio, the longer the time; and the lower the level of compression, the lower the ratio, the shorter the time. The actual compression ratio depends on the distribution mode of table data loaded. By default, **COMPRESSION=NO** is added to row-store tables. Value range: The valid values for column-store tables are **YES**, **NO**, **LOW**, **MIDDLE**, and **HIGH**, and the default value is **LOW**. * COMPRESSLEVEL Specifies the table data compression ratio and duration at the same compression level. This divides a compression level into sublevels, providing more choices for compression ratio and duration. As the value becomes greater, the compression ratio becomes higher and duration longer at the same compression level. Value range: 0 to 3. The default value is **0**. * COMPRESSTYPE Specifies the row-store table compression algorithm. The value **1** indicates the PGLZ algorithm, the value **2** indicates the ZSTD algorithm, the value **3** indicates the PGZSTD algorithm (currently not supported), and the value **4** indicates the ZLIB algorithm. By default, indexes are not compressed. (Only common tables in the Astore engine are supported.) Value range: 0 to 4. The default value is **0**. * COMPRESS\_LEVEL Specifies the row-store table compression algorithm level. This parameter is valid only when **COMPRESSTYPE** is set to **2** or **4**. A higher compression level indicates a better table compression effect and a slower table access speed. (Only common tables in the Astore engine are supported.) Value range: –31 to 31. The default value is **0**. * COMPRESS\_CHUNK\_SIZE Specifies the size of a row-store table compression chunk. A smaller chunk size indicates a better compression effect, and a larger data dispersion degree indicates a slower table access speed. (Only common tables in the Astore engine are supported.) Value range: subject to the page size. When the page size is 8 KB, the value can be **512**, **1024**, **2048**, or **4096**. Default value: **4096** * COMPRESS\_PREALLOC\_CHUNKS Specifies the number of pre-allocated row-store table compression chunks. A larger number of pre-allocated chunks indicates a lower table compression ratio, and a smaller data dispersion degree indicates a better access performance. (Only common tables in the Astore engine are supported.) Value range: 0 to 7. The default value is **0**. * The maximum value of this parameter is **7** when **COMPRESS\_CHUNK\_SIZE** is set to **512** or **1024**. * The maximum value of this parameter is **3** when **COMPRESS\_CHUNK\_SIZE** is set to **2048**. * The maximum value of this parameter is **1** when **COMPRESS\_CHUNK\_SIZE** is set to **4096**. * COMPRESS\_BYTE\_CONVERT Sets the preprocessing of row-store table compression byte conversion. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * COMPRESS\_DIFF\_CONVERT Sets the preprocessing of row-store table compression differentiation. This parameter can be used together only with **COMPRESS\_BYTE\_CONVERT**. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * MAX\_BATCHROW Specifies the maximum number of rows in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000. The default value is **60000**. * PARTIAL\_CLUSTER\_ROWS Specifies the number of records to be partially clustered for storage during data loading. The parameter is only valid for column-store tables. Value range: greater than or equal to **MAX\_BATCHROW**. You are advised to set this parameter to an integer multiple of **MAX\_BATCHROW**. * DELTAROW\_THRESHOLD Specifies the upper limit of to-be-imported rows for triggering the data import to a delta table when data of a column-store table is to be imported. This parameter takes effect only if **enable\_delta\_store** is set to **on**. The parameter is only valid for column-store tables. Value range: 0 to 9999. The default value is **100**. * segment The data is stored in segment-page mode. This parameter supports only row-store tables. Column-store tables, temporary tables, and unlogged tables are not supported. The ustore storage engine is not supported. Value range: **on** and **off** Default value: **off** * dek\_cipher Ciphertext of the key used for transparent data encryption. When **enable\_tde** is enabled, the system automatically applies for ciphertext creation. You cannot specify the ciphertext. The key rotation function can be used to update the key. Value range: a string. If encryption is disabled, the default value is null by default. * hasuids If this parameter is set to **on**, a unique table-level ID is allocated to a tuple when the tuple is updated. Value range: **on** and **off** Default value: **off** * **ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }** **ON COMMIT** determines what to do when you commit a temporary table creation operation. The three options are as follows. Currently, only **PRESERVE ROWS** and **DELETE ROWS** can be used. * **PRESERVE ROWS** (default): No special action is taken at the ends of transactions. The temporary table and its table data are unchanged. * **DELETE ROWS**: All rows in the temporary table will be deleted at the end of each transaction block. * **DROP**: The temporary table will be dropped at the end of the current transaction block. Only local temporary tables can be dropped. Global temporary tables cannot be dropped. * **COMPRESS | NOCOMPRESS** If you specify **COMPRESS** in the **CREATE TABLE** statement, the compression feature is triggered in case of a bulk **INSERT** operation. If this feature is enabled, a scan is performed for all tuple data within the page to generate a dictionary and then the tuple data is compressed and stored. If **NOCOMPRESS** is specified, the table is not compressed. Row-store tables do not support compression. Default value: **NOCOMPRESS**, that is, tuple data is not compressed before storage. * **TABLESPACE tablespace\_name** Specifies the tablespace where the new table is created. If not specified, the default tablespace is used. * **COMMNET {=| } text** Comments a new table. If this parameter is not specified, no comment is created. * **CONSTRAINT constraint\_name** Specifies the name of a column or table constraint. The optional constraint clauses specify constraints that new or updated rows must satisfy for an insert or update operation to succeed. There are two ways to define constraints: * A column constraint is defined as part of a column definition, and it is bound to a particular column. * A table constraint is not bound to a particular column but can apply to more than one column. * **NOT NULL** The column is not allowed to contain null values. * **NULL** The column is allowed to contain null values. This is the default setting. This clause is only provided for compatibility with non-standard SQL databases. It is not recommended. * **CHECK ( expression )** Specifies an expression producing a Boolean result where the insert or update operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A check constraint specified as a column constraint should reference only the column's values, while an expression appearing in a table constraint can reference multiple columns. > \[!NOTE]NOTE > > **<>NULL** and **!=NULL** are invalid in an expression. Change them to **IS NOT NULL**. * **DEFAULT default\_expr** Assigns a default data value for a column. The value can be any variable-free expressions. (Subqueries and cross-references to other columns in the current table are not allowed.) The data type of the default expression must match the data type of the column. The default expression will be used in any insert operation that does not specify a value for the column. If there is no default value for a column, then the default value is null. * **AUTO\_INCREMENT** Specifies an auto-increment column. If the value of this column is not specified (or the value of this column is set to **0**, **NULL**, or **DEFAULT**), the value of this column is automatically increased by the auto-increment counter. If this column is inserted or updated to a value greater than the current auto-increment counter, the auto-increment counter is updated to this value after the command is executed successfully. The initial auto-increment value is set by the AUTO\_INCREMENT \[ = ] value clause. If it is not set, the default value **1** is used. > \[!NOTE]NOTE > > * The auto-increment column can be specified only when **sql\_compatibility** is set to **B**. > * The data type of the auto-increment column can only be integer, 4-byte or 8-byte floating point, or Boolean. > * Each table can have only one auto-increment column. > * The auto-increment column must be the first column of a primary key constraint or unique constraint. > * The DEFAULT value cannot be specified for an auto-increment column. > \>- The expression of the CHECK constraint cannot contain auto-increment columns. > * You can specify that the auto-increment column can be NULL. If it is not specified, the auto-increment column contains the NOT NULL constraint by default. > * When a table containing an auto-increment column is created, a sequence that depends on the column is created as an auto-increment counter. You are not allowed to modify or delete the sequence using sequence-related functions. You can view the value of the sequence. > * Sequences are not created for auto-increment columns in local temporary tables. > * Auto-increment columns do not support column store. > * The auto-increment and refresh operations of the auto-increment counter are not rolled back. * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** Specifies that a group of one or more columns of a table can contain only unique values. For the purpose of a unique constraint, null is not considered equal. * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** Specifies that a column or columns of a table can contain only unique (non-duplicate) and non-null values. Only one primary key can be specified for a table. * **REFERENCES reftable \[ ( refcolum ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (column constraint)** **FOREIGN KEY ( column\_name \[, ... ] ) REFERENCES reftable \[ ( refcolumn \[, ... ] ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (table constraint)** The foreign key constraint requires that the group consisting of one or more columns in the new table should contain and match only the referenced column values in the referenced table. If **refcolum** is omitted, the primary key of **reftable** is used. The referenced column should be the only column or primary key in the referenced table. A foreign key constraint cannot be defined between a temporary table and a permanent table. There are three types of matching between a reference column and a referenced column: * **MATCH FULL**: A column with multiple foreign keys cannot be **NULL** unless all foreign key columns are **NULL**. * **MATCH SIMPLE** (default): Any unexpected foreign key column can be **NULL**. * **MATCH PARTIAL**: This option is not supported currently. In addition, when certain operations are performed on the data in the referenced table, the operations are performed on the corresponding columns in the new table. **ON DELETE**: specifies the operations to be executed after a referenced row in the referenced table is deleted. **ON UPDATE**: specifies the operation to be performed when the referenced column data in the referenced table is updated. Possible responses to the **ON DELETE** and **ON UPDATE** clauses are as follows: * **NO ACTION** (default): An error indicating that the foreign key constraint is violated is reported. If the constraint is deferrable and there are still any referenced columns, this error will occur when the constraint is checked. * **RESTRICT**: An error indicating that the foreign key constraint is violated is created. It is the same as **NO ACTION** except that the constraint is not deferrable. * **CASCADE**: deletes any rows referencing the deleted row, or update the value of the referencing column to the new value of the referenced column, respectively. * **SET NULL**: sets the referencing column(s) to **NULL**. * **SET DEFAULT**: sets the referencing column(s) to their default values. * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(default): Enable constraints, create indexes, and enforce constraints on both existing data and newly added data. * ENABLE NOVALIDATE: Enable constraints and create indexes. For CHECK constraints, the constraints are only enforced for newly added data, regardless of the existing data in the table. For UNIQUE and PRIMARY KEY, indexes need to be established, so the constraints will be enforced for the existing data. * DISABLE( NOVALIDATE)(default): Disable constraints, delete indexes, and operations such as modifying the data of the constraint columns can be performed. * DISABLE VALIDATE: Disable constraints and delete indexes. Insertion, update and deletion operations on the table cannot be performed. * **DEFERRABLE | NOT DEFERRABLE** Controls whether the constraint can be deferred. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable can be postponed until the end of the transaction using the **SET CONSTRAINTS** command. **NOT DEFERRABLE** is the default value. Currently, only UNIQUE constraints, primary key constraints, and foreign key constraints accept this clause. All the other constraints are not deferrable. > \[!NOTE]NOTE > > Ustore tables do not support the keywords **DEFERRABLE** and **INITIALLY DEFERRED**. * **COMMENT text** Comments. * **PARTIAL CLUSTER KEY** Specifies a partial cluster key for storage. When importing data to a column-store table, you can perform local data sorting by specified columns (single or multiple). * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** If a constraint is deferrable, this clause specifies the default time to check the constraint. * If the constraint is **INITIALLY IMMEDIATE** (default value), it is checked after each statement. * If the constraint is **INITIALLY DEFERRED**, it is checked only at the end of the transaction. The constraint check time can be altered using the **SET CONSTRAINTS** statement. * **USING INDEX TABLESPACE tablespace\_name** Allows selection of the tablespace in which the index associated with a **UNIQUE** or **PRIMARY KEY** constraint will be created. If not specified, **default\_tablespace** is consulted, or the default tablespace in the database if **default\_tablespace** is empty. * **ENCRYPTION\_TYPE = encryption\_type\_value** For the encryption type in the ENCRYPTED WITH constraint, the value of **encryption\_type\_value** is **DETERMINISTIC** or **RANDOMIZED**. ## Examples ``` -- Create a simple table. openGauss=# CREATE TABLE tpcds.warehouse_t1 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); openGauss=# CREATE TABLE tpcds.warehouse_t2 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60), W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` ``` -- Create a table and set the default value of the W_STATE column to GA. openGauss=# CREATE TABLE tpcds.warehouse_t3 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) DEFAULT 'GA', W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a table and check whether the W_WAREHOUSE_NAME column is unique at the end of its creation. openGauss=# CREATE TABLE tpcds.warehouse_t4 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE DEFERRABLE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` ``` -- Create a table with its fill factor set to 70%. openGauss=# CREATE TABLE tpcds.warehouse_t5 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), UNIQUE(W_WAREHOUSE_NAME) WITH(fillfactor=70) ); -- Alternatively, user the following syntax: openGauss=# CREATE TABLE tpcds.warehouse_t6 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH(fillfactor=70); -- Create a table and specify that its data is not written to WALs. openGauss=# CREATE UNLOGGED TABLE tpcds.warehouse_t7 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a temporary table. openGauss=# CREATE TEMPORARY TABLE warehouse_t24 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a local temporary table and specify that this table is dropped when the transaction is committed. openGauss=# CREATE TEMPORARY TABLE warehouse_t25 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) ON COMMIT DELETE ROWS; --Create a global temporary table and specify that the temporary table data is deleted when the session ends. The current Ustore storage engine does not support global temporary tables. openGauss=# CREATE GLOBAL TEMPORARY TABLE gtt1 ( ID INTEGER NOT NULL, NAME CHAR(16) NOT NULL, ADDRESS VARCHAR(50) , POSTCODE CHAR(6) ) ON COMMIT PRESERVE ROWS; -- Create a table and specify that no error is reported for duplicate tables (if any). openGauss=# CREATE TABLE IF NOT EXISTS tpcds.warehouse_t8 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a general tablespace. openGauss=# CREATE TABLESPACE DS_TABLESPACE1 RELATIVE LOCATION 'tablespace/tablespace_1'; -- Specify a tablespace when creating a table. openGauss=# CREATE TABLE tpcds.warehouse_t9 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) TABLESPACE DS_TABLESPACE1; -- Separately specify the index tablespace for W_WAREHOUSE_NAME when creating the table. openGauss=# CREATE TABLE tpcds.warehouse_t10 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE USING INDEX TABLESPACE DS_TABLESPACE1, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` ``` -- Create a table with a primary key constraint. openGauss=# CREATE TABLE tpcds.warehouse_t11 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- An alternative for the preceding syntax is as follows: openGauss=# CREATE TABLE tpcds.warehouse_t12 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), PRIMARY KEY(W_WAREHOUSE_SK) ); -- Or use the following statement to specify the name of the constraint: openGauss=# CREATE TABLE tpcds.warehouse_t13 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CSTR_KEY1 PRIMARY KEY(W_WAREHOUSE_SK) ); -- Create a table with a compound primary key constraint. openGauss=# CREATE TABLE tpcds.warehouse_t14 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CSTR_KEY2 PRIMARY KEY(W_WAREHOUSE_SK, W_WAREHOUSE_ID) ); -- Create a column-store table. openGauss=# CREATE TABLE tpcds.warehouse_t15 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH (ORIENTATION = COLUMN); -- Create a column-store table using partial clustered storage. openGauss=# CREATE TABLE tpcds.warehouse_t16 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), PARTIAL CLUSTER KEY(W_WAREHOUSE_SK, W_WAREHOUSE_ID) ) WITH (ORIENTATION = COLUMN); -- Define a column-store table with compression enabled. openGauss=# CREATE TABLE tpcds.warehouse_t17 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH (ORIENTATION = COLUMN, COMPRESSION=HIGH); -- Define a column check constraint. openGauss=# CREATE TABLE tpcds.warehouse_t19 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY CHECK (W_WAREHOUSE_SK > 0), W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) CHECK (W_WAREHOUSE_NAME IS NOT NULL), W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); openGauss=# CREATE TABLE tpcds.warehouse_t20 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) CHECK (W_WAREHOUSE_NAME IS NOT NULL), W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CONSTR_KEY2 CHECK(W_WAREHOUSE_SK > 0 AND W_WAREHOUSE_NAME IS NOT NULL) ); -- Create a table with a foreign key constraint. openGauss=# CREATE TABLE tpcds.city_t23 ( W_CITY VARCHAR(60) PRIMARY KEY, W_ADDRESS TEXT ); openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) REFERENCES tpcds.city_t23(W_CITY), W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- An alternative for the preceding syntax is as follows: openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , FOREIGN KEY(W_CITY) REFERENCES tpcds.city_t23(W_CITY) ); -- Or use the following statement to specify the name of the constraint: openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , CONSTRAINT W_FORE_KEY1 FOREIGN KEY(W_CITY) REFERENCES tpcds.city_t23(W_CITY) ); -- Add a varchar column to the tpcds.warehouse_t19 table. ``` ``` openGauss=# ALTER TABLE tpcds.warehouse_t19 ADD W_GOODS_CATEGORY varchar(30); -- Add a check constraint to the tpcds.warehouse_t19 table. openGauss=# ALTER TABLE tpcds.warehouse_t19 ADD CONSTRAINT W_CONSTR_KEY4 CHECK (W_STATE IS NOT NULL); -- Use one statement to alter the types of two existing columns. openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY TYPE varchar(80), ALTER COLUMN W_STREET_NAME TYPE varchar(100); -- This statement is equivalent to the preceding statement. openGauss=# ALTER TABLE tpcds.warehouse_t19 MODIFY (W_GOODS_CATEGORY varchar(30), W_STREET_NAME varchar(60)); -- Add a not-null constraint to an existing column. openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY SET NOT NULL; -- Remove not-null constraints from an existing column. openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY DROP NOT NULL; -- If no partial cluster is specified in a column-store table, add a partial cluster to the table. openGauss=# ALTER TABLE tpcds.warehouse_t17 ADD PARTIAL CLUSTER KEY(W_WAREHOUSE_SK); -- View the constraint name and delete the partial cluster column of a column-store table. openGauss=# \d+ tpcds.warehouse_t17 Table "tpcds.warehouse_t17" Column | Type | Modifiers | Storage | Stats target | Description -------------------+-----------------------+-----------+----------+--------------+------------- w_warehouse_sk | integer | not null | plain | | w_warehouse_id | character(16) | not null | extended | | w_warehouse_name | character varying(20) | | extended | | w_warehouse_sq_ft | integer | | plain | | w_street_number | character(10) | | extended | | w_street_name | character varying(60) | | extended | | w_street_type | character(15) | | extended | | w_suite_number | character(10) | | extended | | w_city | character varying(60) | | extended | | w_county | character varying(30) | | extended | | w_state | character(2) | | extended | | w_zip | character(10) | | extended | | w_country | character varying(20) | | extended | | w_gmt_offset | numeric(5,2) | | main | | Partial Cluster : "warehouse_t17_cluster" PARTIAL CLUSTER KEY (w_warehouse_sk) Has OIDs: no Location Nodes: ALL DATANODES Options: compression=no, version=0.12 openGauss=# ALTER TABLE tpcds.warehouse_t17 DROP CONSTRAINT warehouse_t17_cluster; -- Move a table to another tablespace. openGauss=# ALTER TABLE tpcds.warehouse_t19 SET TABLESPACE PG_DEFAULT; -- Create the joe schema. openGauss=# CREATE SCHEMA joe; -- Move a table to another schema. openGauss=# ALTER TABLE tpcds.warehouse_t19 SET SCHEMA joe; -- Rename an existing table. openGauss=# ALTER TABLE joe.warehouse_t19 RENAME TO warehouse_t23; -- Delete a column from the warehouse_t23 table. openGauss=# ALTER TABLE joe.warehouse_t23 DROP COLUMN W_STREET_NAME; -- Delete the tablespace, schema joe, and schema tables warehouse. openGauss=# DROP TABLE tpcds.warehouse_t1; openGauss=# DROP TABLE tpcds.warehouse_t2; openGauss=# DROP TABLE tpcds.warehouse_t3; openGauss=# DROP TABLE tpcds.warehouse_t4; openGauss=# DROP TABLE tpcds.warehouse_t5; openGauss=# DROP TABLE tpcds.warehouse_t6; openGauss=# DROP TABLE tpcds.warehouse_t7; openGauss=# DROP TABLE tpcds.warehouse_t8; openGauss=# DROP TABLE tpcds.warehouse_t9; openGauss=# DROP TABLE tpcds.warehouse_t10; openGauss=# DROP TABLE tpcds.warehouse_t11; openGauss=# DROP TABLE tpcds.warehouse_t12; openGauss=# DROP TABLE tpcds.warehouse_t13; openGauss=# DROP TABLE tpcds.warehouse_t14; openGauss=# DROP TABLE tpcds.warehouse_t15; openGauss=# DROP TABLE tpcds.warehouse_t16; openGauss=# DROP TABLE tpcds.warehouse_t17; openGauss=# DROP TABLE tpcds.warehouse_t18; openGauss=# DROP TABLE tpcds.warehouse_t20; openGauss=# DROP TABLE tpcds.warehouse_t21; openGauss=# DROP TABLE tpcds.warehouse_t22; openGauss=# DROP TABLE joe.warehouse_t23; openGauss=# DROP TABLE tpcds.warehouse_t24; openGauss=# DROP TABLE tpcds.warehouse_t25; openGauss=# DROP TABLESPACE DS_TABLESPACE1; openGauss=# DROP SCHEMA IF EXISTS joe CASCADE; ``` ## Helpful Links [ALTER TABLE](alter_table.md), [DROP TABLE](drop_table.md), and [CREATE TABLESPACE](create_tablespace.md) ## Suggestions * UNLOGGED * The unlogged table and its indexes do not use the WAL log mechanism during data writing. Their write speed is much higher than that of ordinary tables. Therefore, they can be used for storing intermediate result sets of complex queries to improve query performance. * The unlogged table has no primary/standby mechanism. In case of system faults or abnormal breakpoints, data loss may occur. Therefore, the unlogged table cannot be used to store basic data. * TEMPORARY | TEMP * A temporary table is automatically dropped at the end of a session. * LIKE * The new table automatically inherits all column names, data types, and not-null constraints from this table. The new table is irrelevant to the original table after the creation. * LIKE INCLUDING DEFAULTS * The default expressions are copied from the original table to the new table only if **INCLUDING DEFAULTS** is specified. The default behavior is to exclude default expressions, resulting in the copied columns in the new table having default values **NULL**. * LIKE INCLUDING CONSTRAINTS * The **CHECK** constraints are copied from the original table to the new table only when **INCLUDING CONSTRAINTS** is specified. Other types of constraints are never copied to the new table. Not-null constraints are always copied to the new table. These rules also apply to column constraints and table constraints. * LIKE INCLUDING INDEXES * Any indexes on the original table will not be created on the new table, unless the **INCLUDING INDEXES** clause is specified. * LIKE INCLUDING STORAGE * **STORAGE** settings for the copied column definitions are copied only if **INCLUDING STORAGE** is specified. The default behavior is to exclude **STORAGE** settings. * LIKE INCLUDING COMMENTS * If **INCLUDING COMMENTS** is specified, comments for the copied columns, constraints, and indexes are copied. The default behavior is to exclude comments. * LIKE INCLUDING PARTITION * If **INCLUDING PARTITION** is specified, the partition definitions of the source table are copied to the new table, and the new table no longer uses the **PARTITION BY** clause. The default behavior is to exclude partition definition of the original table. > \[!TIP]NOTICE > > List and hash partitioned tables do not support **LIKE INCLUDING PARTITION**. * LIKE INCLUDING RELOPTIONS * If **INCLUDING RELOPTIONS** is specified, the new table will copy the storage parameter (that is, **WITH** clause) of the source table. The default behavior is to exclude partition definition of the storage parameter of the original table. * LIKE INCLUDING ALL * **INCLUDING ALL** contains the meaning of **INCLUDING DEFAULTS**, **INCLUDING CONSTRAINTS**, **INCLUDING INDEXES**, **INCLUDING STORAGE**, **INCLUDING COMMENTS**, **INCLUDING PARTITION**, and **INCLUDING RELOPTIONS**. * ORIENTATION ROW * Creates a row-store table. Row-store applies to the OLTP service, which has many interactive transactions. An interaction involves many columns in the table. Using row-store can improve the efficiency. * ORIENTATION COLUMN * Creates a column-store table. Column-store applies to the DWS, which has a large amount of aggregation computing, and involves a few column operations. --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-create-table.md --- # CREATE TABLE ## Function Creates an empty table in the current database. The table will be owned by the creator. ## Precautions * This section describes only the new syntax of Dolphin. The original syntax of openGauss is not deleted or modified. ## Syntax Create a table using LIKE. ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name LIKE source_table [ like_option [...] ] ``` Create a table. ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | table_indexclause | LIKE source_table [ like_option [...] ] } [, ... ]) [ AUTO_INCREMENT [ = ] value ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMMENT {=| } 'text' ]; [ create_option ] Where create\_option is: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMPRESSION [=] compression_arg ] [ ENGINE [=] engine_name ] [ COLLATE [=] collation_name ] [ [DEFAULT] { CHARSET | CHARACTER SET } [=] charset_name ] [ ROW_FORMAT [=] row_format_name ] In addition to the WITH option, you can enter the same create\_option for multiple times. The latest input prevails. ``` * table\_indexclause: ``` {INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option]... ``` This syntax does not support CREATE FOREIGN TABLE (such as MOT). * Values of index\_type are as follows: ``` USING {BTREE | HASH | GIN | GIST | PSORT | UBTREE} ``` * Values of key\_part are as follows: ``` {col_name[(length)] | (expr)} [ASC | DESC] ``` **length** indicates the prefix index. * The index\_option parameter is as follows: ``` index_option:{ COMMENT 'string' | index_type } ``` The sequence and quantity of COMMENT and index\_type can be random, but only the last value of the same column takes effect. * The like\_option is as follows: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | PARTITION | RELOPTIONS | ALL } ``` ## Parameter Description * **data\_type** Specifies the data type of the column. For the enumeration type ENUM and character types such as CHAR, CHARACTER, VARCHAR, TEXT, you can use the keyword CHARSET or CHARACTER SET to specify the column character set when creating a table. Currently, it is used only for syntax and has no actual purpose. * **column\_constraint** The ON UPDATE feature of MySQL is added to the column type constraint. The constraint is of the same type as the DEFAULT attribute. The ON UPDATE attribute is used to automatically update the timestamp column when the timestamp column of the UPDATE operation is set to the default value. ```sql CREATE TABLE table_name(column_name timestamp ON UPDATE CURRENT_TIMESTAMP); ``` * **COLLATE collation** Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the **select \* from pg\_collation** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. If a collation is not supported, the database issues a warning and sets the column as the default collation. * **{ \[DEFAULT] CHARSET | CHARACTER SET } \[=] charset\_name** Selects the character set used by the table. Currently, it is used only for syntax and has no actual purpose. * **COLLATE \[=] collation\_name** Selects the collation used by a table. Currently, it is used only for syntax and has no actual purpose. * **ROW\_FORMAT \[=] row\_format\_name** Selects the row-store format used by a table. Currently, it is used only for syntax and has no actual purpose. ## Examples ``` --Create an index on a table. openGauss=# CREATE TABLE tpcds.warehouse_t24 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , key (W_WAREHOUSE_SK) , index idx_ID using btree (W_WAREHOUSE_ID) ); --Create composite indexes, expression indexes, and function indexes on tables. openGauss=# CREATE TABLE tpcds.warehouse_t25 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , key using btree (W_WAREHOUSE_SK, W_WAREHOUSE_ID desc) , index idx_SQ_FT using btree ((abs(W_WAREHOUSE_SQ_FT))) , key idx_SK using btree ((abs(W_WAREHOUSE_SK)+1)) ); --The index\_option column is included. openGauss=# create table test_option(a int, index idx_op using btree(a) comment 'idx comment'); ``` ``` --Specify the character set for the column when creating a table. openGauss=# CREATE TABLE t_column_charset(c text CHARSET test_charset); WARNING: character set "test_charset" for type text is not supported yet. default value set CREATE TABLE --Specify the character order for the table when creating the table. openGauss=# CREATE TABLE t_table_collate(c text) COLLATE test_collation; WARNING: COLLATE for TABLE is not supported for current version. skipped CREATE TABLE --Specify the character set for the table when creating the table. openGauss=# CREATE TABLE t_table_charset(c text) CHARSET test_charset; WARNING: CHARSET for TABLE is not supported for current version. skipped CREATE TABLE --Specify the row record format for the table when creating the table. openGauss=# CREATE TABLE t_row_format(c text) ROW_FORMAT test_row_format; WARNING: ROW_FORMAT for TABLE is not supported for current version. skipped CREATE TABLE ``` --- --- url: /en/docs/latest/sql_reference/create_table.md --- # CREATE TABLE ## Function **CREATE TABLE** creates an initially empty table in the current database. The table will be owned by the creator. ## Precautions * For details about the data types supported by column-store tables, see [Data Types Supported by Column-store Tables](data_types_supported_by_column_store_tables.md). * Column-store tables do not support the array. * Column-store tables do not support column generation. * Column-store tables cannot be created as global temporary tables. * It is recommended that the number of column-store tables do not exceed 1000. * If an error occurs during table creation, after it is fixed, the system may fail to delete the empty disk files created before the last automatic clearance. This problem seldom occurs and does not affect system running of the database. * Only **PARTIAL CLUSTER KEY**, **UNIQUE**, and **PRIAMRY KEY** can be used as the table-level constraint of column-store tables. Table-level foreign key constraints are not supported. * Only the **NULL**, **NOT NULL**, **DEFAULT** constant values, **UNIQUE**, and **PRIMARY KEY** can be used as column-store table constraints. * Whether column-store tables support a delta table is specified by the enable\_delta\_store parameter. The threshold for storing data into a delta table is specified by the **deltarow\_threshold** parameter. * When JDBC is used, the **DEFAULT** value can be set through **PrepareStatement**. * The maximum number of columns on each table is 1600, which depends on the column type. The total size of all columns cannot exceed 8192 bytes, except for the columns of variable data types, such as text, varchar, and char. * A user granted with the **CREATE ANY TABLE** permission can create tables in the public and user schemas. To create a table that contains serial columns, you must also grant the **CREATE ANY SEQUENCE** permission to create sequences. ## Syntax Create a table. ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ]) [ AUTO_INCREMENT [ = ] value ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMMENT {=| } 'text' ]; ``` * **column\_constraint** is as follows: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * **compress\_mode** of a column is as follows: ``` { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } ``` * **table\_constraint** is as follows: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { { column_name | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * **like\_option** is as follows: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | PARTITION | RELOPTIONS | ALL } ``` * **index\_parameters** is as follows: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## Parameter Description * **UNLOGGED** If this keyword is specified, the created table is an unlogged table. Data written to unlogged tables is not written to the WALs, which makes them considerably faster than ordinary tables. However, an unlogged table is automatically truncated after conflicts, operating system restart, database restart, primary/standby switchover, power-off, or abnormal shutdown, incurring data loss risks. Contents of an unlogged table are also not replicated to standby servers. Any indexes created on an unlogged table are not automatically logged as well. Usage scenario: Unlogged tables do not ensure data security. Users can back up data before using unlogged tables; for example, users should back up the data before a system upgrade. Troubleshooting: If data is missing in the indexes of unlogged tables due to some unexpected operations such as an unclean shutdown, users should re-create the indexes with errors. * **GLOBAL | LOCAL** When creating a temporary table, you can specify the **GLOBAL** or **LOCAL** keyword before **TEMP** or **TEMPORARY**. If the keyword **GLOBAL** is specified, openGauss creates a global temporary table. Otherwise, openGauss creates a local temporary table. * **TEMPORARY | TEMP** If **TEMP** or **TEMPORARY** is specified, the created table is a temporary table. Temporary tables are classified into global temporary tables and local temporary tables. If the keyword **GLOBAL** is specified when a temporary table is created, the table is a global temporary table. Otherwise, the table is a local temporary table. The metadata of the global temporary table is visible to all sessions. After the sessions end, the metadata still exists. The user data, indexes, and statistics of a session are isolated from those of another session. Each session can only view and modify the data submitted by itself. Global temporary tables have two schemas: **ON COMMIT PRESERVE ROWS** and **ON COMMIT PRESERVE ROWS**. In session-based **ON COMMIT PRESERVE ROWS** schema, user data is automatically cleared when a session ends. In transaction-based **ON COMMIT DELETE ROWS** schema, user data is automatically cleared when the commit or rollback operation is performed. If the **ON COMMIT** option is not specified during table creation, the session level is used by default. Different from local temporary tables, you can specify a schema that does not start with **pg\_temp\_** when creating a global temporary table. A local temporary table is automatically dropped at the end of the current session. Therefore, you can create and use temporary tables in the current session as long as the connected database node in the session is normal. Temporary tables are created only in the current session. If a DDL statement involves operations on temporary tables, a DDL error will be generated. Therefore, you are not advised to perform operations on temporary tables in DDL statements. **TEMP** is equivalent to **TEMPORARY**. > \[!TIP]NOTICE > > * Local temporary tables are visible to the current session through the schema starting with **pg\_temp**. Users should not delete schemas starting with **pg\_temp** or **pg\_toast\_temp**. > * If **TEMPORARY** or **TEMP** is not specified when you create a table but its schema is set to that starting with **pg\_temp\_** in the current session, the table will be created as a temporary table. > * If global temporary tables and indexes are being used by other sessions, do not perform **ALTER** or **DROP** (except the **ALTER INDEX index\_name REBUILD** command). > * The DDL of a global temporary table affects only the user data and indexes of the current session. For example, **TRUNCATE**, **REINDEX**, and **ANALYZE** are valid only for the current session. > * You can set the GUC parameter **max\_active\_global\_temporary\_table** to determine whether to enable the global temporary table function. If **max\_active\_global\_temporary\_table** is set to **0**, the global temporary table function is disabled. > * A temporary table is visible only to the current session. Therefore, it cannot be used together with **\parallel on**. > * The temporary table does not support primary/standby switchover. > * The global temporary table does not respond to automatic clearance. In persistent connection scenarios, you are advised to use the global temporary table in the ON COMMIT DELETE ROWS clause or periodically and manually execute the VACUUM statement. Otherwise, Clogs may not be reclaimed. * **IF NOT EXISTS** Sends a notice, but does not throw an error, if a table with the same name exists. * **table\_name** Specifies the name of the table to be created. > \[!TIP]NOTICE > Some processing logic of materialized views determines whether a table is the log table of a materialized view or a table associated with a materialized view based on the table name prefix. Therefore, do not create a table whose name prefix is **mlog\_** or **matviewmap\_**. Otherwise, some functions of the table are affected. * **column\_name** Specifies the name of a column to be created in the new table. * **constraint\_name** Specifies the name of the constraint specified during table creation. > \[!TIP]NOTICE > constraint\_name is optional in B-compatible mode (**sql\_compatibility = 'B'**). For other modes, constraint\_name must be added. * **index\_name** Specifies an index name. > \[!TIP]NOTICE > > * index\_name is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * For foreign key constraints, if constraint\_name and index\_name are specified at the same time, constraint\_name is used as the index name. > * For a unique key constraint, if both constraint\_name and index\_name are specified, index\_name is used as the index name. * **USING method** Specifies the name of the index method to be used. For details about the value range, see [USING method](create_index.md). > \[!TIP]NOTICE > > * The USING method is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * In B-compatible mode, if USING method is not specified, the default index method is btree for ASTORE or ubtree for USTORE. * **ASC | DESC** **ASC** specifies an ascending (default) sort order. **DESC** specifies a descending sort order. > \[!TIP]NOTICE > ASC|DESC is supported only in B-compatible databases (sql\_compatibility = 'B'). * **expression** Specifies an expression index constraint created based on one or more columns of the table. The expression index must be written with surrounding parentheses. > \[!TIP]NOTICE > Expression indexes are supported only in B-compatible databases (that is, sql\_compatibility = 'B'). * **data\_type** Specifies the data type of the column. * **compress\_mode** Specifies whether to compress a table column. The option specifies the algorithm preferentially used by table columns. Row-store tables do not support compression. Value range: **DELTA**, **PREFIX**, **DICTIONARY**, **NUMSTR**, and **NOCOMPRESS** * **COLLATE collation** Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the **select \* from pg\_collation;** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **LIKE source\_table \[ like\_option ... ]** Specifies a table from which the new table automatically copies all column names, their data types, and their not-null constraints. The new table and the original table are decoupled after creation is complete. Changes to the original table will not be applied to the new table, and it is not possible to include data of the new table in scans of the original table. Columns and constraints copied by **LIKE** are not merged with the same name. If the same name is specified explicitly or in another **LIKE** clause, an error is reported. * The default expressions are copied from the original table to the new table only if **INCLUDING DEFAULTS** is specified. The default behavior is to exclude default expressions, resulting in the copied columns in the new table having default values **NULL**. * The **CHECK** constraints are copied from the original table to the new table only when **INCLUDING CONSTRAINTS** is specified. Other types of constraints are never copied to the new table. Not-null constraints are always copied to the new table. These rules also apply to column constraints and table constraints. * By default, indexes of the source table are created on the new table and does not affect the **INCLUDING INDEXES** clause. If you do not want to copy the indexes of the source table, you need to specify the **EXCLUDING INDEXES** clause. * **STORAGE** settings for the copied column definitions are copied only if **INCLUDING STORAGE** is specified. The default behavior is to exclude **STORAGE** settings. * If **INCLUDING COMMENTS** is specified, comments for the copied columns, constraints, and indexes are copied. The default behavior is to exclude comments. * If the source table is a partitioned table, the partition definition of the source table is copied to the new table by default. In addition, the **PRTITION BY** clause cannot be used in the new table, and the **INCLUDING PARTITION** clause can be specified. If you do not want to copy partition information, you need to specify the **EXCLUDING PARTITION** clause. An error is reported if the source partitioned table has indexes, only **EXCLUDING PARTITION** is used, the target table is defined as an ordinary table, and the partitioned indexes of the source table is copied by default. The reason is that ordinary tables do not support partitioned indexes. * If **INCLUDING RELOPTIONS** is specified, the new table will copy the storage parameter (that is, **WITH** clause) of the source table. The default behavior is to exclude partition definition of the storage parameter of the original table. * **INCLUDING ALL** contains the meaning of **INCLUDING DEFAULTS**, **INCLUDING CONSTRAINTS**, **INCLUDING INDEXES**, **INCLUDING STORAGE**, **INCLUDING COMMENTS**,**INCLUDING PARTITION**, and **INCLUDING RELOPTIONS**. > \[!TIP]NOTICE > > * If the source table contains a sequence with the **SERIAL**, **BIGSERIAL**, **SMALLSERIAL** or **LARGESERIAL** data type, or a column in the source table is a sequence by default and the sequence is created for this table by using **CREATE SEQUENCE...** **OWNED BY**, these sequences will not be copied to the new table, and another sequence specific to the new table will be created. This is different from earlier versions. To share a sequence between the source table and new table, create a shared sequence (do not use **OWNED BY**) and set a column in the source table to this sequence. > > * You are not advised to set a column in the source table to the sequence specific to another table especially when the table is distributed in specific node groups, because doing so may result in **CREATE TABLE ... LIKE** execution failures. In addition, doing so may cause the sequence to become invalid in the source sequence because the sequence will also be deleted from the source table when it is deleted from the table that the sequence is specific to. To share a sequence among multiple tables, you are advised to create a shared sequence for them. > > * **EXCLUDING** of a partitioned table must be used together with **INCLUDING ALL**, for example, **INCLUDING ALL EXCLUDING DEFAULTS**, except for **DEFAULTS** of the source partitioned table. > > * If the source table is a local temporary table, the new table must also be a local temporary table. Otherwise, an error is reported. > > * An error is reported if CREATE TABLE ... LIKE is executed to copy hash or list partitions of the source table by default. The hash or list partitions cannot be copied. Only range partitions can be copied. In this case, you need to manually run EXCLUDING PARITITION. For level-2 partitioned tables, only level-2 range-range partitions can be copied. * **WITH ( { storage\_parameter = value } \[, ... ] )** Specifies an optional storage parameter for a table or an index. > \[!NOTE]NOTE > When using **Numeric** of any precision to define a column, specifies precision **p** and scale **s**. When precision and scale are not specified, the input will be displayed. The description of parameters is as follows: * FILLFACTOR The fill factor of a table is a percentage from 10 to 100. **100** (complete filling) is the default value. When a smaller fill factor is specified, **INSERT** operations pack table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives **UPDATE** a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter has no meaning for column-store tables. Value range: 10–100 * ORIENTATION Specifies the storage mode (row-store or column-store) of table data. This parameter cannot be modified once it is set. Value range: * **ROW** indicates that table data is stored in rows. **ROW** applies to OLTP service and scenarios with a large number of point queries or addition/deletion operations. * **COLUMN** indicates that the data is stored in columns. **COLUMN** applies to the data warehouse service, which has a large amount of aggregation computing, and involves a few column operations. Default value: If an ordinary tablespace is specified, the default is **ROW**. * STORAGE\_TYPE Specifies the storage engine type. This parameter cannot be modified once it is set. Value range: * **USTORE** indicates that tables support the inplace-update storage engine. Note that the **track\_counts** and **track\_activities** parameters must be enabled when the Ustore table is used. Otherwise, space expansion may occur. * **ASTORE** indicates that tables support the append-only storage engine. Default value: If no table is specified, data is stored in append-only mode by default. * INIT\_TD Specifies the number of TDs to be initialized when an Ustore table is created. This parameter is valid only when an Ustore table is created. Value ranges: 2–128. The default value is **4**. * COMPRESSION Specifies the compression level of table data. It determines the compression ratio and time. Generally, the higher the level of compression, the higher the ratio, the longer the time; and the lower the level of compression, the lower the ratio, the shorter the time. The actual compression ratio depends on the distribution mode of table data loaded. By default, **COMPRESSION=NO** is added to row-store tables. Value range: The valid values for column-store tables are **YES**, **NO**, **LOW**, **MIDDLE**, and **HIGH**, and the default value is **LOW**. * COMPRESSLEVEL Specifies the table data compression ratio and duration at the same compression level. This divides a compression level into sublevels, providing more choices for compression ratio and duration. As the value becomes greater, the compression ratio becomes higher and duration longer at the same compression level. Value range: 0 to 3. The default value is **0**. * COMPRESSTYPE Specifies the row-store table compression algorithm. The value **1** indicates the PGLZ algorithm, the value **2** indicates the ZSTD algorithm, the value **3** indicates the PGZSTD algorithm (currently not supported), and the value **4** indicates the ZLIB algorithm. By default, row-store tables are not compressed. This parameter cannot be modified after it takes effect. (Only common tables in the Astore engine are supported.) Value range: 0 to 4. The default value is **0**. * COMPRESS\_LEVEL Specifies the row-store table compression algorithm level. This parameter is valid only when **COMPRESSTYPE** is set to **2** or **4**. A higher compression level indicates a better table compression effect and a slower table access speed. This parameter can be modified. The modification affects the compression level of changed data and new data. (Only common tables in the Astore engine are supported.) Value range: –31 to 31. The default value is **0**. * COMPRESS\_CHUNK\_SIZE Specifies the size of a row-store table compression chunk. A smaller chunk size indicates a better compression effect, and a larger data dispersion degree indicates a slower table access speed. This parameter cannot be modified after it takes effect. (Only common tables in the Astore engine are supported.) Value range: subject to the page size. When the page size is 8 KB, the value can be **512**, **1024**, **2048**, or **4096**. Default value: **4096** * COMPRESS\_PREALLOC\_CHUNKS Specifies the number of pre-allocated row-store table compression chunks. A larger number of pre-allocated chunks indicates a lower table compression ratio, and a smaller data dispersion degree indicates a better access performance. This parameter can be modified. The modification affects the number of pre-allocated changed data and new data. (Only common tables in the Astore engine are supported.) Value range: 0 to 7. The default value is **0**. * The maximum value of this parameter is **7** when **COMPRESS\_CHUNK\_SIZE** is set to **512** or **1024**. * The maximum value of this parameter is **3** when **COMPRESS\_CHUNK\_SIZE** is set to **2048**. * The maximum value of this parameter is **1** when **COMPRESS\_CHUNK\_SIZE** is set to **4096**. * COMPRESS\_BYTE\_CONVERT Sets the preprocessing of row-store table compression byte conversion. In some scenarios, the compression effect can be improved, but the performance deteriorates. This parameter can be modified. The modification determines whether to perform byte conversion preprocessing for changed data and new data. This parameter cannot be set to **false** if COMPRESS\_DIFF\_CONVERT is set to **true**. Value range: Boolean value. By default, this function is disabled. * COMPRESS\_DIFF\_CONVERT Sets the preprocessing of row-store table compression differentiation. This parameter can be used together only with **COMPRESS\_BYTE\_CONVERT**. In some scenarios, the compression effect can be improved, but the performance deteriorates. This parameter can be modified. The modification determines whether to perform byte differentiation preprocessing for changed data and new data. Value range: Boolean value. By default, this function is disabled. * MAX\_BATCHROW Specifies the maximum number of rows in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000. The default value is **60000**. * PARTIAL\_CLUSTER\_ROWS Specifies the number of records to be partially clustered for storage during data loading. The parameter is only valid for column-store tables. Value range: greater than or equal to **MAX\_BATCHROW**. You are advised to set this parameter to an integer multiple of **MAX\_BATCHROW**. * DELTAROW\_THRESHOLD Specifies the upper limit of to-be-imported rows for triggering the data import to a delta table when data of a column-store table is to be imported. This parameter takes effect only if **enable\_delta\_store** is set to **on**. The parameter is only valid for column-store tables. Value range: 0 to 9999. The default value is **100**. * segment The data is stored in segment-page mode. This parameter supports only row-store tables. Column-store tables, temporary tables, and unlogged tables are not supported. The Ustore storage engine is not supported. Value range: **on** and **off** Default value: **off** * dek\_cipher Ciphertext of the key used for transparent data encryption. When **enable\_tde** is enabled, the system automatically applies for ciphertext creation. You cannot specify the ciphertext. The key rotation function can be used to update the key. Value range: a string. If encryption is disabled, the default value is null by default. * hasuids If this parameter is set to **on**, a unique table-level ID is allocated to a tuple when the tuple is updated. Value range: **on** and **off** Default value: **off** * **ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }** **ON COMMIT** determines what to do when you commit a temporary table creation operation. The three options are as follows. Currently, only **PRESERVE ROWS** and **DELETE ROWS** can be used. * **PRESERVE ROWS** (default): No special action is taken at the ends of transactions. The temporary table and its table data are unchanged. * **DELETE ROWS**: All rows in the temporary table will be deleted at the end of each transaction block. * **DROP**: The temporary table will be dropped at the end of the current transaction block. Only local temporary tables can be dropped. Global temporary tables cannot be dropped. * **COMPRESS | NOCOMPRESS** If you specify **COMPRESS** in the **CREATE TABLE** statement, the compression feature is triggered in case of a bulk **INSERT** operation. If this feature is enabled, a scan is performed for all tuple data within the page to generate a dictionary and then the tuple data is compressed and stored. If **NOCOMPRESS** is specified, the table is not compressed. Row-store tables do not support compression. Default value: **NOCOMPRESS**, that is, tuple data is not compressed before storage. * **TABLESPACE tablespace\_name** Specifies the tablespace where the new table is created. If not specified, the default tablespace is used. * **COMMNET {=| } text** Comments a new table. If this parameter is not specified, no comment is created. * **CONSTRAINT constraint\_name** Specifies the name of a column or table constraint. The optional constraint clauses specify constraints that new or updated rows must satisfy for an insert or update operation to succeed. There are two ways to define constraints: * A column constraint is defined as part of a column definition, and it is bound to a particular column. * A table constraint is not bound to a particular column but can apply to more than one column. * **NOT NULL** The column is not allowed to contain null values. * **NULL** The column is allowed to contain null values. This is the default setting. This clause is only provided for compatibility with non-standard SQL databases. It is not recommended. * **CHECK ( expression )** Specifies an expression producing a Boolean result where the insert or update operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A check constraint specified as a column constraint should reference only the column's values, while an expression appearing in a table constraint can reference multiple columns. > \[!NOTE]NOTE > **<>NULL** and **!=NULL** are invalid in an expression. Change them to **IS NOT NULL**. * **DEFAULT default\_expr** Assigns a default data value for a column. The value can be any variable-free expressions. (Subqueries and cross-references to other columns in the current table are not allowed.) The data type of the default expression must match the data type of the column. The default expression will be used in any insert operation that does not specify a value for the column. If there is no default value for a column, then the default value is null. * **AUTO\_INCREMENT** Specifies an auto-increment column. If the value of this column is not specified (or the value of this column is set to **0**, **NULL**, or **DEFAULT**), the value of this column is automatically increased by the auto-increment counter. If this column is inserted or updated to a value greater than the current auto-increment counter, the auto-increment counter is updated to this value after the command is executed successfully. The initial auto-increment value is set by the AUTO\_INCREMENT \[ = ] value clause. If it is not set, the default value **1** is used. > \[!NOTE]NOTE > > * The auto-increment column can be specified only when **sql\_compatibility** is set to **B**. > * The data type of the auto-increment column can only be integer, 4-byte or 8-byte floating point, or Boolean. > * Each table can have only one auto-increment column. > * The auto-increment column must be the first column of a primary key constraint or unique constraint. > * The DEFAULT value cannot be specified for an auto-increment column. > * The expression of the CHECK constraint cannot contain auto-increment columns. > * You can specify that the auto-increment column can be NULL. If it is not specified, the auto-increment column contains the NOT NULL constraint by default. > * When a table containing an auto-increment column is created, a sequence that depends on the column is created as an auto-increment counter. You are not allowed to modify or delete the sequence using sequence-related functions. You can view the value of the sequence. > * Sequences are not created for auto-increment columns in local temporary tables. > * Auto-increment columns do not support column store. > * The auto-increment and refresh operations of the auto-increment counter are not rolled back. * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** Specifies that a group of one or more columns of a table can contain only unique values. For the purpose of a unique constraint, null is not considered equal. * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** Specifies that a column or columns of a table can contain only unique (non-duplicate) and non-null values. Only one primary key can be specified for a table. * **REFERENCES reftable \[ ( refcolum ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (column constraint)** **FOREIGN KEY ( column\_name \[, ... ] ) REFERENCES reftable \[ ( refcolumn \[, ... ] ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (table constraint)** The foreign key constraint requires that the group consisting of one or more columns in the new table should contain and match only the referenced column values in the referenced table. If **refcolum** is omitted, the primary key of **reftable** is used. The referenced column should be the only column or primary key in the referenced table. A foreign key constraint cannot be defined between a temporary table and a permanent table. There are three types of matching between a reference column and a referenced column: * **MATCH FULL**: A column with multiple foreign keys cannot be **NULL** unless all foreign key columns are **NULL**. * **MATCH SIMPLE** (default): Any unexpected foreign key column can be **NULL**. * **MATCH PARTIAL**: This option is not supported currently. In addition, when certain operations are performed on the data in the referenced table, the operations are performed on the corresponding columns in the new table. **ON DELETE**: specifies the operations to be executed after a referenced row in the referenced table is deleted. **ON UPDATE**: specifies the operation to be performed when the referenced column data in the referenced table is updated. Possible responses to the **ON DELETE** and **ON UPDATE** clauses are as follows: * **NO ACTION** (default): An error indicating that the foreign key constraint is violated is reported. If the constraint is deferrable and there are still any referenced columns, this error will occur when the constraint is checked. * **RESTRICT**: An error indicating that the foreign key constraint is violated is created. It is the same as **NO ACTION** except that the constraint is not deferrable. * **CASCADE**: deletes any rows referencing the deleted row, or update the value of the referencing column to the new value of the referenced column, respectively. * **SET NULL**: sets the referencing column(s) to **NULL**. * **SET DEFAULT**: sets the referencing column(s) to their default values. * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(default): Enable constraints, create indexes, and enforce constraints on both existing data and newly added data. * ENABLE NOVALIDATE: Enable constraints and create indexes. For CHECK constraints, the constraints are only enforced for newly added data, regardless of the existing data in the table. For UNIQUE and PRIMARY KEY, indexes need to be established, so the constraints will be enforced for the existing data. * DISABLE( NOVALIDATE)(default): Disable constraints, delete indexes, and operations such as modifying the data of the constraint columns can be performed. * DISABLE VALIDATE: Disable constraints and delete indexes. Insertion, update and deletion operations on the table cannot be performed. * **DEFERRABLE | NOT DEFERRABLE** Controls whether the constraint can be deferred. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable can be postponed until the end of the transaction using the **SET CONSTRAINTS** command. **NOT DEFERRABLE** is the default value. Currently, only UNIQUE constraints, primary key constraints, and foreign key constraints accept this clause. All the other constraints are not deferrable. > \[!NOTE]NOTE > Ustore tables do not support the keywords **DEFERRABLE** and **INITIALLY DEFERRED**. * **COMMENT text** Comments. * **PARTIAL CLUSTER KEY** Specifies a partial cluster key for storage. When importing data to a column-store table, you can perform local data sorting by specified columns (single or multiple). * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** If a constraint is deferrable, this clause specifies the default time to check the constraint. * If the constraint is **INITIALLY IMMEDIATE** (default value), it is checked after each statement. * If the constraint is **INITIALLY DEFERRED**, it is checked only at the end of the transaction. The constraint check time can be altered using the **SET CONSTRAINTS** statement. * **USING INDEX TABLESPACE tablespace\_name** Allows selection of the tablespace in which the index associated with a **UNIQUE** or **PRIMARY KEY** constraint will be created. If not specified, **default\_tablespace** is consulted, or the default tablespace in the database if **default\_tablespace** is empty. * **ENCRYPTION\_TYPE = encryption\_type\_value** For the encryption type in the ENCRYPTED WITH constraint, the value of **encryption\_type\_value** is **DETERMINISTIC** or **RANDOMIZED**. ## Examples ``` -- Create a simple table. openGauss=# CREATE TABLE tpcds.warehouse_t1 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); openGauss=# CREATE TABLE tpcds.warehouse_t2 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60), W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` ``` -- Create a table and set the default value of the W_STATE column to GA. openGauss=# CREATE TABLE tpcds.warehouse_t3 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) DEFAULT 'GA', W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a table and check whether the W_WAREHOUSE_NAME column is unique at the end of its creation. openGauss=# CREATE TABLE tpcds.warehouse_t4 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE DEFERRABLE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` ``` -- Create a table with its fill factor set to 70%. openGauss=# CREATE TABLE tpcds.warehouse_t5 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), UNIQUE(W_WAREHOUSE_NAME) WITH(fillfactor=70) ); -- Alternatively, user the following syntax: openGauss=# CREATE TABLE tpcds.warehouse_t6 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH(fillfactor=70); -- Create a table and specify that its data is not written to WALs. openGauss=# CREATE UNLOGGED TABLE tpcds.warehouse_t7 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a temporary table. openGauss=# CREATE TEMPORARY TABLE warehouse_t24 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a local temporary table and specify that this table is dropped when the transaction is committed. openGauss=# CREATE TEMPORARY TABLE warehouse_t25 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) ON COMMIT DELETE ROWS; -- Create a global temporary table and specify that this table data is deleted when the session ends. The current Ustore storage engine does not support global temporary tables. openGauss=# CREATE GLOBAL TEMPORARY TABLE gtt1 ( ID INTEGER NOT NULL, NAME CHAR(16) NOT NULL, ADDRESS VARCHAR(50) , POSTCODE CHAR(6) ) ON COMMIT PRESERVE ROWS; -- Create a table and specify that no error is reported for duplicate tables (if any). openGauss=# CREATE TABLE IF NOT EXISTS tpcds.warehouse_t8 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a general tablespace. openGauss=# CREATE TABLESPACE DS_TABLESPACE1 RELATIVE LOCATION 'tablespace/tablespace_1'; -- Specify a tablespace when creating a table. openGauss=# CREATE TABLE tpcds.warehouse_t9 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) TABLESPACE DS_TABLESPACE1; -- Separately specify the index tablespace for W_WAREHOUSE_NAME when creating the table. openGauss=# CREATE TABLE tpcds.warehouse_t10 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE USING INDEX TABLESPACE DS_TABLESPACE1, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` ``` -- Create a table with a primary key constraint. openGauss=# CREATE TABLE tpcds.warehouse_t11 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- An alternative for the preceding syntax is as follows: openGauss=# CREATE TABLE tpcds.warehouse_t12 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), PRIMARY KEY(W_WAREHOUSE_SK) ); -- Or use the following statement to specify the name of the constraint: openGauss=# CREATE TABLE tpcds.warehouse_t13 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CSTR_KEY1 PRIMARY KEY(W_WAREHOUSE_SK) ); -- Create a table with a compound primary key constraint. openGauss=# CREATE TABLE tpcds.warehouse_t14 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CSTR_KEY2 PRIMARY KEY(W_WAREHOUSE_SK, W_WAREHOUSE_ID) ); -- Create a column-store table. openGauss=# CREATE TABLE tpcds.warehouse_t15 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH (ORIENTATION = COLUMN); -- Create a column-store table using partial clustered storage. openGauss=# CREATE TABLE tpcds.warehouse_t16 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), PARTIAL CLUSTER KEY(W_WAREHOUSE_SK, W_WAREHOUSE_ID) ) WITH (ORIENTATION = COLUMN); -- Define a column-store table with compression enabled. openGauss=# CREATE TABLE tpcds.warehouse_t17 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH (ORIENTATION = COLUMN, COMPRESSION=HIGH); -- Define a column check constraint. openGauss=# CREATE TABLE tpcds.warehouse_t19 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY CHECK (W_WAREHOUSE_SK > 0), W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) CHECK (W_WAREHOUSE_NAME IS NOT NULL), W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); openGauss=# CREATE TABLE tpcds.warehouse_t20 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) CHECK (W_WAREHOUSE_NAME IS NOT NULL), W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CONSTR_KEY2 CHECK(W_WAREHOUSE_SK > 0 AND W_WAREHOUSE_NAME IS NOT NULL) ); -- Create a table with a foreign key constraint. openGauss=# CREATE TABLE tpcds.city_t23 ( W_CITY VARCHAR(60) PRIMARY KEY, W_ADDRESS TEXT ); openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) REFERENCES tpcds.city_t23(W_CITY), W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- An alternative for the preceding syntax is as follows: openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , FOREIGN KEY(W_CITY) REFERENCES tpcds.city_t23(W_CITY) ); -- Or use the following statement to specify the name of the constraint: openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , CONSTRAINT W_FORE_KEY1 FOREIGN KEY(W_CITY) REFERENCES tpcds.city_t23(W_CITY) ); -- Add a varchar column to the tpcds.warehouse_t19 table. ``` ``` openGauss=# ALTER TABLE tpcds.warehouse_t19 ADD W_GOODS_CATEGORY varchar(30); -- Add a check constraint to the tpcds.warehouse_t19 table. openGauss=# ALTER TABLE tpcds.warehouse_t19 ADD CONSTRAINT W_CONSTR_KEY4 CHECK (W_STATE IS NOT NULL); -- Use one statement to alter the types of two existing columns. openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY TYPE varchar(80), ALTER COLUMN W_STREET_NAME TYPE varchar(100); -- This statement is equivalent to the preceding statement. openGauss=# ALTER TABLE tpcds.warehouse_t19 MODIFY (W_GOODS_CATEGORY varchar(30), W_STREET_NAME varchar(60)); -- Add a not-null constraint to an existing column. openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY SET NOT NULL; -- Remove not-null constraints from an existing column. openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY DROP NOT NULL; -- If no partial cluster is specified in a column-store table, add a partial cluster to the table. openGauss=# ALTER TABLE tpcds.warehouse_t17 ADD PARTIAL CLUSTER KEY(W_WAREHOUSE_SK); -- View the constraint name and delete the partial cluster column of a column-store table. openGauss=# \d+ tpcds.warehouse_t17 Table "tpcds.warehouse_t17" Column | Type | Modifiers | Storage | Stats target | Description -------------------+-----------------------+-----------+----------+--------------+------------- w_warehouse_sk | integer | not null | plain | | w_warehouse_id | character(16) | not null | extended | | w_warehouse_name | character varying(20) | | extended | | w_warehouse_sq_ft | integer | | plain | | w_street_number | character(10) | | extended | | w_street_name | character varying(60) | | extended | | w_street_type | character(15) | | extended | | w_suite_number | character(10) | | extended | | w_city | character varying(60) | | extended | | w_county | character varying(30) | | extended | | w_state | character(2) | | extended | | w_zip | character(10) | | extended | | w_country | character varying(20) | | extended | | w_gmt_offset | numeric(5,2) | | main | | Partial Cluster : "warehouse_t17_cluster" PARTIAL CLUSTER KEY (w_warehouse_sk) Has OIDs: no Location Nodes: ALL DATANODES Options: compression=no, version=0.12 openGauss=# ALTER TABLE tpcds.warehouse_t17 DROP CONSTRAINT warehouse_t17_cluster; -- Move a table to another tablespace. openGauss=# ALTER TABLE tpcds.warehouse_t19 SET TABLESPACE PG_DEFAULT; -- Create the joe schema. openGauss=# CREATE SCHEMA joe; -- Move a table to another schema. openGauss=# ALTER TABLE tpcds.warehouse_t19 SET SCHEMA joe; -- Rename an existing table. openGauss=# ALTER TABLE joe.warehouse_t19 RENAME TO warehouse_t23; -- Delete a column from the warehouse_t23 table. openGauss=# ALTER TABLE joe.warehouse_t23 DROP COLUMN W_STREET_NAME; -- Delete the tablespace, schema joe, and schema tables warehouse. openGauss=# DROP TABLE tpcds.warehouse_t1; openGauss=# DROP TABLE tpcds.warehouse_t2; openGauss=# DROP TABLE tpcds.warehouse_t3; openGauss=# DROP TABLE tpcds.warehouse_t4; openGauss=# DROP TABLE tpcds.warehouse_t5; openGauss=# DROP TABLE tpcds.warehouse_t6; openGauss=# DROP TABLE tpcds.warehouse_t7; openGauss=# DROP TABLE tpcds.warehouse_t8; openGauss=# DROP TABLE tpcds.warehouse_t9; openGauss=# DROP TABLE tpcds.warehouse_t10; openGauss=# DROP TABLE tpcds.warehouse_t11; openGauss=# DROP TABLE tpcds.warehouse_t12; openGauss=# DROP TABLE tpcds.warehouse_t13; openGauss=# DROP TABLE tpcds.warehouse_t14; openGauss=# DROP TABLE tpcds.warehouse_t15; openGauss=# DROP TABLE tpcds.warehouse_t16; openGauss=# DROP TABLE tpcds.warehouse_t17; openGauss=# DROP TABLE tpcds.warehouse_t18; openGauss=# DROP TABLE tpcds.warehouse_t20; openGauss=# DROP TABLE tpcds.warehouse_t21; openGauss=# DROP TABLE tpcds.warehouse_t22; openGauss=# DROP TABLE joe.warehouse_t23; openGauss=# DROP TABLE tpcds.warehouse_t24; openGauss=# DROP TABLE tpcds.warehouse_t25; openGauss=# DROP TABLESPACE DS_TABLESPACE1; openGauss=# DROP SCHEMA IF EXISTS joe CASCADE; ``` ## Helpful Links [ALTER TABLE](alter_table.md), [DROP TABLE](drop_table.md), and [CREATE TABLESPACE](create_tablespace.md) ## Suggestions * UNLOGGED * The unlogged table and its indexes do not use the WAL log mechanism during data writing. Their write speed is much higher than that of ordinary tables. Therefore, they can be used for storing intermediate result sets of complex queries to improve query performance. * The unlogged table has no primary/standby mechanism. In case of system faults or abnormal breakpoints, data loss may occur. Therefore, the unlogged table cannot be used to store basic data. * TEMPORARY | TEMP * A temporary table is automatically dropped at the end of a session. * LIKE * The new table automatically inherits all column names, data types, and not-null constraints from this table. The new table is irrelevant to the original table after the creation. * LIKE INCLUDING DEFAULTS * The default expressions are copied from the original table to the new table only if **INCLUDING DEFAULTS** is specified. The default behavior is to exclude default expressions, resulting in the copied columns in the new table having default values **NULL**. * LIKE INCLUDING CONSTRAINTS * The **CHECK** constraints are copied from the original table to the new table only when **INCLUDING CONSTRAINTS** is specified. Other types of constraints are never copied to the new table. Not-null constraints are always copied to the new table. These rules also apply to column constraints and table constraints. * LIKE INCLUDING INDEXES * Any indexes on the original table will not be created on the new table, unless the **INCLUDING INDEXES** clause is specified. * LIKE INCLUDING STORAGE * **STORAGE** settings for the copied column definitions are copied only if **INCLUDING STORAGE** is specified. The default behavior is to exclude **STORAGE** settings. * LIKE INCLUDING COMMENTS * If **INCLUDING COMMENTS** is specified, comments for the copied columns, constraints, and indexes are copied. The default behavior is to exclude comments. * LIKE INCLUDING PARTITION * If **INCLUDING PARTITION** is specified, the partition definitions of the source table are copied to the new table, and the new table no longer uses the **PARTITION BY** clause. The default behavior is to exclude partition definition of the original table. > \[!TIP]NOTICE > List and hash partitioned tables do not support **LIKE INCLUDING PARTITION**. * LIKE INCLUDING RELOPTIONS * If **INCLUDING RELOPTIONS** is specified, the new table will copy the storage parameter (that is, **WITH** clause) of the source table. The default behavior is to exclude partition definition of the storage parameter of the original table. * LIKE INCLUDING ALL * **INCLUDING ALL** contains the meaning of **INCLUDING DEFAULTS**, **INCLUDING CONSTRAINTS**, **INCLUDING INDEXES**, **INCLUDING STORAGE**, **INCLUDING COMMENTS**, **INCLUDING PARTITION**, and **INCLUDING RELOPTIONS**. * ORIENTATION ROW * Creates a row-store table. Row-store applies to the OLTP service, which has many interactive transactions. An interaction involves many columns in the table. Using row-store can improve the efficiency. * ORIENTATION COLUMN * Creates a column-store table. Column-store applies to the DWS, which has a large amount of aggregation computing, and involves a few column operations. --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CREATE-TABLE.md --- # CREATE TABLE ## 功能描述 在当前数据库中创建一个新的空白表,该表由命令执行者所有。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 ## 语法格式 通过无括号like创建表。 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name LIKE source_table [ like_option [...] ] ``` * like后不能添加普通建表的额外可选语句。 * table前不能添加foreign选项,包括外表、mot表的创建。 * 默认复制源表的索引,若不希望复制索引,需要手动指定EXCLUDING INDEXES。 * 默认复制源分区表的分区,若不希望复制分区,需要手动指定EXCLUDING PARTITION。 * 默认复制字段的DEFAULT值,若不希望复制DEFAULT值,需要手动指定EXCLUDING DEFAULTS。 * 对于含索引的分区表,若只指定EXCLUDING PARTITION,由于默认复制分区,将会报错,因为普通表不支持分区索引。 * 只支持复制range分区表的分区,对于hash、list分区表,由于默认复制分区,会直接报错,需要手动指定EXCLUING PARTITION。二级分区只支持复制range-range分区,处理方法同上。 * 生成列语法支持忽略GENERATED ALWAYS。 * 大多数情况下,生成列表达式调用的函数只能是不可变(IMMUTABLE)函数,但是对于非IMMUTABLE的concat和concat\_ws函数,特定入参类型同样支持,这些类型包括BOOL,CHAR,NAME,INT1,INT2,INT4,INT8,INT16,TEXT,OID,CLOB,JSON,XML,UNKNOWN,VARCHAR,VARBIT,CSTRING,ANYSET,ANYENUM,JSONB,NVARCHAR2,YEAR,UINT1,UINT2,UINT4,UINT8。 创建表。 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ CHARACTER SET | CHARSET charset ] [BINARY | ASCII] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | table_indexclause | LIKE source_table [ like_option [...] ] } [, ... ]) [ create_option [ ...] ] ``` * 其中create\_option为: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ create_table_option [[,] ...] ] 除了WITH选项外允许输入多次同一种create_option,以最后一次的输入为准。 ``` * 其中create\_table\_option为: ``` [ AUTOEXTEND_SIZE [=] value ] [ AUTO_INCREMENT [=] value ] [ AVG_ROW_LENGTH [=] value ] [ [DEFAULT] { CHARSET | CHARACTER SET } [=] charset_name ] [ CHECKSUM [=] value ] [ [DEFAULT] COLLATE [=] collation_name ] [ COMMENT [=] 'text' ] [ COMPRESSION [=] compression_arg ] [ CONNECTION [=] 'connect_string' ] [ {DATA | INDEX} DIRECTORY [=] 'absolute path to directory' ] [ DELAY_KEY_WRITE [=] value ] [ ENCRYPTION [=] 'encryption_string' ] [ ENGINE [=] engine_name ] [ ENGINE_ATTRIBUTE [=] 'string' ] [ INSERT_METHOD [=] { NO | FIRST | LAST } ] [ KEY_BLOCK_SIZE [=] value ] [ MAX_ROWS [=] value ] [ MIN_ROWS [=] value ] [ PACK_KEYS [=] value ] [ PASSWORD [=] 'password' ] [ ROW_FORMAT [=] row_format_name ] [ START TRANSACTION ] [ SECONDARY_ENGINE_ATTRIBUTE [=] 'string' ] [ STATS_AUTO_RECALC [=] value ] [ STATS_PERSISTENT [=] value ] [ STATS_SAMPLE_PAGES [=] value ] [ TABLESPACE tablespace_name [STORAGE DISK] ] [ [TABLESPACE tablespace_name] STORAGE MEMORY ] [ UNION [=] (tbl_name[,tbl_name]...) ] 允许输入多次同一种create_table_option,以最后一次的输入为准。 ``` * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { { column_name | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PRIMARY KEY [ index_name ] [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | COMMENT {=| } 'text' } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | [GENERATED ALWAYS] AS ( generation_expr ) [STORED] | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE [KEY] index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | [PRIMARY] KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 创建表上索引table\_indexclause: ```sql {[FULLTEXT] INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option]... ``` 该语法不支持CREATE FOREIGN TABLE (MOT表等) 创建。 * 其中参数index\_type为: ``` USING {BTREE | HASH | GIN | GIST | PSORT | UBTREE} ``` * 其中参数key\_part为: ``` {col_name[(length)] | (expr)} [ASC | DESC] ``` length为前缀索引。 * 其中参数index\_option为: ``` index_option:{ COMMENT 'string' | index_type | [ VISIBLE | INVISIBLE ] | [WITH PARSER NGRAM] } ``` COMMENT、index\_type、\[ VISIBLE | INVISIBLE ] 的顺序和数量任意,但相同字段仅最后一个值生效。WITH PARSER NGRAM 为FULLTEXT INDEX指定的ngram解析器,前提是索引必须指定关键字FULLTEXT,FULLTEXT 默认 WITH PARSER NGRAM。 * 其中like选项like\_option为: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | PARTITION | RELOPTIONS | ALL } ``` ## 参数说明 * **data\_type** 字段的数据类型。 对枚举类型ENUM,以及CHAR, CHARACTER, VARCHAR, TEXT等字符类型,创建表格时可使用关键字CHARSET或CHARACTER SET声明列字符集。目前该特性仅做语法支持,不实现功能。 * **column\_constraint** 字段的类型约束中,添加了mysql的ON UPDATE特性,归类于字段类型约束。与DEFAULT属性属于同类约束。该ON UPDATE属性用于,执行UPDATE操作timestamp字段为缺省时,则自动更新timestamp字段的时间截。如果更新字段的数据内容与原来的数据内容一致,则其他含有ON UPDATE的字段的时间截不会自动更新。 ```sql CREATE TABLE table_name(column_name timestamp ON UPDATE CURRENT_TIMESTAMP); ``` * **CHARACTER SET | CHARSET charset** 用于指定表字段的字符集,单独指定时会将字段的字符序设置为指定的字符集的默认字符序。支持ASCII和BINARY字符集。 * **COLLATE collation** COLLATE子句指定列的排序规则(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 对未被支持的排序规则,数据库将发出警告,并将该列设置为默认的排序规则。支持BINARY字符序。 * **{ \[DEFAULT] CHARSET | CHARACTER SET } \[=] charset\_name** 用于选择表所使用的字符集,单独指定时会将字段的字符序设置为指定的字符集的默认字符序。支持ASCII和BINARY字符集。 * **COLLATE \[=] collation\_name** 用于选择表所使用的排序规则,如果没有指定,则使用默认的排序规则。支持BINARY字符序。 * **ROW\_FORMAT \[=] row\_format\_name** 用于选择表所使用的行存储格式;目前该特性仅有语法支持,不实现功能。 * **AUTO\_INCREMENT** 该关键字将字段指定为自动增长列。自动增长列必须是某个索引的第一个字段。 若在插入时不指定此列的值(或指定此列的值为0、NULL、DEFAULT),此列的值将由自增计数器自动增长得到。 若插入或更新此列为一个大于当前自增计数器的值,执行成功后,自增计数器将刷新为此值。 自增初始值由“AUTO\_INCREMENT \[ = ] value”子句设置,若不设置,默认为1。 > \[!NOTE]说明 > > * 仅在参数sql\_compatibility=B时可以指定自动增长列。 > * 自动增长列数据类型只能为整数类型、4字节或8字节浮点类型。 > * 每个表只能有一个自动增长列。 > * 自动增长列必须是索引的第一个字段。 > * 自动增长列不能指定DEFAULT缺省值。 > * CHECK约束的表达式中不能含有自动增长列。 > * 可以指定自动增长列允许NULL,若不指定,默认自动增长列含有NOT NULL约束。 > * 含有自动增长列的表创建时,会创建一个依赖于此列的序列作为自增计数器,不允许通过序列相关功能修改或删除此序列,可以查看序列的值。 > * 本地临时表中的自动增长列不会创建序列。 > * 自动增长列不支持列式存储。 > * 自增计数器自增和刷新操作不会回滚。 > * 因精度问题,自增值较大时,FLOAT/DOUBLE类型自增后可能重复报错,可见文末示例。 * **BINARY** 该关键字将设置列的字符序为该列字符集对应的`_bin`字符序,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`。 * **ASCII** 该关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 * **AUTOEXTEND\_SIZE \[=] value** 用于指定在表空间变满时扩展表空间大小;目前该特性仅有语法支持,不实现功能。参数的取值范围包括非负整数,小数,标识符,非负整数+标识符,小数+标识符。 * **AVG\_ROW\_LENGTH \[=] value** 用于指定表的平均行长度;目前该特性仅有语法支持,不实现功能。参数的取值范围包括非负整数,小数。 * **CHECKSUM \[=] value** 用于指定是否维护所有行的实时校验和;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **CONNECTION \[=] 'connect\_string'** 用于指定联合表的连接字符串;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **{DATA | INDEX} DIRECTORY \[=] 'absolute path to directory'** 用于指定表数据数据和索引的存储目录;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **DELAY\_KEY\_WRITE \[=] value** 用于指定是否延迟表的索引更新直到表关闭;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **ENCRYPTION \[=] 'encryption\_string'** 用于指定表启用或禁用页面级数据加密;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **ENGINE\_ATTRIBUTE \[=] 'string'** 用于指定主存储引擎的表属性;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **INSERT\_METHOD \[=] { NO | FIRST | LAST }** 用于指定应将行插入到的表;目前该特性仅有语法支持,不实现功能。参数的取值范围为NO,FIRST,LAST。 * **KEY\_BLOCK\_SIZE \[=] value** 用于指定索引键块的字节大小;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **MAX\_ROWS \[=] value** 用于指定计划在表中存储的最大行数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **MIN\_ROWS \[=] value** 用于指定计划在表中存储的最小行数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **PACK\_KEYS \[=] value** 用于指定控制压缩索引的方式;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **PASSWORD \[=] 'password'** 此选项未使用;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **SECONDARY\_ENGINE\_ATTRIBUTE \[=] 'string'** 用于指定辅助存储引擎的表属性;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **START TRANSACTION** 用于开启事务模式;目前该特性仅有语法支持,不实现功能。 * **STATS\_AUTO\_RECALC \[=] value** 用于指定是否自动重新计算表的持久统计信息;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **STATS\_PERSISTENT \[=] value** 用于指定是否为表启用持久统计信息;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **STATS\_SAMPLE\_PAGES \[=] value** 用于指定估计索引列的基数和其他统计信息时要采样的索引页数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **UNION \[=] (tbl\_name\[,tbl\_name]...)** 用于访问一组相同的表作为一个表;目前该特性仅有语法支持,不实现功能。 * **TABLESPACE tablespace\_name STORAGE DISK** 用于指定表存储在磁盘;目前该特性仅有语法支持,不实现功能。 * **\[TABLESPACE tablespace\_name] STORAGE MEMORY** 用于指定表存储在内存;目前该特性仅有语法支持,不实现功能。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 ## 示例 ``` --创建表上索引 openGauss=# CREATE TABLE tpcds.warehouse_t24 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , key (W_WAREHOUSE_SK) , index idx_ID using btree (W_WAREHOUSE_ID) ); --创建表上组合索引、表达式索引、函数索引 openGauss=# CREATE TABLE tpcds.warehouse_t25 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , key using btree (W_WAREHOUSE_SK, W_WAREHOUSE_ID desc) , index idx_SQ_FT using btree ((abs(W_WAREHOUSE_SQ_FT))) , key idx_SK using btree ((abs(W_WAREHOUSE_SK)+1)) ); --创建带INVISIBLE普通索引的表 openGauss=# CREATE TABLE tpcds.warehouse_t26 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , index idx_ID using btree (W_WAREHOUSE_ID) INVISIBLE ); --包含index_option字段 openGauss=# create table test_option(a int, index idx_op using btree(a) comment 'idx comment'); ``` ``` --创建表格时对列指定字符集。 openGauss=# CREATE TABLE t_column_charset(c text CHARSET test_charset); WARNING: character set "test_charset" for type text is not supported yet. default value set CREATE TABLE --创建表格时对表格指定字符序。 openGauss=# CREATE TABLE t_table_collate(c text) COLLATE test_collation; WARNING: COLLATE for TABLE is not supported for current version. skipped CREATE TABLE --创建表格时对表格指定字符集。 openGauss=# CREATE TABLE t_table_charset(c text) CHARSET test_charset; WARNING: CHARSET for TABLE is not supported for current version. skipped CREATE TABLE --创建表格时对表格指定行记录格式。 openGauss=# CREATE TABLE t_row_format(c text) ROW_FORMAT test_row_format; WARNING: ROW_FORMAT for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定在表空间变满时扩展表空间大小。 openGauss=# CREATE TABLE t_autoextend_size(c text) AUTOEXTEND_SIZE 4M; WARNING: AUTOEXTEND_SIZE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表的平均行长度。 openGauss=# CREATE TABLE t_avg_row_length(c text) AVG_ROW_LENGTH 10; WARNING: AVG_ROW_LENGTH for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定是否维护所有行的实时校验和。 openGauss=# CREATE TABLE t_checksum(c text) CHECKSUM 0; WARNING: CHECKSUM for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定联合表的连接字符串。 openGauss=# CREATE TABLE t_connection(c text) CONNECTION 'connect_string'; WARNING: CONNECTION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表数据数据和索引的存储目录。 openGauss=# CREATE TABLE t_data_directory(c text) DATA DIRECTORY 'data_directory'; WARNING: DIRECTORY for TABLE is not supported for current version. skipped CREATE TABLE openGauss=# CREATE TABLE t_index_directory(c text) INDEX DIRECTORY 'index_directory'; WARNING: DIRECTORY for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定是否延迟表的索引更新直到表关闭。 openGauss=# CREATE TABLE t_delay_key_write(c text) DELAY_KEY_WRITE 1; WARNING: DELAY_KEY_WRITE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表启用或禁用页面级数据加密。 openGauss=# CREATE TABLE t_encryption(c text) ENCRYPTION 'Y'; WARNING: ENCRYPTION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定主存储引擎的表属性。 openGauss=# CREATE TABLE t_engine_attribute(c text) ENGINE_ATTRIBUTE 'engine_attribute'; WARNING: ENGINE_ATTRIBUTE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定应将行插入到的表。 openGauss=# CREATE TABLE t_insert_method(c text) INSERT_METHOD NO; WARNING: INSERT_METHOD for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定索引键块的字节大小。 openGauss=# CREATE TABLE t_key_block_size(c text) KEY_BLOCK_SIZE 10; WARNING: KEY_BLOCK_SIZE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定计划在表中存储的最大行数。 openGauss=# CREATE TABLE t_max_rows(c text) MAX_ROWS 20; WARNING: MAX_ROWS for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定计划在表中存储的最小行数。 openGauss=# CREATE TABLE t_min_rows(c text) MIN_ROWS 5; WARNING: MIN_ROWS for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定控制压缩索引的方式。 openGauss=# CREATE TABLE t_pack_keys(c text) PACK_KEYS DEFAULT; WARNING: PACK_KEYS for TABLE is not supported for current version. skipped CREATE TABLE openGauss=# CREATE TABLE t_password(c text) PASSWORD 'password'; WARNING: PASSWORD for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定开启事务模式。 openGauss=# CREATE TABLE t_start_transaction(c text) START TRANSACTION; WARNING: START TRANSACTION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定辅助存储引擎的表属性。 openGauss=# CREATE TABLE t_secondary_engine_attribute(c text) SECONDARY_ENGINE_ATTRIBUTE 'secondary_engine_attribute'; WARNING: SECONDARY_ENGINE_ATTRIBUTE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定是否自动重新计算表的持久统计信息。 openGauss=# CREATE TABLE t_stats_auto_recalc(c text) STATS_AUTO_RECALC DEFAULT; WARNING: STATS_AUTO_RECALC for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定是否为表启用持久统计信息。 openGauss=# CREATE TABLE t_stats_persistent(c text) STATS_PERSISTENT DEFAULT; WARNING: STATS_PERSISTENT for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定估计索引列的基数和其他统计信息时要采样的索引页数。 openGauss=# CREATE TABLE t_stats_sample_pages(c text) STATS_SAMPLE_PAGES 1; WARNING: STATS_SAMPLE_PAGES for TABLE is not supported for current version. skipped CREATE TABLE --创建表时访问一组相同的表作为一个表。 openGauss=# CREATE TABLE t_union(c text) UNION(a, b); WARNING: UNION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表存储在磁盘。 openGauss=# CREATE TABLESPACE test ADD DATAFILE 'data.ibd'; WARNING: Suffix ".ibd" of datafile path detected. The actual path will be renamed as "data_ibd" CREATE TABLESPACE openGauss=# CREATE TABLE t_tablespace_storage_disk(c text) TABLESPACE test STORAGE DISK; WARNING: TABLESPACE_OPTION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表存储在内存。 openGauss=# CREATE TABLESPACE test ADD DATAFILE 'data.ibd'; WARNING: Suffix ".ibd" of datafile path detected. The actual path will be renamed as "data_ibd" CREATE TABLESPACE openGauss=# CREATE TABLE t_tablespace_storage_memory(c text) TABLESPACE test STORAGE MEMORY; WARNING: TABLESPACE_OPTION for TABLE is not supported for current version. skipped CREATE TABLE ``` \--创建兼容MySQL全文索引语法的表。前提是兼容模式为B的数据库。 ```sql openGauss=# CREATE TABLE test ( openGauss(# id int unsigned auto_increment not null primary key, openGauss(# title varchar, openGauss(# boby text, openGauss(# name name, openGauss(# FULLTEXT (title, boby) WITH PARSER ngram openGauss(# ); NOTICE: CREATE TABLE will create implicit sequence "test_id_seq" for serial column "test.id" NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_pkey" for table "test" CREATE TABLE openGauss=# drop table if exists articles; NOTICE: table "articles" does not exist, skipping DROP TABLE openGauss=# CREATE TABLE articles ( openGauss(# ID int, openGauss(# title VARCHAR(100), openGauss(# FULLTEXT INDEX ngram_idx(title)WITH PARSER ngram openGauss(# ); CREATE TABLE openGauss=# \d articles Table "fulltext_test.articles" Column | Type | Modifiers --------+------------------------+----------- ID | integer | title | character varying(100) | Indexes: "ngram_idx" gin (to_tsvector('ngram'::regconfig, title::text)) TABLESPACE pg_default openGauss=# drop table if exists articles; DROP TABLE openGauss=# CREATE TABLE articles ( openGauss(# ID int, openGauss(# title VARCHAR(100), openGauss(# FULLTEXT INDEX (title)WITH PARSER ngram openGauss(# ); CREATE TABLE openGauss=# \d articles Table "fulltext_test.articles" Column | Type | Modifiers --------+------------------------+----------- ID | integer | title | character varying(100) | Indexes: "articles_to_tsvector_idx" gin (to_tsvector('ngram'::regconfig, title::text)) TABLESPACE pg_default openGauss=# drop table if exists articles; DROP TABLE openGauss=# CREATE TABLE articles ( openGauss(# ID int, openGauss(# title VARCHAR(100), openGauss(# FULLTEXT KEY keyngram_idx(title)WITH PARSER ngram openGauss(# ); CREATE TABLE openGauss=# \d articles Table "fulltext_test.articles" Column | Type | Modifiers --------+------------------------+----------- ID | integer | title | character varying(100) | Indexes: "keyngram_idx" gin (to_tsvector('ngram'::regconfig, title::text)) TABLESPACE pg_default openGauss=# drop table if exists articles; DROP TABLE openGauss=# CREATE TABLE articles ( openGauss(# ID int, openGauss(# title VARCHAR(100), openGauss(# FULLTEXT KEY (title)WITH PARSER ngram openGauss(# ); CREATE TABLE openGauss=# \d articles Table "fulltext_test.articles" Column | Type | Modifiers --------+------------------------+----------- ID | integer | title | character varying(100) | Indexes: "articles_to_tsvector_idx" gin (to_tsvector('ngram'::regconfig, title::text)) TABLESPACE pg_default openGauss=# create table table_ddl_0154(col1 int,col2 varchar(64), FULLTEXT idx_ddl_0154(col2)); CREATE TABLE openGauss=# create table t2 (a float primary key auto_increment); NOTICE: CREATE TABLE will create implicit sequence "t2_a_seq" for serial column "t2.a" NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "t2_pkey" for table "t2" CREATE TABLE openGauss=# alter table t2 auto_increment = 16777216; ALTER TABLE openGauss=# insert into t2 values (null); INSERT 0 1 -- float类型能精确表示的上限为16777216,自增到16777217时存储的值与16777216一致,导致主键冲突 openGauss=# insert into t2 values (null); ERROR: duplicate key value violates unique constraint "t2_pkey" DETAIL: Key (a)=(1.67772e+07) already exists. openGauss=# insert into t2 values (null); INSERT 0 1 ``` --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/server/shark-CREATE-TABLE.md --- # CREATE TABLE ## 功能描述 在当前数据库中创建一个新的空白表,该表由命令执行者所有。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。 * 新增支持 `AS expr [PERSISTED]` 生成列语法。 * 新增支持`opt_clustered`语法。 * 建表语句中,针对UNIQUE和PRIMARY KEY约束,支持通过WITH给出选项,对应index\_parameters子句,新增支持的选项包括: ``` FILLFACTOR = fillfactor | PAD_INDEX = { ON | OFF } | IGNORE_DUP_KEY = { ON | OFF } | STATISTICS_NORECOMPUTE = { ON | OFF } | STATISTICS_INCREMENTAL = { ON | OFF } | ALLOW_ROW_LOCKS = { ON | OFF } | ALLOW_PAGE_LOCKS = { ON | OFF } | OPTIMIZE_FOR_SEQUENTIAL_KEY = { ON | OFF } | XML_COMPRESSION = { ON | OFF } | COMPRESSION_DELAY = { 0 | delay [ MINUTES | MINUTE ] } | DATA_COMPRESSION = { NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE } ``` 其中FILLFACTOR选项的取值fillfactor为\[1, 100]的整数,实际含义同A库(A库的取值范围为\[10, 100]的整数),因此当D库中fillfactor的取值范围为\[1, 10),不报错,将打印notice信息,并将fillfactor的取值设置为A库的最小值10; COMPRESSION\_DELAY选项的取值delay为\[0, 10080]的整数; 除FILLFACTOR选项含有实际功能,同A库,其余参数均无实际功能,仅语法支持。 * 建表语句中,针对UNIQUE和PRIMARY KEY约束,支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * 建表语句新增支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * 建表语句新增支持TEXTIMAGE\_ON { filegroup | "default" } 选项,无实际作用,仅语法支持。 * filegroup为任意字符串,支持通过\[]包裹。 * 如果同时指定ON filegroup子句和TEXTIMAGE\_ON filegroup子句,ON filegroup子句应位于前面,否则会出现语法报错。 * ON/TEXTIMAGE\_ON filegroup子句无法和ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }子句同时存在。 * 支持通过特殊前缀(`#`和`##`)的表名分别创建本地临时表和全局临时表。 默认将`#`, `##`识别为标识符的一部分(通过会话级布尔参数`enable_special_operator`切换)而非操作符,因此若只作为操作符使用则需要打开该参数,若同时作为表名以及操作符使用,则关闭该参数并将操作符与操作数用空格分开。 ## 语法格式 创建表。 ```EBNF CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ CHARACTER SET | CHARSET charset ] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ]) [ AUTO_INCREMENT [ = ] value ] [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] | [ ON filegroup ] | [ TEXTIMAGE_ON filegroup ] ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMMENT {=| } 'text' ]; ``` * 其中列约束column\_constraint为: ```EBNF [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | IDENTITY [ ( seed, increment ) ] | GENERATED ALWAYS AS ( generation_expr ) [STORED] | AS ( generation_expr ) [PERSISTED] | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE [KEY] index_parameters [ ON filegroup ] | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters [ ON filegroup ] | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中表约束table\_constraint为: ```EBNF [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ opt_clustered ] ( { { column_name [ ( length ) ] | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] [ ON filegroup ] | PRIMARY KEY [ opt_clustered ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] [ ON filegroup ] | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中索引参数index\_parameters为: ```EBNF [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## 参数说明 * **IDENTITY \[ ( seed, increment ) ]** * 该语法为列添加identity属性,序列值递增,`seed`指定起始值,`increment`指定步长。 * 一张表只能定义一列(包括generated as identity)。 * **AS ( generation\_expr ) \[PERSISTED]** 该子句为兼容D库的语法,将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,PERSISTED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > > * PERSISTED关键字可省略,与不省略PERSISTED语义相同。 > * 兼容D库的生成列无需指定列类型,由表达式计算类型得到列的类型。 > * 兼容D库的生成列在删除生成列依赖的普通列时报错,必须先删除生成列,才能删除生成列依赖的普通列。 * **opt\_clustered** 参数内容为CLUSTERED/NONCLUSTERED,兼容D库的语法,指定创建聚合/非聚合索引。仅语法作用,没有实际功能。 * **WITH ( { storage\_parameter = value } \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。用于表的WITH子句还可以包含OIDS=FALSE表示不分配OID。 针对UNIQUE和PRIMARY KEY约束,新增支持的storage\_parameter选项包括: * FILLFACTOR int类型,填充因子,实际的含义和功能同A库。 取值范围:\[1, 100]的整数,A库的取值范围为\[10, 100]的整数,因此当D库中fillfactor的取值范围为\[1, 10),不报错,将打印notice信息,并将fillfactor的取值设置为A库的最小值10。 * PAD\_INDEX bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * IGNORE\_DUP\_KEY bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * STATISTICS\_NORECOMPUTE bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * STATISTICS\_INCREMENTAL bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * ALLOW\_ROW\_LOCKS bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * ALLOW\_PAGE\_LOCKS bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * OPTIMIZE\_FOR\_SEQUENTIAL\_KEY bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * XML\_COMPRESSION bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * COMPRESSION\_DELAY int类型,单位MINUTES或者MINUTE,可选,无实际功能,仅语法兼容。 取值范围:0 | delay \[ MINUTES | MINUTE ],其中delay为\[0, 10080]的整数。 * DATA\_COMPRESSION string类型,无实际功能,仅语法兼容。 取值范围:NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE\_ARCHIVE。 * **filegroup** * 建表语句中,针对UNIQUE和PRIMARY KEY约束,支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * 建表语句新增支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * 建表语句新增支持TEXTIMAGE\_ON { filegroup | "default" } 选项,无实际作用,仅语法支持。 * filegroup为任意字符串,支持通过\[]包裹。 * 如果同时指定ON filegroup子句和TEXTIMAGE\_ON filegroup子句,ON filegroup子句应位于前面,否则会出现语法报错。 * ON/TEXTIMAGE\_ON filegroup子句无法和ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }子句同时存在。 * **ASC | DESC** * table\_constraint中,针对PRIMARY KEY和UNIQUE约束支持使用{ column\_name \[ ASC | DESC ] }语法, 为主键和唯一键提供升序或降序约束。 ## 生成列示例 ```sql opengauss=# CREATE TABLE Products( opengauss(# QtyAvailable smallint, opengauss(# UnitPrice money, opengauss(# InventoryValue AS (QtyAvailable * UnitPrice) opengauss(# ); NOTICE: The virtual computed columns (non-persisted) are currently ignored and behave the same as persisted columns. CREATE TABLE opengauss=# ALTER TABLE Products ADD RetailValue AS (QtyAvailable * UnitPrice * 1.5) PERSISTED; ALTER TABLE opengauss=# \d+ Products Table "public.products" Column | Type | Modifiers | Storage | Stats target | Description ----------------+----------+-----------------------------------------------------------------------+---------+--------------+------------- qtyavailable | smallint | | plain | | unitprice | money | | plain | | inventoryvalue | money | as ((qtyavailable * unitprice)) persisted | plain | | retailvalue | money | as (((qtyavailable * unitprice) * (1.5)::double precision)) persisted | plain | | Has OIDs: no Options: orientation=row, compression=no opengauss=# ALTER TABLE Products DROP unitprice; ERROR: cannot drop a column used by a generated column DETAIL: Column "unitprice" is used by generated column "retailvalue". opengauss=# ALTER TABLE Products DROP inventoryvalue; ALTER TABLE opengauss=# ALTER TABLE Products DROP retailvalue; ALTER TABLE opengauss=# ALTER TABLE Products DROP unitprice; ALTER TABLE ``` ## IDENTITY \[ ( seed, increment ) ] 示例 ```sql openGauss=# create extension shark; CREATE EXTENSION openGauss=# create table t1 (a int identity(10, 20), b int); NOTICE: CREATE TABLE will create implicit sequence "t1_a_seq_identity" for serial column "t1.a" CREATE TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+-------------------+---------+--------------+------------- a | integer | not null identity | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no, collate=1537 Character Set: UTF8 Collate: utf8mb4_general_ci openGauss=# insert into t1(b) values(10); INSERT 0 1 openGauss=# insert into t1(a, b) overriding system value values(12, 10); INSERT 0 1 openGauss=# insert into t1 default values; INSERT 0 1 openGauss=# select * from t1; a | b ----+---- 10 | 10 12 | 10 30 | (3 rows) ``` ## WITH ( { storage\_parameter = value } \[, ... ] )示例 ```sql create table test_with_1(a int, CONSTRAINT PK_test_with_1 PRIMARY KEY(a) WITH (PAD_INDEX = OFF, FILLFACTOR = 50, IGNORE_DUP_KEY = off, STATISTICS_NORECOMPUTE = off, STATISTICS_INCREMENTAL = off, ALLOW_ROW_LOCKS = off, ALLOW_PAGE_LOCKS = off, OPTIMIZE_FOR_SEQUENTIAL_KEY = off, XML_COMPRESSION = off)); NOTICE: parameter "pad_index" is currently ignored. NOTICE: parameter "ignore_dup_key" is currently ignored. NOTICE: parameter "statistics_norecompute" is currently ignored. NOTICE: parameter "statistics_incremental" is currently ignored. NOTICE: parameter "allow_row_locks" is currently ignored. NOTICE: parameter "allow_page_locks" is currently ignored. NOTICE: parameter "optimize_for_sequential_key" is currently ignored. NOTICE: parameter "xml_compression" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_with_1" for table "test_with_1" create table test_with_2(a int, CONSTRAINT PK_test_with_2 PRIMARY KEY(a) with (COMPRESSION_DELAY = 0 MINUTES)); NOTICE: parameter "compression_delay" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_with_2" for table "test_with_2" create table test_with_3(a int, CONSTRAINT PK_test_with_3 PRIMARY KEY(a) with (COMPRESSION_DELAY = 10080 minute)); NOTICE: parameter "compression_delay" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_with_3" for table "test_with_3" create table test_with_4(a int, CONSTRAINT PK_test_with_4 PRIMARY KEY(a) with (data_compression = COLUMNSTORE_ARCHIVE)); NOTICE: parameter "data_compression" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_with_4" for table "test_with_4" create table test_with_5(a int, PRIMARY KEY(a) with (pad_index = on, fillfactor = 20)); NOTICE: parameter "pad_index" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_with_5_pkey" for table "test_with_5" create table test_with_6(a int, PRIMARY KEY(a) with (pad_index = on, fillfactor = 1)); NOTICE: parameter "pad_index" is currently ignored. NOTICE: parameter fillfactor will be set to 10 when it is less than 10. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_with_6_pkey" for table "test_with_6" create table test_with_7(a int, UNIQUE(a) with (pad_index = on, fillfactor = 1)); NOTICE: parameter "pad_index" is currently ignored. NOTICE: parameter fillfactor will be set to 10 when it is less than 10. NOTICE: CREATE TABLE / UNIQUE will create implicit index "test_with_7_a_key" for table "test_with_7" ``` ## filegroup示例 ```sql create table t1(a int) on [primary]; create table t2(a int) on "default"; create table t3(id int) on [filegroup]; create table t4(id int) on filegroup; create table t5(id int) on 'filegroup'; create table t6(id int) on "filegroup"; create table t7(a int) textimage_on [primary]; create table t8(a int) textimage_on "default"; create table t9(a int) on "default" textimage_on [primary]; create table t10(a int) on "default" textimage_on "default"; create table t11(a int PRIMARY KEY WITH (PAD_INDEX = OFF) ON [primary]) ON [primary]; create table t12(a int UNIQUE WITH (XML_COMPRESSION = OFF) ON [primary]) ON [primary]; create table t13(a int, CONSTRAINT PK_t11 PRIMARY KEY(a) WITH (PAD_INDEX = OFF) ON [primary]) ON [primary]; create table t14(a int, CONSTRAINT PK_t12 UNIQUE(a) WITH (XML_COMPRESSION = OFF) ON [primary]) ON [primary]; ``` ## ASC | DESC示例 ```sql openGauss=# create table CONSTRAINT_DESC(id int not null, v1 varchar(30), constraint PK_CONSTRAINT_DESC primary key(id DESC)); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_constraint_desc" for table "constraint_desc" CREATE TABLE openGauss=# \d+ CONSTRAINT_DESC Table "public.constraint_desc" Column | Type | Modifiers | Storage | Stats target | Description --------+-----------------------+-----------+----------+--------------+------------- id | integer | not null | plain | | v1 | character varying(30) | | extended | | Indexes: "pk_constraint_desc" PRIMARY KEY, btree (id DESC) TABLESPACE pg_default Has OIDs: no Options: orientation=row, compression=no ``` ## 使用特殊前缀创建本地和全局临时表 ```sql openGauss=# CREATE TEMPORARY TABLE #ltt1 ( ID INTEGER NOT NULL, NAME CHAR(16) NOT NULL, ADDRESS VARCHAR(50) , POSTCODE CHAR(6) ) ON COMMIT PRESERVE ROWS; CREATE TABLE openGauss=# CREATE GLOBAL TEMPORARY TABLE ##gtt1 ( ID INTEGER NOT NULL, NAME CHAR(16) NOT NULL, ADDRESS VARCHAR(50) , POSTCODE CHAR(6) ) ON COMMIT PRESERVE ROWS; CREATE TABLE ``` ## 相关链接 [CREATE TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_table.html) --- --- url: /zh/docs/latest-lite/sql_reference/create_table_1.md --- # CREATE TABLE ## 功能描述 在当前数据库中创建一个新的空白表,该表由命令执行者所有。 ## 注意事项 * 列存表支持的数据类型请参考[列存表支持的数据类型](data_types_supported_by_column_store_tables.md)。 * 列存表不支持数组。 * 列存表不支持生成列。 * 列存表不支持创建全局临时表。 * 创建列存表的数量建议不超过1000个。 * 如果在建表过程中数据库系统发生故障,系统恢复后可能无法自动清除之前已创建的、大小为0的磁盘文件。此种情况出现概率小,不影响数据库系统的正常运行。 * 列存表的表级约束只支持PARTIAL CLUSTER KEY、UNIQUE、PRIAMRY KEY,不支持外键等表级约束。 * 列存表的字段约束只支持NULL、NOT NULL和DEFAULT常量值、UNIQUE和PRIMARY KEY。 * 列存表支持delta表,受参数enable\_delta\_store控制是否开启,受参数deltarow\_threshold控制进入delta表的阀值。 * 列存表的字段的字符集必须与数据库字符集一致。 * 使用JDBC时,支持通过PrepareStatement对DEFAULT值进行参数化设置。 * 每张表的列数最大为1600,具体取决于列的类型,所有列的大小加起来不能超过8192 byte(由于数据存储形式原因,实际上限略小于8192 byte),text、varchar、char等长度可变的类型除外。 * 被授予CREATE ANY TABLE权限的用户,可以在public模式和用户模式下创建表。如果想要创建包含serial类型列的表,还需要授予CREATE ANY SEQUENCE创建序列的权限。 * 不可与同一模式下已存在的synonym产生命名冲突。 * 仅支持在B兼容性数据库下指定COMMENT和可见性VISIBLE\INVISIBLE。 ## 语法格式 创建表。 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ CHARACTER SET | CHARSET charset ] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ]) [ AUTO_INCREMENT [ = ] value ] [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMMENT {=| } 'text' ]; ``` * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED ALWAYS AS ( generation_expr ) [STORED] | AUTO_INCREMENT | UNIQUE [KEY] index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中列的压缩可选项compress\_mode为: ``` { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } ``` * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { { column_name [ ( length ) ] | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中like选项like\_option为: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | PARTITION | RELOPTIONS | ALL } ``` * 其中索引参数index\_parameters为: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## 参数说明 * **UNLOGGED** 如果指定此关键字,则创建的表为非日志表。在非日志表中写入的数据不会被写入到预写日志中,这样就会比普通表快很多。但是非日志表在冲突、执行操作系统重启、强制重启、切断电源操作或异常关机后会被自动截断,会造成数据丢失的风险。非日志表中的内容也不会被复制到备服务器中。在非日志表中创建的索引也不会被自动记录。 使用场景:非日志表不能保证数据的安全性,用户应该在确保数据已经做好备份的前提下使用,例如系统升级时进行数据的备份。 故障处理:当异常关机等操作导致非日志表上的索引发生数据丢失时,用户应该对发生错误的索引进行重建。 * **GLOBAL | LOCAL** 创建临时表时可以在TEMP或TEMPORARY前指定GLOBAL或LOCAL关键字。如果指定GLOBAL关键字,openGauss会创建全局临时表,否则openGauss会创建本地临时表。 * **TEMPORARY | TEMP** 如果指定TEMP或TEMPORARY关键字,则创建的表为临时表。临时表分为全局临时表和本地临时表两种类型。创建临时表时如果指定GLOBAL关键字则为全局临时表,否则为本地临时表。 全局临时表的元数据对所有会话可见,会话结束后元数据继续存在。会话与会话之间的用户数据、索引和统计信息相互隔离,每个会话只能看到和更改自己提交的数据。全局临时表有两种模式:一种是基于会话级别的(ON COMMIT PRESERVE ROWS), 当会话结束时自动清空用户数据;一种是基于事务级别的(ON COMMIT DELETE ROWS), 当执行commit或rollback时自动清空用户数据。建表时如果没有指定ON COMMIT选项,则缺省为会话级别。与本地临时表不同,全局临时表建表时可以指定非pg\_temp\_开头的schema。 本地临时表只在当前会话可见,本会话结束后会自动删除。因此,在除当前会话连接的数据库节点故障时,仍然可以在当前会话上创建和使用临时表。由于临时表只在当前会话创建,对于涉及对临时表操作的DDL语句,会产生DDL失败的报错。因此,建议DDL语句中不要对临时表进行操作。TEMP和TEMPORARY等价。 > \[!TIP]须知 > > * 本地临时表通过每个会话独立的以pg\_temp开头的schema来保证只对当前会话可见,因此,不建议用户在日常操作中手动删除以pg\_temp、pg\_toast\_temp开头的schema。 > * 如果建表时不指定TEMPORARY/TEMP关键字,而指定表的schema为当前会话的pg\_temp\_开头的schema,则此表会被创建为临时表。 > * ALTER/DROP全局临时表和索引,如果其它会话正在使用它,禁止操作(ALTER INDEX index\_name REBUILD除外)。 > * 全局临时表的DDL只会影响当前会话的用户数据和索引。例如truncate、reindex、analyze只对当前会话有效。 > * 全局临时表功能可以通过设置GUC参数max\_active\_global\_temporary\_table控制是否启用。如果max\_active\_global\_temporary\_table=0,关闭全局临时表功能。 > * 临时表只对当前会话可见,因此不支持与\parallel on并行执行一起使用。 > * 临时表不支持主备切换。 > * 全局临时表不响应自动清理,在长链接场景使用时尽量使用on commit delete rows的全局临时表,或定期手动执行vacuum,否则可能导致clog日志不回收。 * **IF NOT EXISTS** 如果已经存在相同名称的表,不会报出错误,而会发出通知,告知通知此表已存在。 * **table\_name** 要创建的表名。 > \[!TIP]须知 > > * 物化视图的一些处理逻辑会通过表名的前缀来识别是不是物化视图日志表和物化视图关联表,因此,用户不要创建表名以mlog\_或matviewmap\_为前缀的表,否则会影响此表的一些功能。 * **column\_name** 新表中要创建的字段名。 * **constraint\_name** 建表时指定的约束名称。 > \[!TIP]须知 > > 在B模式数据库下(即sql\_compatibility = 'B')constraint\_name为可选项,在其他模式数据库下,必须加上constraint\_name。 * **index\_name** 索引名。 > \[!TIP]须知 > > * index\_name仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 对于外键约束,constraint\_name和index\_name同时指定时,索引名为constraint\_name。 > * 对于唯一键约束,constraint\_name和index\_name同时指定时,索引名以index\_name。 * **USING method** 指定创建索引的方法。 取值范围参考[参数说明](create_index.md)中的USING method。 > \[!TIP]须知 > > * USING method仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 在B模式下,未指定USING method时,对于Astore的存储方式,默认索引方法为btree;对于Ustore的存储方式,默认索引方法为ubtree。 * **ASC | DESC** ASC表示指定按升序排序(默认)。DESC指定按降序排序。 > \[!TIP]须知 > > ASC|DESC只在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库不支持。 * **expression** > \[!TIP]须知 > > 表达式索引只在B模式数据库下支持(即sql\_compatibility = 'B'),其他模式数据库不支持。 * **data\_type** 字段的数据类型。 * **compress\_mode** 表字段的压缩选项。该选项指定表字段优先使用的压缩算法。行存表不支持压缩。 取值范围:DELTA、PREFIX、DICTIONARY、NUMSTR、NOCOMPRESS * DELTA压缩仅支持长度为1-8字节的数据类型(0 < pg\_type.typlen <= 8)。 * PREFIX、NUMSTR压缩仅支持变长数据类型(pg\_type.typlen = -1)和NULL结尾的C字符串(pg\_type.typlen = -2)。 * 该压缩选项与列存表自适应压缩算法无关,后者为列存表内部数据存储采用的压缩算法,不支持用户指定。 * **CHARACTER SET | CHARSET charset** 只在B模式数据库下(即sql\_compatibility = 'B')支持该语法,其他模式数据库不支持。指定表字段的字符集,单独指定时会将字段的字符序设置为指定的字符集的默认字符序。 * **COLLATE collation** COLLATE子句指定列的排序规则(字符序)(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。对于B模式数据库下(即sql\_compatibility = 'B')还支持utf8mb4\_bin、utf8mb4\_general\_ci、utf8mb4\_unicode\_ci、binary字符序。 > \[!NOTE]说明 > > * 仅字符类型支持指定字符集,指定为binary字符集或字符序实际是将字符类型转化为对应的二进制类型,若类型映射不存在则报错。当前仅有TEXT类型转化为BLOB的映射。 > * 除binary字符集和字符序外,当前仅支持指定与数据库编码相同的字符集。 > * 未显式指定字段字符集或字符序时,若指定了表的默认字符集或字符序,字段字符集和字符序将从表上继承。若表的默认字符集或字符序不存在,当b\_format\_behavior\_compat\_options = 'default\_collation'时,字段的字符集和字符序将继承当前数据库的字符集及其对应的默认字符序。 **表 1** B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍 * **LIKE source\_table \[ like\_option ... ]** LIKE子句声明一个表,新表自动从这个表中继承所有字段名及其数据类型和非空约束。 新表与源表之间在创建动作完毕之后是完全无关的。在源表做的任何修改都不会传播到新表中,并且也不可能在扫描源表的时候包含新表的数据。 被复制的列和约束并不使用相同的名称进行融合。如果明确的指定了相同的名称或者在另外一个LIKE子句中,将会报错。 * 源表上的字段缺省表达式只有在指定INCLUDING DEFAULTS时,才会复制到新表中。缺省是不包含缺省表达式的,即新表中的所有字段的缺省值都是NULL。 * 源表上的CHECK约束仅在指定INCLUDING CONSTRAINTS时,会复制到新表中,而其他类型的约束永远不会复制到新表中。非空约束总是复制到新表中。此规则同时适用于表约束和列约束。 * 如果指定了INCLUDING INDEXES,则源表上的索引也将在新表上创建,默认不建立索引。 * 如果指定了INCLUDING STORAGE,则复制列的STORAGE设置会复制到新表中,默认情况下不包含STORAGE设置。 * 如果指定了INCLUDING COMMENTS,则源表列、约束和索引的注释会复制到新表中。默认情况下,不复制源表的注释。 * 如果指定了INCLUDING PARTITION,则源表的分区定义会复制到新表中,同时新表将不能再使用PARTITION BY子句。默认情况下,不拷贝源表的分区定义。如果源表上带有索引,可以使用INCLUDING PARTITION INCLUDING INDEXES语法实现。如果对分区表只使用INCLUDING INDEXES,目标表定义将是普通表,但是索引是分区索引,最后结果会报错,因为普通表不支持分区索引。 * 如果指定了INCLUDING RELOPTIONS,则源表的存储参数(即源表的WITH子句)会复制到新表中。默认情况下,不复制源表的存储参数。 * INCLUDING ALL包含了INCLUDING DEFAULTS、INCLUDING CONSTRAINTS、INCLUDING INDEXES、INCLUDING STORAGE、INCLUDING COMMENTS、INCLUDING PARTITION和INCLUDING RELOPTIONS的内容。 > \[!TIP]须知 > > * 如果源表包含serial、bigserial、smallserial、largeserial类型,或者源表字段的默认值是sequence,且sequence属于源表(通过CREATE SEQUENCE ... OWNED BY创建),这些Sequence不会关联到新表中,新表中会重新创建属于自己的sequence。这和之前版本的处理逻辑不同。如果用户希望源表和新表共享Sequence,需要首先创建一个共享的Sequence(避免使用OWNED BY),并配置为源表字段默认值,这样创建的新表会和源表共享该Sequence。 > * 不建议将其他表私有的Sequence配置为源表字段的默认值,尤其是其他表只分布在特定的NodeGroup上,这可能导致CREATE TABLE ... LIKE执行失败。另外,如果源表配置其他表私有的Sequence,当该表删除时Sequence也会连带删除,这样源表的Sequence将不可用。如果用户希望多个表共享Sequence,建议创建共享的Sequence。 > * 对于分区表EXCLUDING,需要配合INCLUDING ALL使用,如INCLUDING ALL EXCLUDING DEFAULTS,除源分区表的DEFAULTS,其它全包含。 * **AUTO\_INCREMENT \[ = ] value** 这个子句为自动增长列指定一个初始值,value必须为正整数,不得超过2127-1。 > \[!TIP]须知 > > 该子句仅在参数sql\_compatibility=B时有效。 * **WITH ( { storage\_parameter = value } \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。用于表的WITH子句还可以包含OIDS=FALSE表示不分配OID。 > \[!NOTE]说明 > > 使用任意精度类型Numeric定义列时,建议指定精度p以及刻度s。在不指定精度和刻度时,会按输入的显示出来。 参数的详细描述如下所示。 * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数对于列存表没有意义。 取值范围:10~100 * ORIENTATION 指定表数据的存储方式,即行存方式、列存方式,该参数设置成功后就不再支持修改。 取值范围: * ROW,表示表的数据将以行式存储。 行存储适合于OLTP业务,适用于点查询或者增删操作较多的场景。 * COLUMN,表示表的数据将以列式存储。 列存储适合于数据仓库业务,此类型的表上会做大量的汇聚计算,且涉及的列操作较少。 默认值: 若指定表空间为普通表空间,默认值为ROW。 * STORAGE\_TYPE 指定存储引擎类型,该参数设置成功后就不再支持修改。 取值范围: * USTORE,表示表支持Inplace-Update存储引擎。 * ASTORE,表示表支持Append-Only存储引擎。 默认值: 不指定表时,默认是Append-Only存储。 * INIT\_TD 创建Ustore表时,指定初始化的TD个数,该参数只在创建Ustore表时才能设置生效。 取值范围:2~128,默认值为4。 * COMPRESSION 指定表数据的压缩级别,它决定了表数据的压缩比以及压缩时间。一般来讲,压缩级别越高,压缩比也越大,压缩时间也越长;反之亦然。实际压缩比取决于加载的表数据的分布特征。行存表默认增加COMPRESSION=NO字段。 取值范围: 列存表的有效值为YES/NO/LOW/MIDDLE/HIGH,默认值为LOW。 * COMPRESSLEVEL 指定表数据同一压缩级别下的不同压缩水平,它决定了同一压缩级别下表数据的压缩比以及压缩时间。对同一压缩级别进行了更加详细的划分,为用户选择压缩比和压缩时间提供了更多的空间。总体来讲,此值越大,表示同一压缩级别下压缩比越大,压缩时间越长;反之亦然。 取值范围:0~3,默认值为0。 * COMPRESSTYPE 行存表参数,设置行存表压缩算法。1代表pglz算法(不推荐使用),2代表zstd算法,3代表pgzstd算法(目前暂不支持),4代表zlib算法,默认不压缩。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。(仅支持Astore和Ustore下的普通表和分区表) 取值范围:0~4,默认值为0。 * COMPRESS\_LEVEL 行存表参数,设置行存表压缩算法等级,仅当COMPRESSTYPE为2或4时生效。压缩等级越高,表的压缩效果越好,表的访问速度越慢。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:-31~31,默认值为0。 * COMPRESS\_CHUNK\_SIZE 行存表参数,设置行存表压缩chunk块大小,仅当COMPRESSTYPE不为0时生效。chunk数据块越小,预期能达到的压缩效果越好,同时数据越离散,影响表的访问速度。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:与页面大小有关。在页面大小为8k场景,取值范围为:512、1024、2048、4096。 默认值:4096 * COMPRESS\_PREALLOC\_CHUNKS 行存表参数,设置行存表压缩chunk块预分配数量。预分配数量越大,表的压缩率相对越差,离散度越小,访问性能越好。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:0~7,默认值为0。 * 当COMPRESS\_CHUNK\_SIZE为512和1024时,支持预分配设置最大为7。 * 当COMPRESS\_CHUNK\_SIZE为2048时,支持预分配设置最大为3。 * 当COMPRESS\_CHUNK\_SIZE为4096时,支持预分配设置最大为1。 * COMPRESS\_BYTE\_CONVERT 行存表参数,设置行存表压缩字节转换预处理,仅当COMPRESSTYPE不为0时生效。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:布尔值,默认关闭。 * COMPRESS\_DIFF\_CONVERT 行存表参数,设置行存表压缩字节差分预处理。只能与compress\_byte\_convert一起使用。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:布尔值,默认关闭。 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000,默认60000。 * PARTIAL\_CLUSTER\_ROWS 指定了在数据加载过程中进行将局部聚簇存储的记录数目。该参数只对列存表有效。 取值范围:大于等于MAX\_BATCHROW,建议取值为MAX\_BATCHROW的整数倍。 * DELTAROW\_THRESHOLD 指定列存表导入时小于多少行的数据进入delta表,只在GUC参数enable\_delta\_store开启时生效。该参数只对列存表有效。 取值范围:0~9999,默认值为100 * segment 使用段页式的方式存储。本参数仅支持行存表。不支持列存表、临时表、unlog表。不支持Ustore存储引擎。 取值范围:on/off 默认值:off * dek\_cipher 透明数据加密密钥的密文。当开启enable\_tde选项时会自动申请创建,用户不可单独指定。通过密钥轮转功能可以对密钥进行更新。 取值范围:字符串。 默认值:不开启加密时默认为空。 * hasuids 参数开启:更新表元组时,为元组分配表级唯一标识id。 取值范围:on/off。 默认值:off。 * collate 在B模式数据库下(即sql\_compatibility = 'B')用于记录表的默认字符序,一般只用于内部存储和导入导出,不推荐用户指定或修改。 取值范围:B模式数据库中独立支持的字符序的oid。 默认值:0。 * AUTOVACUUM\_ENABLED 需数据库打开autovacuum功能时,单独设置此表是否进行autovacuum。 取值范围:布尔值,默认开启。 * AUTOVACUUM、AUTOANALYZE相关参数 参数有:AUTOVACUUM\_VACUUM\_THREASHOLD、AUTOVACUUM\_ANALYZE\_THREASHOLD、AUTOVACUUM\_VACUUM\_COST\_DELAY、AUTOVACUUM\_VACUUM\_COST\_LIMIT、AUTOVACUUM\_FREEZE\_MIN\_AGE、AUTOVACUUM\_FREEZE\_MAX\_AGE、AUTOVACUUM\_FREEZE\_TABLE\_AGE、AUTOVACUUM\_VACUUM\_SCALE\_FACTOR、AUTOVACUUM\_ANALYZE\_SCALE\_FACTOR 单独设置此表的autovacuum、autoanalyze相关功能参数配置,与同名GUC功能相同,优先生效此处的配置。 取值范围:与同名GUC相同。 * vacuum\_truncate 参数开启:VACUUM/AUTOVACUUM过程中尝试截断表末尾的空页面,并允许将截断页的磁盘空间返回到操作系统。仅非段页式的Astore表支持该选项。 取值范围:on/off。 默认值:on。 * **WITHOUT OIDS** 等价于WITH(OIDS=FALSE)的语法 * **ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }** ON COMMIT选项决定在事务中执行创建临时表操作,当事务提交时,此临时表的后续操作。有以下三个选项,当前支持PRESERVE ROWS和DELETE ROWS选项。 * PRESERVE ROWS(缺省值):提交时不对临时表做任何操作,临时表及其表数据保持不变。 * DELETE ROWS:提交时删除临时表中数据。 * DROP:提交时删除此临时表。只支持本地临时表,不支持全局临时表。 * **COMPRESS | NOCOMPRESS** 创建新表时,需要在CREATE TABLE语句中指定关键字COMPRESS,这样,当对该表进行批量插入时就会触发压缩特性。该特性会在页范围内扫描所有元组数据,生成字典、压缩元组数据并进行存储。指定关键字NOCOMPRESS则不对表进行压缩。行存表不支持压缩。 缺省值:NOCOMPRESS,即不对元组数据进行压缩。 * **TABLESPACE tablespace\_name** 创建新表时指定此关键字,表示新表将要在指定表空间内创建。如果没有声明,将使用默认表空间。 * **COMMNET {=| } text** 创建新表时指定此关键字,表示新表的注释内容。如果没有声明,则不创建注释。 * **CONSTRAINT constraint\_name** 列约束或表约束的名称。可选的约束子句用于声明约束,新行或者更新的行必须满足这些约束才能成功插入或更新。 定义约束有两种方法: * 列约束:作为一个列定义的一部分,仅影响该列。 * 表约束:不和某个列绑在一起,可以作用于多个列。 * **NOT NULL** 字段值不允许为NULL。 * **NULL** 字段值允许为NULL ,这是缺省值。 这个子句只是为和非标准SQL数据库兼容。不建议使用。 * **CHECK ( expression )** CHECK约束声明一个布尔表达式,每次要插入的新行或者要更新的行的新值必须使表达式结果为真或未知才能成功,否则会抛出一个异常并且不会修改数据库。 声明为字段约束的检查约束应该只引用该字段的数值,而在表约束里出现的表达式可以引用多个字段。 > \[!NOTE]说明 > > expression表达式中,如果存在“<>NULL”或“!=NULL”,这种写法是无效的,需要写成“is NOT NULL”。 * **DEFAULT default\_expr** DEFAULT子句给字段指定缺省值。该数值可以是任何不含变量的表达式(不允许使用子查询和对本表中的其他字段的交叉引用)。缺省表达式的数据类型必须和字段类型匹配。 缺省表达式将被用于任何未声明该字段数值的插入操作。如果没有指定缺省值则缺省值为NULL 。 * **GENERATED ALWAYS AS ( generation\_expr ) \[STORED]** 该子句将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,STORED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > ``` >- STORED关键字可省略,与不省略STORED语义相同。 ``` > * 生成表达式不能以任何方式引用当前行以外的其他数据。生成表达式不能引用其他生成列,不能引用系统列。生成表达式不能返回结果集,不能使用子查询,不能使用聚集函数,不能使用窗口函数。生成表达式调用的函数只能是不可变(IMMUTABLE)函数。 > \>- 不能为生成列指定默认值。 > * 生成列不能作为分区键的一部分。 > \>- 生成列不能和ON UPDATE约束字句的CASCADE,SET NULL,SET DEFAULT动作同时指定。生成列不能和ON DELETE约束字句的SET NULL,SET DEFAULT动作同时指定。 > \>- 修改和删除生成列的方法和普通列相同。删除生成列依赖的普通列,生成列被自动删除。不能改变生成列所依赖的列的类型。 > \>- 生成列不能被直接写入。在INSERT或UPDATE命令中, 不能为生成列指定值, 但是可以指定关键字DEFAULT。 > \>- 生成列的权限控制和普通列一样。 > \>- 列存表、内存表MOT不支持生成列。外表中仅postgres\_fdw支持生成列。 * **AUTO\_INCREMENT** 该关键字将字段指定为自动增长列。 若在插入时不指定此列的值(或指定此列的值为0、NULL、DEFAULT),此列的值将由自增计数器自动增长得到。 若插入或更新此列为一个大于当前自增计数器的值,执行成功后,自增计数器将刷新为此值。 自增初始值由“AUTO\_INCREMENT \[ = ] value”子句设置,若不设置,默认为1。 > \[!NOTE]说明 > > * 仅在参数sql\_compatibility=B时可以指定自动增长列。 > * 自动增长列数据类型只能为整数类型、4字节或8字节浮点类型、布尔类型。 > * 每个表只能有一个自动增长列。 > * 自动增长列必须是主键约束或唯一约束的第一个字段。 > * 自动增长列不能指定DEFAULT缺省值。 > \>- CHECK约束的表达式中不能含有自动增长列。 > * 可以指定自动增长列允许NULL,若不指定,默认自动增长列含有NOT NULL约束。 > * 含有自动增长列的表创建时,会创建一个依赖于此列的序列作为自增计数器,不允许通过序列相关功能修改 或删除此序列,可以查看序列的值。 > * 本地临时表中的自动增长列不会创建序列。 > * 自动增长列不支持列式存储。 > * 自增计数器自增和刷新操作不会回滚。 * **\[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset** 仅在sql\_compatibility='B'时支持该语法。指定表的默认字符集,单独指定时会将表的默认字符序设置为指定的字符集的默认字符序。 * **\[DEFAULT] COLLATE \[ = ] default\_collation** 仅在sql\_compatibility='B'时支持该语法。指定表的默认字符序,单独指定时会将表的默认字符集设置为指定的字符序对应的字符集。字符序参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](#table8163190152)。 > \[!NOTE]说明 > 未显式指定表的字符集或字符序时,若指定了模式的默认字符集或字符序,表字符集和字符序将从模式上继承。若模式的默认字符集或字符序不存在,当b\_format\_behavior\_compat\_options = 'default\_collation'时,表的字符集和字符序将继承当前数据库的字符集及其对应的默认字符序。 * **UNIQUE \[KEY] index\_parameters** **UNIQUE ( column\_name \[ ( length ) ] \[, ... ] ) index\_parameters** UNIQUE约束表示表里的一个字段或多个字段的组合必须在全表范围内唯一。 对于唯一约束,NULL被认为是互不相等的。 UNIQUE KEY只能在sql\_compatibility='B'时使用,与UNIQUE语义相同。 column\_name(length)是前缀键,详见:[前缀键说明](create_index_1.md#前缀键说明)。 * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** 主键约束声明表中的一个或者多个字段只能包含唯一的非NULL值。 一个表只能声明一个主键。 * **REFERENCES reftable \[ ( refcolum ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (column constraint)** **FOREIGN KEY ( column\_name \[, ... ] ) REFERENCES reftable \[ ( refcolumn \[, ... ] ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (table constraint)** 外键约束要求新表中一列或多列构成的组应该只包含、匹配被参考表中被参考字段值。若省略refcolum,则将使用reftable的主键。被参考列应该是被参考表中的唯一字段或主键。外键约束不能被定义在临时表和永久表之间。 参考字段与被参考字段之间存在三种类型匹配,分别是: * MATCH FULL:不允许一个多字段外键的字段为NULL,除非全部外键字段都是NULL。 * MATCH SIMPLE(缺省):允许任意外键字段为NULL。 * MATCH PARTIAL:目前暂不支持。 另外,当被参考表中的数据发生改变时,某些操作也会在新表对应字段的数据上执行。ON DELETE子句声明当被参考表中的被参考行被删除时要执行的操作。ON UPDATE子句声明当被参考表中的被参考字段数据更新时要执行的操作。对于ON DELETE子句、ON UPDATE子句的可能动作: * NO ACTION(缺省):删除或更新时,创建一个表明违反外键约束的错误。若约束可推迟,且若仍存在任何引用行,那这个错误将会在检查约束的时候产生。 * RESTRICT:删除或更新时,创建一个表明违反外键约束的错误。与NO ACTION相同,只是动作不可推迟。 * CASCADE:删除新表中任何引用了被删除行的行,或更新新表中引用行的字段值为被参考字段的新值。 * SET NULL:设置引用字段为NULL。 * SET DEFAULT:设置引用字段为它们的缺省值。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 * * **DEFERRABLE | NOT DEFERRABLE** 这两个关键字设置该约束是否可推迟。一个不可推迟的约束将在每条命令之后马上检查。可推迟约束可以推迟到事务结尾使用SET CONSTRAINTS命令检查。缺省是NOT DEFERRABLE。目前,UNIQUE约束、主键约束、外键约束可以接受这个子句。所有其他约束类型都是不可推迟的。 > \[!NOTE]说明Ustore表不支持 DEFERRABLE 以及 INITIALLY DEFERRED 约束。 * **COMMENT text** 注释。 * **VISIBLE | INVISIBLE** 指定索引是否可见,如果没有声明则默认为VISIBLE。 * **PARTIAL CLUSTER KEY** 局部聚簇存储,列存表导入数据时按照指定的列(单列或多列),进行局部排序。 * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** 如果约束是可推迟的,则这个子句声明检查约束的缺省时间。 * 如果约束是INITIALLY IMMEDIATE(缺省),则在每条语句执行之后就立即检查它; * 如果约束是INITIALLY DEFERRED ,则只有在事务结尾才检查它。 约束检查的时间可以用SET CONSTRAINTS命令修改。 * **USING INDEX TABLESPACE tablespace\_name** 为UNIQUE或PRIMARY KEY约束相关的索引声明一个表空间。如果没有提供这个子句,这个索引将在default\_tablespace中创建,如果default\_tablespace为空,将使用数据库的缺省表空间。 * **ENCRYPTION\_TYPE = encryption\_type\_value** 为ENCRYPTED WITH约束中的加密类型,encryption\_type\_value的值为\[ DETERMINISTIC | RANDOMIZED ] ## 示例 ``` --创建简单的表。 openGauss=# CREATE TABLE tpcds.warehouse_t1 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); openGauss=# CREATE TABLE tpcds.warehouse_t2 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60), W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` ``` --创建表,并指定W_STATE字段的缺省值为GA。 openGauss=# CREATE TABLE tpcds.warehouse_t3 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) DEFAULT 'GA', W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建表,并在事务结束时检查W_WAREHOUSE_NAME字段是否有重复。 openGauss=# CREATE TABLE tpcds.warehouse_t4 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE DEFERRABLE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` ``` --创建一个带有70%填充因子的表。 openGauss=# CREATE TABLE tpcds.warehouse_t5 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), UNIQUE(W_WAREHOUSE_NAME) WITH(fillfactor=70) ); --或者用下面的语法。 openGauss=# CREATE TABLE tpcds.warehouse_t6 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH(fillfactor=70); --创建表,并指定该表数据不写入预写日志。 openGauss=# CREATE UNLOGGED TABLE tpcds.warehouse_t7 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建表临时表。 openGauss=# CREATE TEMPORARY TABLE warehouse_t24 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建本地临时表,并指定提交事务时删除该临时表数据。 openGauss=# CREATE TEMPORARY TABLE warehouse_t25 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) ON COMMIT DELETE ROWS; --创建全局临时表,并指定会话结束时删除该临时表数据。当前Ustore存储引擎不支持全局临时表。 openGauss=# CREATE GLOBAL TEMPORARY TABLE gtt1 ( ID INTEGER NOT NULL, NAME CHAR(16) NOT NULL, ADDRESS VARCHAR(50) , POSTCODE CHAR(6) ) ON COMMIT PRESERVE ROWS; --创建表时,不希望因为表已存在而报错。 openGauss=# CREATE TABLE IF NOT EXISTS tpcds.warehouse_t8 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建普通表空间。 openGauss=# CREATE TABLESPACE DS_TABLESPACE1 RELATIVE LOCATION 'tablespace/tablespace_1'; --创建表时,指定表空间。 openGauss=# CREATE TABLE tpcds.warehouse_t9 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) TABLESPACE DS_TABLESPACE1; --创建表时,单独指定W_WAREHOUSE_NAME的索引表空间。 openGauss=# CREATE TABLE tpcds.warehouse_t10 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE USING INDEX TABLESPACE DS_TABLESPACE1, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` ``` --创建一个有主键约束的表。 openGauss=# CREATE TABLE tpcds.warehouse_t11 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ---或是用下面的语法,效果完全一样。 openGauss=# CREATE TABLE tpcds.warehouse_t12 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), PRIMARY KEY(W_WAREHOUSE_SK) ); --或是用下面的语法,指定约束的名称。 openGauss=# CREATE TABLE tpcds.warehouse_t13 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CSTR_KEY1 PRIMARY KEY(W_WAREHOUSE_SK) ); --创建一个有复合主键约束的表。 openGauss=# CREATE TABLE tpcds.warehouse_t14 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CSTR_KEY2 PRIMARY KEY(W_WAREHOUSE_SK, W_WAREHOUSE_ID) ); --创建列存表。 openGauss=# CREATE TABLE tpcds.warehouse_t15 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH (ORIENTATION = COLUMN); --创建局部聚簇存储的列存表。 openGauss=# CREATE TABLE tpcds.warehouse_t16 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), PARTIAL CLUSTER KEY(W_WAREHOUSE_SK, W_WAREHOUSE_ID) ) WITH (ORIENTATION = COLUMN); --定义一个带压缩的列存表。 openGauss=# CREATE TABLE tpcds.warehouse_t17 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH (ORIENTATION = COLUMN, COMPRESSION=HIGH); --定义一个检查列约束。 openGauss=# CREATE TABLE tpcds.warehouse_t19 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY CHECK (W_WAREHOUSE_SK > 0), W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) CHECK (W_WAREHOUSE_NAME IS NOT NULL), W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); openGauss=# CREATE TABLE tpcds.warehouse_t20 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) CHECK (W_WAREHOUSE_NAME IS NOT NULL), W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CONSTR_KEY2 CHECK(W_WAREHOUSE_SK > 0 AND W_WAREHOUSE_NAME IS NOT NULL) ); --创建一个有外键约束的表。 openGauss=# CREATE TABLE tpcds.city_t23 ( W_CITY VARCHAR(60) PRIMARY KEY, W_ADDRESS TEXT ); openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) REFERENCES tpcds.city_t23(W_CITY), W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --或是用下面的语法,效果完全一样。 openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , FOREIGN KEY(W_CITY) REFERENCES tpcds.city_t23(W_CITY) ); --或是用下面的语法,指定约束的名称。 openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , CONSTRAINT W_FORE_KEY1 FOREIGN KEY(W_CITY) REFERENCES tpcds.city_t23(W_CITY) ); --向tpcds.warehouse_t19表中增加一个varchar列。 ``` ``` openGauss=# ALTER TABLE tpcds.warehouse_t19 ADD W_GOODS_CATEGORY varchar(30); --给tpcds.warehouse_t19表增加一个检查约束。 openGauss=# ALTER TABLE tpcds.warehouse_t19 ADD CONSTRAINT W_CONSTR_KEY4 CHECK (W_STATE IS NOT NULL); --在一个操作中改变两个现存字段的类型。 openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY TYPE varchar(80), ALTER COLUMN W_STREET_NAME TYPE varchar(100); --此语句与上面语句等效。 openGauss=# ALTER TABLE tpcds.warehouse_t19 MODIFY (W_GOODS_CATEGORY varchar(30), W_STREET_NAME varchar(60)); --给一个已存在字段添加非空约束。 openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY SET NOT NULL; --移除已存在字段的非空约束。 openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY DROP NOT NULL; --如果列存表中还未指定局部聚簇,向在一个列存表中添加局部聚簇列。 openGauss=# ALTER TABLE tpcds.warehouse_t17 ADD PARTIAL CLUSTER KEY(W_WAREHOUSE_SK); --查看约束的名称,并删除一个列存表中的局部聚簇列。 openGauss=# \d+ tpcds.warehouse_t17 Table "tpcds.warehouse_t17" Column | Type | Modifiers | Storage | Stats target | Description -------------------+-----------------------+-----------+----------+--------------+------------- w_warehouse_sk | integer | not null | plain | | w_warehouse_id | character(16) | not null | extended | | w_warehouse_name | character varying(20) | | extended | | w_warehouse_sq_ft | integer | | plain | | w_street_number | character(10) | | extended | | w_street_name | character varying(60) | | extended | | w_street_type | character(15) | | extended | | w_suite_number | character(10) | | extended | | w_city | character varying(60) | | extended | | w_county | character varying(30) | | extended | | w_state | character(2) | | extended | | w_zip | character(10) | | extended | | w_country | character varying(20) | | extended | | w_gmt_offset | numeric(5,2) | | main | | Partial Cluster : "warehouse_t17_cluster" PARTIAL CLUSTER KEY (w_warehouse_sk) Has OIDs: no Location Nodes: ALL DATANODES Options: compression=no, version=0.12 openGauss=# ALTER TABLE tpcds.warehouse_t17 DROP CONSTRAINT warehouse_t17_cluster; --将表移动到另一个表空间。 openGauss=# ALTER TABLE tpcds.warehouse_t19 SET TABLESPACE PG_DEFAULT; --创建模式joe。 openGauss=# CREATE SCHEMA joe; --将表移动到另一个模式中。 openGauss=# ALTER TABLE tpcds.warehouse_t19 SET SCHEMA joe; --重命名已存在的表。 openGauss=# ALTER TABLE joe.warehouse_t19 RENAME TO warehouse_t23; --从warehouse_t23表中删除一个字段。 openGauss=# ALTER TABLE joe.warehouse_t23 DROP COLUMN W_STREET_NAME; --创建带INVISIBLE唯一索引的表,需要在B兼容性数据库下 openGauss=# CREATE TABLE tpcds.warehouse_t26 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , UNIQUE uni_t26 (W_WAREHOUSE_SK) INVISIBLE ) WITH(fillfactor=70); --删除表空间、模式joe和模式表warehouse。 openGauss=# DROP TABLE tpcds.warehouse_t1; openGauss=# DROP TABLE tpcds.warehouse_t2; openGauss=# DROP TABLE tpcds.warehouse_t3; openGauss=# DROP TABLE tpcds.warehouse_t4; openGauss=# DROP TABLE tpcds.warehouse_t5; openGauss=# DROP TABLE tpcds.warehouse_t6; openGauss=# DROP TABLE tpcds.warehouse_t7; openGauss=# DROP TABLE tpcds.warehouse_t8; openGauss=# DROP TABLE tpcds.warehouse_t9; openGauss=# DROP TABLE tpcds.warehouse_t10; openGauss=# DROP TABLE tpcds.warehouse_t11; openGauss=# DROP TABLE tpcds.warehouse_t12; openGauss=# DROP TABLE tpcds.warehouse_t13; openGauss=# DROP TABLE tpcds.warehouse_t14; openGauss=# DROP TABLE tpcds.warehouse_t15; openGauss=# DROP TABLE tpcds.warehouse_t16; openGauss=# DROP TABLE tpcds.warehouse_t17; openGauss=# DROP TABLE tpcds.warehouse_t18; openGauss=# DROP TABLE tpcds.warehouse_t20; openGauss=# DROP TABLE tpcds.warehouse_t21; openGauss=# DROP TABLE tpcds.warehouse_t22; openGauss=# DROP TABLE joe.warehouse_t23; openGauss=# DROP TABLE tpcds.warehouse_t24; openGauss=# DROP TABLE tpcds.warehouse_t25; openGauss=# DROP TABLE tpcds.warehouse_t26; openGauss=# DROP TABLESPACE DS_TABLESPACE1; openGauss=# DROP SCHEMA IF EXISTS joe CASCADE; ``` ## 相关链接 [ALTER TABLE](alter_table.md),[DROP TABLE](drop_table.md),[CREATE TABLESPACE](create_tablespace.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CREATE-TABLE.md --- # CREATE TABLE ## 功能描述 在当前数据库中创建一个新的空白表,该表由命令执行者所有。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 ## 语法格式 通过无括号like创建表。 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name LIKE source_table [ like_option [...] ] ``` * like后不能添加普通建表的额外可选语句。 * table前不能添加foreign选项,包括外表、mot表的创建。 * 默认复制源表的索引,若不希望复制索引,需要手动指定EXCLUDING INDEXES。 * 默认复制源分区表的分区,若不希望复制分区,需要手动指定EXCLUDING PARTITION。 * 默认复制字段的DEFAULT值,若不希望复制DEFAULT值,需要手动指定EXCLUDING DEFAULTS。 * 对于含索引的分区表,若只指定EXCLUDING PARTITION,由于默认复制分区,将会报错,因为普通表不支持分区索引。 * 只支持复制range分区表的分区,对于hash、list分区表,由于默认复制分区,会直接报错,需要手动指定EXCLUING PARTITION。二级分区只支持复制range-range分区,处理方法同上。 * 生成列语法支持忽略GENERATED ALWAYS。 * 大多数情况下,生成列表达式调用的函数只能是不可变(IMMUTABLE)函数,但是对于非IMMUTABLE的concat和concat\_ws函数,特定入参类型同样支持,这些类型包括BOOL,CHAR,NAME,INT1,INT2,INT4,INT8,INT16,TEXT,OID,CLOB,JSON,XML,UNKNOWN,VARCHAR,VARBIT,CSTRING,ANYSET,ANYENUM,JSONB,NVARCHAR2,YEAR,UINT1,UINT2,UINT4,UINT8。 创建表。 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ CHARACTER SET | CHARSET charset ] [BINARY | ASCII] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | table_indexclause | LIKE source_table [ like_option [...] ] } [, ... ]) [ create_option [ ...]] ``` * 其中create\_option为: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ create_table_option [[,] ...]] 除了WITH选项外允许输入多次同一种create_option,以最后一次的输入为准。 ``` * 其中create\_table\_option为: ``` [ AUTOEXTEND_SIZE [=] value ] [ AUTO_INCREMENT [=] value ] [ AVG_ROW_LENGTH [=] value ] [ [DEFAULT] { CHARSET | CHARACTER SET } [=] charset_name ] [ CHECKSUM [=] value ] [ [DEFAULT] COLLATE [=] collation_name ] [ COMMENT [=] 'text' ] [ COMPRESSION [=] compression_arg ] [ CONNECTION [=] 'connect_string' ] [ {DATA | INDEX} DIRECTORY [=] 'absolute path to directory' ] [ DELAY_KEY_WRITE [=] value ] [ ENCRYPTION [=] 'encryption_string' ] [ ENGINE [=] engine_name ] [ ENGINE_ATTRIBUTE [=] 'string' ] [ INSERT_METHOD [=] { NO | FIRST | LAST } ] [ KEY_BLOCK_SIZE [=] value ] [ MAX_ROWS [=] value ] [ MIN_ROWS [=] value ] [ PACK_KEYS [=] value ] [ PASSWORD [=] 'password' ] [ ROW_FORMAT [=] row_format_name ] [ START TRANSACTION ] [ SECONDARY_ENGINE_ATTRIBUTE [=] 'string' ] [ STATS_AUTO_RECALC [=] value ] [ STATS_PERSISTENT [=] value ] [ STATS_SAMPLE_PAGES [=] value ] [ TABLESPACE tablespace_name [STORAGE DISK] ] [ [TABLESPACE tablespace_name] STORAGE MEMORY ] [ UNION [=] (tbl_name[,tbl_name]...) ] 允许输入多次同一种create_table_option,以最后一次的输入为准。 ``` * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { { column_name | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PRIMARY KEY [ index_name ] [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) | COMMENT {=| } 'text' } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | [GENERATED ALWAYS] AS ( generation_expr ) [STORED] | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE [KEY] index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | [PRIMARY] KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 创建表上索引table\_indexclause: ```sql {[FULLTEXT] INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option]... ``` 该语法不支持CREATE FOREIGN TABLE (MOT表等) 创建。 * 其中参数index\_type为: ``` USING {BTREE | HASH | GIN | GIST | PSORT | UBTREE} ``` * 其中参数key\_part为: ``` {col_name[(length)] | (expr)} [ASC | DESC] ``` length为前缀索引。 * 其中参数index\_option为: ``` index_option:{ COMMENT 'string' | index_type | [ VISIBLE | INVISIBLE ] | [WITH PARSER NGRAM] } ``` COMMENT、index\_type、\[ VISIBLE | INVISIBLE ] 的顺序和数量任意,但相同字段仅最后一个值生效。WITH PARSER NGRAM 为FULLTEXT INDEX指定的ngram解析器,前提是索引必须指定关键字FULLTEXT,FULLTEXT 默认 WITH PARSER NGRAM。 * 其中like选项like\_option为: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | PARTITION | RELOPTIONS | ALL } ``` ## 参数说明 * **data\_type** 字段的数据类型。 对枚举类型ENUM,以及CHAR, CHARACTER, VARCHAR, TEXT等字符类型,创建表格时可使用关键字CHARSET或CHARACTER SET声明列字符集。目前该特性仅做语法支持,不实现功能。 * **column\_constraint** 字段的类型约束中,添加了mysql的ON UPDATE特性,归类于字段类型约束。与DEFAULT属性属于同类约束。该ON UPDATE属性用于,执行UPDATE操作timestamp字段为缺省时,则自动更新timestamp字段的时间截。如果更新字段的数据内容与原来的数据内容一致,则其他含有ON UPDATE的字段的时间截不会自动更新。 ```sql CREATE TABLE table_name(column_name timestamp ON UPDATE CURRENT_TIMESTAMP); ``` * **CHARACTER SET | CHARSET charset** 用于指定表字段的字符集,单独指定时会将字段的字符序设置为指定的字符集的默认字符序。支持ASCII和BINARY字符集。 * **COLLATE collation** COLLATE子句指定列的排序规则(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 对未被支持的排序规则,数据库将发出警告,并将该列设置为默认的排序规则。支持BINARY字符序。 * **{ \[DEFAULT] CHARSET | CHARACTER SET } \[=] charset\_name** 用于选择表所使用的字符集,单独指定时会将字段的字符序设置为指定的字符集的默认字符序。支持ASCII和BINARY字符集。 * **COLLATE \[=] collation\_name** 用于选择表所使用的排序规则,如果没有指定,则使用默认的排序规则。支持BINARY字符序。 * **ROW\_FORMAT \[=] row\_format\_name** 用于选择表所使用的行存储格式;目前该特性仅有语法支持,不实现功能。 * **AUTO\_INCREMENT** 该关键字将字段指定为自动增长列。自动增长列必须是某个索引的第一个字段。 若在插入时不指定此列的值(或指定此列的值为0、NULL、DEFAULT),此列的值将由自增计数器自动增长得到。 若插入或更新此列为一个大于当前自增计数器的值,执行成功后,自增计数器将刷新为此值。 自增初始值由“AUTO\_INCREMENT \[ = ] value”子句设置,若不设置,默认为1。 > \[!NOTE]说明 > > * 仅在参数sql\_compatibility=B时可以指定自动增长列。 > * 自动增长列数据类型只能为整数类型、4字节或8字节浮点类型。 > * 每个表只能有一个自动增长列。 > * 自动增长列必须是索引的第一个字段。 > * 自动增长列不能指定DEFAULT缺省值。 > * CHECK约束的表达式中不能含有自动增长列。 > * 可以指定自动增长列允许NULL,若不指定,默认自动增长列含有NOT NULL约束。 > * 含有自动增长列的表创建时,会创建一个依赖于此列的序列作为自增计数器,不允许通过序列相关功能修改或删除此序列,可以查看序列的值。 > * 本地临时表中的自动增长列不会创建序列。 > * 自动增长列不支持列式存储。 > * 自增计数器自增和刷新操作不会回滚。 > * 因精度问题,自增值较大时,FLOAT/DOUBLE类型自增后可能重复报错,可见文末示例。 * **BINARY** 该关键字将设置列的字符序为该列字符集对应的`_bin`字符序,如果对应字符集的`_bin`字符序不存在,则告警并忽略BINARY属性。比如列的字符集为`utf8`,则指定BINARY时,等价于设置列的字符序为`utf8_bin`。 * **ASCII** 该关键字将设置列的字符集为`latin1`,是`CHARACTER SET latin1`的缩写。 * **AUTOEXTEND\_SIZE \[=] value** 用于指定在表空间变满时扩展表空间大小;目前该特性仅有语法支持,不实现功能。参数的取值范围包括非负整数,小数,标识符,非负整数+标识符,小数+标识符。 * **AVG\_ROW\_LENGTH \[=] value** 用于指定表的平均行长度;目前该特性仅有语法支持,不实现功能。参数的取值范围包括非负整数,小数。 * **CHECKSUM \[=] value** 用于指定是否维护所有行的实时校验和;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **CONNECTION \[=] 'connect\_string'** 用于指定联合表的连接字符串;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **{DATA | INDEX} DIRECTORY \[=] 'absolute path to directory'** 用于指定表数据数据和索引的存储目录;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **DELAY\_KEY\_WRITE \[=] value** 用于指定是否延迟表的索引更新直到表关闭;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **ENCRYPTION \[=] 'encryption\_string'** 用于指定表启用或禁用页面级数据加密;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **ENGINE\_ATTRIBUTE \[=] 'string'** 用于指定主存储引擎的表属性;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **INSERT\_METHOD \[=] { NO | FIRST | LAST }** 用于指定应将行插入到的表;目前该特性仅有语法支持,不实现功能。参数的取值范围为NO,FIRST,LAST。 * **KEY\_BLOCK\_SIZE \[=] value** 用于指定索引键块的字节大小;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **MAX\_ROWS \[=] value** 用于指定计划在表中存储的最大行数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **MIN\_ROWS \[=] value** 用于指定计划在表中存储的最小行数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数。 * **PACK\_KEYS \[=] value** 用于指定控制压缩索引的方式;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **PASSWORD \[=] 'password'** 此选项未使用;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **SECONDARY\_ENGINE\_ATTRIBUTE \[=] 'string'** 用于指定辅助存储引擎的表属性;目前该特性仅有语法支持,不实现功能。参数的取值范围为任意字符串。 * **START TRANSACTION** 用于开启事务模式;目前该特性仅有语法支持,不实现功能。 * **STATS\_AUTO\_RECALC \[=] value** 用于指定是否自动重新计算表的持久统计信息;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **STATS\_PERSISTENT \[=] value** 用于指定是否为表启用持久统计信息;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数,DEFAULT。 * **STATS\_SAMPLE\_PAGES \[=] value** 用于指定估计索引列的基数和其他统计信息时要采样的索引页数;目前该特性仅有语法支持,不实现功能。参数的取值范围为非负整数,小数,十六进制数。 * **UNION \[=] (tbl\_name\[,tbl\_name]...)** 用于访问一组相同的表作为一个表;目前该特性仅有语法支持,不实现功能。 * **TABLESPACE tablespace\_name STORAGE DISK** 用于指定表存储在磁盘;目前该特性仅有语法支持,不实现功能。 * **\[TABLESPACE tablespace\_name] STORAGE MEMORY** 用于指定表存储在内存;目前该特性仅有语法支持,不实现功能。 ## 示例 ``` --创建表上索引 openGauss=# CREATE TABLE tpcds.warehouse_t24 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , key (W_WAREHOUSE_SK) , index idx_ID using btree (W_WAREHOUSE_ID) ); --创建表上组合索引、表达式索引、函数索引 openGauss=# CREATE TABLE tpcds.warehouse_t25 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , key using btree (W_WAREHOUSE_SK, W_WAREHOUSE_ID desc) , index idx_SQ_FT using btree ((abs(W_WAREHOUSE_SQ_FT))) , key idx_SK using btree ((abs(W_WAREHOUSE_SK)+1)) ); --创建带INVISIBLE普通索引的表 openGauss=# CREATE TABLE tpcds.warehouse_t26 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , index idx_ID using btree (W_WAREHOUSE_ID) INVISIBLE ); --包含index_option字段 openGauss=# create table test_option(a int, index idx_op using btree(a) comment 'idx comment'); ``` ``` --创建表格时对列指定字符集。 openGauss=# CREATE TABLE t_column_charset(c text CHARSET test_charset); WARNING: character set "test_charset" for type text is not supported yet. default value set CREATE TABLE --创建表格时对表格指定字符序。 openGauss=# CREATE TABLE t_table_collate(c text) COLLATE test_collation; WARNING: COLLATE for TABLE is not supported for current version. skipped CREATE TABLE --创建表格时对表格指定字符集。 openGauss=# CREATE TABLE t_table_charset(c text) CHARSET test_charset; WARNING: CHARSET for TABLE is not supported for current version. skipped CREATE TABLE --创建表格时对表格指定行记录格式。 openGauss=# CREATE TABLE t_row_format(c text) ROW_FORMAT test_row_format; WARNING: ROW_FORMAT for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定在表空间变满时扩展表空间大小。 openGauss=# CREATE TABLE t_autoextend_size(c text) AUTOEXTEND_SIZE 4M; WARNING: AUTOEXTEND_SIZE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表的平均行长度。 openGauss=# CREATE TABLE t_avg_row_length(c text) AVG_ROW_LENGTH 10; WARNING: AVG_ROW_LENGTH for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定是否维护所有行的实时校验和。 openGauss=# CREATE TABLE t_checksum(c text) CHECKSUM 0; WARNING: CHECKSUM for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定联合表的连接字符串。 openGauss=# CREATE TABLE t_connection(c text) CONNECTION 'connect_string'; WARNING: CONNECTION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表数据数据和索引的存储目录。 openGauss=# CREATE TABLE t_data_directory(c text) DATA DIRECTORY 'data_directory'; WARNING: DIRECTORY for TABLE is not supported for current version. skipped CREATE TABLE openGauss=# CREATE TABLE t_index_directory(c text) INDEX DIRECTORY 'index_directory'; WARNING: DIRECTORY for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定是否延迟表的索引更新直到表关闭。 openGauss=# CREATE TABLE t_delay_key_write(c text) DELAY_KEY_WRITE 1; WARNING: DELAY_KEY_WRITE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表启用或禁用页面级数据加密。 openGauss=# CREATE TABLE t_encryption(c text) ENCRYPTION 'Y'; WARNING: ENCRYPTION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定主存储引擎的表属性。 openGauss=# CREATE TABLE t_engine_attribute(c text) ENGINE_ATTRIBUTE 'engine_attribute'; WARNING: ENGINE_ATTRIBUTE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定应将行插入到的表。 openGauss=# CREATE TABLE t_insert_method(c text) INSERT_METHOD NO; WARNING: INSERT_METHOD for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定索引键块的字节大小。 openGauss=# CREATE TABLE t_key_block_size(c text) KEY_BLOCK_SIZE 10; WARNING: KEY_BLOCK_SIZE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定计划在表中存储的最大行数。 openGauss=# CREATE TABLE t_max_rows(c text) MAX_ROWS 20; WARNING: MAX_ROWS for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定计划在表中存储的最小行数。 openGauss=# CREATE TABLE t_min_rows(c text) MIN_ROWS 5; WARNING: MIN_ROWS for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定控制压缩索引的方式。 openGauss=# CREATE TABLE t_pack_keys(c text) PACK_KEYS DEFAULT; WARNING: PACK_KEYS for TABLE is not supported for current version. skipped CREATE TABLE openGauss=# CREATE TABLE t_password(c text) PASSWORD 'password'; WARNING: PASSWORD for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定开启事务模式。 openGauss=# CREATE TABLE t_start_transaction(c text) START TRANSACTION; WARNING: START TRANSACTION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定辅助存储引擎的表属性。 openGauss=# CREATE TABLE t_secondary_engine_attribute(c text) SECONDARY_ENGINE_ATTRIBUTE 'secondary_engine_attribute'; WARNING: SECONDARY_ENGINE_ATTRIBUTE for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定是否自动重新计算表的持久统计信息。 openGauss=# CREATE TABLE t_stats_auto_recalc(c text) STATS_AUTO_RECALC DEFAULT; WARNING: STATS_AUTO_RECALC for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定是否为表启用持久统计信息。 openGauss=# CREATE TABLE t_stats_persistent(c text) STATS_PERSISTENT DEFAULT; WARNING: STATS_PERSISTENT for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定估计索引列的基数和其他统计信息时要采样的索引页数。 openGauss=# CREATE TABLE t_stats_sample_pages(c text) STATS_SAMPLE_PAGES 1; WARNING: STATS_SAMPLE_PAGES for TABLE is not supported for current version. skipped CREATE TABLE --创建表时访问一组相同的表作为一个表。 openGauss=# CREATE TABLE t_union(c text) UNION(a, b); WARNING: UNION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表存储在磁盘。 openGauss=# CREATE TABLESPACE test ADD DATAFILE 'data.ibd'; WARNING: Suffix ".ibd" of datafile path detected. The actual path will be renamed as "data_ibd" CREATE TABLESPACE openGauss=# CREATE TABLE t_tablespace_storage_disk(c text) TABLESPACE test STORAGE DISK; WARNING: TABLESPACE_OPTION for TABLE is not supported for current version. skipped CREATE TABLE --创建表时对表指定表存储在内存。 openGauss=# CREATE TABLESPACE test ADD DATAFILE 'data.ibd'; WARNING: Suffix ".ibd" of datafile path detected. The actual path will be renamed as "data_ibd" CREATE TABLESPACE openGauss=# CREATE TABLE t_tablespace_storage_memory(c text) TABLESPACE test STORAGE MEMORY; WARNING: TABLESPACE_OPTION for TABLE is not supported for current version. skipped CREATE TABLE ``` \--创建兼容MySQL全文索引语法的表。前提是兼容模式为B的数据库。 ```sql openGauss=# CREATE TABLE test ( openGauss(# id int unsigned auto_increment not null primary key, openGauss(# title varchar, openGauss(# boby text, openGauss(# name name, openGauss(# FULLTEXT (title, boby) WITH PARSER ngram openGauss(# ); NOTICE: CREATE TABLE will create implicit sequence "test_id_seq" for serial column "test.id" NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_pkey" for table "test" CREATE TABLE openGauss=# drop table if exists articles; NOTICE: table "articles" does not exist, skipping DROP TABLE openGauss=# CREATE TABLE articles ( openGauss(# ID int, openGauss(# title VARCHAR(100), openGauss(# FULLTEXT INDEX ngram_idx(title)WITH PARSER ngram openGauss(# ); CREATE TABLE openGauss=# \d articles Table "fulltext_test.articles" Column | Type | Modifiers --------+------------------------+----------- ID | integer | title | character varying(100) | Indexes: "ngram_idx" gin (to_tsvector('ngram'::regconfig, title::text)) TABLESPACE pg_default openGauss=# drop table if exists articles; DROP TABLE openGauss=# CREATE TABLE articles ( openGauss(# ID int, openGauss(# title VARCHAR(100), openGauss(# FULLTEXT INDEX (title)WITH PARSER ngram openGauss(# ); CREATE TABLE openGauss=# \d articles Table "fulltext_test.articles" Column | Type | Modifiers --------+------------------------+----------- ID | integer | title | character varying(100) | Indexes: "articles_to_tsvector_idx" gin (to_tsvector('ngram'::regconfig, title::text)) TABLESPACE pg_default openGauss=# drop table if exists articles; DROP TABLE openGauss=# CREATE TABLE articles ( openGauss(# ID int, openGauss(# title VARCHAR(100), openGauss(# FULLTEXT KEY keyngram_idx(title)WITH PARSER ngram openGauss(# ); CREATE TABLE openGauss=# \d articles Table "fulltext_test.articles" Column | Type | Modifiers --------+------------------------+----------- ID | integer | title | character varying(100) | Indexes: "keyngram_idx" gin (to_tsvector('ngram'::regconfig, title::text)) TABLESPACE pg_default openGauss=# drop table if exists articles; DROP TABLE openGauss=# CREATE TABLE articles ( openGauss(# ID int, openGauss(# title VARCHAR(100), openGauss(# FULLTEXT KEY (title)WITH PARSER ngram openGauss(# ); CREATE TABLE openGauss=# \d articles Table "fulltext_test.articles" Column | Type | Modifiers --------+------------------------+----------- ID | integer | title | character varying(100) | Indexes: "articles_to_tsvector_idx" gin (to_tsvector('ngram'::regconfig, title::text)) TABLESPACE pg_default openGauss=# create table table_ddl_0154(col1 int,col2 varchar(64), FULLTEXT idx_ddl_0154(col2)); CREATE TABLE openGauss=# create table t2 (a float primary key auto_increment); NOTICE: CREATE TABLE will create implicit sequence "t2_a_seq" for serial column "t2.a" NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "t2_pkey" for table "t2" CREATE TABLE openGauss=# alter table t2 auto_increment = 16777216; ALTER TABLE openGauss=# insert into t2 values (null); INSERT 0 1 -- float类型能精确表示的上限为16777216,自增到16777217时存储的值与16777216一致,导致主键冲突 openGauss=# insert into t2 values (null); ERROR: duplicate key value violates unique constraint "t2_pkey" DETAIL: Key (a)=(1.67772e+07) already exists. openGauss=# insert into t2 values (null); INSERT 0 1 ``` --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/server/shark-CREATE-TABLE.md --- # CREATE TABLE ## 功能描述 在当前数据库中创建一个新的空白表,该表由命令执行者所有。 ## 注意事项 * 本章节只包含shark新增的语法,原openGauss的语法未做删除和修改。 * 新增支持 `AS expr [PERSISTED]` 生成列语法。 * 新增支持`opt_clustered`语法。 * 建表语句中,针对UNIQUE和PRIMARY KEY约束,支持通过WITH给出选项,对应index\_parameters子句,新增支持的选项包括: ```EBNF FILLFACTOR = fillfactor | PAD_INDEX = { ON | OFF } | IGNORE_DUP_KEY = { ON | OFF } | STATISTICS_NORECOMPUTE = { ON | OFF } | STATISTICS_INCREMENTAL = { ON | OFF } | ALLOW_ROW_LOCKS = { ON | OFF } | ALLOW_PAGE_LOCKS = { ON | OFF } | OPTIMIZE_FOR_SEQUENTIAL_KEY = { ON | OFF } | XML_COMPRESSION = { ON | OFF } | COMPRESSION_DELAY = { 0 | delay [ MINUTES | MINUTE ] } | DATA_COMPRESSION = { NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE_ARCHIVE } ``` 其中FILLFACTOR选项的取值fillfactor为\[1, 100]的整数,实际含义同A库(A库的取值范围为\[10, 100]的整数),因此当D库中fillfactor的取值范围为\[1, 10),不报错,将打印notice信息,并将fillfactor的取值设置为A库的最小值10; COMPRESSION\_DELAY选项的取值delay为\[0, 10080]的整数; 除FILLFACTOR选项含有实际功能,同A库,其余参数均无实际功能,仅语法支持。 * 建表语句中,针对UNIQUE和PRIMARY KEY约束,支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * 建表语句新增支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * 建表语句新增支持TEXTIMAGE\_ON { filegroup | "default" } 选项,无实际作用,仅语法支持。 * filegroup为任意字符串,支持通过\[]包裹。 * 如果同时指定ON filegroup子句和TEXTIMAGE\_ON filegroup子句,ON filegroup子句应位于前面,否则会出现语法报错。 * ON/TEXTIMAGE\_ON filegroup子句无法和ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }子句同时存在。 * 支持通过特殊前缀(`#`和`##`)的表名分别创建本地临时表和全局临时表。 默认将`#`, `##`识别为标识符的一部分(通过会话级布尔参数`enable_special_operator`切换)而非操作符,因此若只作为操作符使用则需要打开该参数,若同时作为表名以及操作符使用,则关闭该参数并将操作符与操作数用空格分开。 ## 语法格式 创建表。 ```EBNF CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ CHARACTER SET | CHARSET charset ] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ]) [ AUTO_INCREMENT [ = ] value ] [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] | [ ON filegroup ] | [ TEXTIMAGE_ON filegroup ] ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMMENT {=| } 'text' ]; ``` * 其中列约束column\_constraint为: ```EBNF [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | IDENTITY [ ( seed, increment ) ] | GENERATED ALWAYS AS ( generation_expr ) [STORED] | AS ( generation_expr ) [PERSISTED] | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE [KEY] index_parameters [ ON filegroup ] | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters [ ON filegroup ] | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中表约束table\_constraint为: ```EBNF [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ opt_clustered ] ( { { column_name [ ( length ) ] | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] [ ON filegroup ] | PRIMARY KEY [ opt_clustered ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] [ ON filegroup ] | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中索引参数index\_parameters为: ```EBNF [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## 参数说明 * **IDENTITY \[ ( seed, increment ) ]** * 该语法为列添加identity属性,序列值递增,`seed`指定起始值,`increment`指定步长。 * 一张表只能定义一列(包括generated as identity)。 * **AS ( generation\_expr ) \[PERSISTED]** 该子句为兼容D库的语法,将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,PERSISTED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > > * PERSISTED关键字可省略,与不省略PERSISTED语义相同。 > * 兼容D库的生成列无需指定列类型,由表达式计算类型得到列的类型。 > * 兼容D库的生成列在删除生成列依赖的普通列时报错,必须先删除生成列,才能删除生成列依赖的普通列。 * **opt\_clustered** 参数内容为CLUSTERED/NONCLUSTERED,兼容D库的语法,指定创建聚合/非聚合索引。仅语法作用,没有实际功能。 * **WITH ( { storage\_parameter = value } \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。用于表的WITH子句还可以包含OIDS=FALSE表示不分配OID。 针对UNIQUE和PRIMARY KEY约束,新增支持的storage\_parameter选项包括: * FILLFACTOR int类型,填充因子,实际的含义和功能同A库。 取值范围:\[1, 100]的整数,A库的取值范围为\[10, 100]的整数,因此当D库中fillfactor的取值范围为\[1, 10),不报错,将打印notice信息,并将fillfactor的取值设置为A库的最小值10。 * PAD\_INDEX bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * IGNORE\_DUP\_KEY bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * STATISTICS\_NORECOMPUTE bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * STATISTICS\_INCREMENTAL bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * ALLOW\_ROW\_LOCKS bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * ALLOW\_PAGE\_LOCKS bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * OPTIMIZE\_FOR\_SEQUENTIAL\_KEY bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * XML\_COMPRESSION bool类型,无实际功能,仅语法兼容。 取值范围:ON或者OFF。 * COMPRESSION\_DELAY int类型,单位MINUTES或者MINUTE,可选,无实际功能,仅语法兼容。 取值范围:0 | delay \[ MINUTES | MINUTE ],其中delay为\[0, 10080]的整数。 * DATA\_COMPRESSION string类型,无实际功能,仅语法兼容。 取值范围:NONE | ROW | PAGE | COLUMNSTORE | COLUMNSTORE\_ARCHIVE。 * **filegroup** * 建表语句中,针对UNIQUE和PRIMARY KEY约束,支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * 建表语句新增支持ON {filegroup | "default" } 选项,无实际作用,仅语法支持。 * 建表语句新增支持TEXTIMAGE\_ON { filegroup | "default" } 选项,无实际作用,仅语法支持。 * filegroup为任意字符串,支持通过\[]包裹。 * 如果同时指定ON filegroup子句和TEXTIMAGE\_ON filegroup子句,ON filegroup子句应位于前面,否则会出现语法报错。 * ON/TEXTIMAGE\_ON filegroup子句无法和ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }子句同时存在。 * **ASC | DESC** * table\_constraint中,针对PRIMARY KEY和UNIQUE约束支持使用{ column\_name \[ ASC | DESC ] }语法, 为主键和唯一键提供升序或降序约束。 ## 生成列示例 ```sql opengauss=# CREATE TABLE Products( opengauss(# QtyAvailable smallint, opengauss(# UnitPrice money, opengauss(# InventoryValue AS (QtyAvailable * UnitPrice) opengauss(# ); NOTICE: The virtual computed columns (non-persisted) are currently ignored and behave the same as persisted columns. CREATE TABLE opengauss=# ALTER TABLE Products ADD RetailValue AS (QtyAvailable * UnitPrice * 1.5) PERSISTED; ALTER TABLE opengauss=# \d+ Products Table "public.products" Column | Type | Modifiers | Storage | Stats target | Description ----------------+----------+-----------------------------------------------------------------------+---------+--------------+------------- qtyavailable | smallint | | plain | | unitprice | money | | plain | | inventoryvalue | money | as ((qtyavailable * unitprice)) persisted | plain | | retailvalue | money | as (((qtyavailable * unitprice) * (1.5)::double precision)) persisted | plain | | Has OIDs: no Options: orientation=row, compression=no opengauss=# ALTER TABLE Products DROP unitprice; ERROR: cannot drop a column used by a generated column DETAIL: Column "unitprice" is used by generated column "retailvalue". opengauss=# ALTER TABLE Products DROP inventoryvalue; ALTER TABLE opengauss=# ALTER TABLE Products DROP retailvalue; ALTER TABLE opengauss=# ALTER TABLE Products DROP unitprice; ALTER TABLE ``` ## IDENTITY \[ ( seed, increment ) ] 示例 ```sql openGauss=# create extension shark; CREATE EXTENSION openGauss=# create table t1 (a int identity(10, 20), b int); NOTICE: CREATE TABLE will create implicit sequence "t1_a_seq_identity" for serial column "t1.a" CREATE TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+-------------------+---------+--------------+------------- a | integer | not null identity | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no, collate=1537 Character Set: UTF8 Collate: utf8mb4_general_ci openGauss=# insert into t1(b) values(10); INSERT 0 1 openGauss=# insert into t1(a, b) overriding system value values(12, 10); INSERT 0 1 openGauss=# insert into t1 default values; INSERT 0 1 openGauss=# select * from t1; a | b ----+---- 10 | 10 12 | 10 30 | (3 rows) ``` ## WITH ( { storage\_parameter = value } \[, ... ] )示例 ```sql create table test_with_1(a int, CONSTRAINT PK_test_with_1 PRIMARY KEY(a) WITH (PAD_INDEX = OFF, FILLFACTOR = 50, IGNORE_DUP_KEY = off, STATISTICS_NORECOMPUTE = off, STATISTICS_INCREMENTAL = off, ALLOW_ROW_LOCKS = off, ALLOW_PAGE_LOCKS = off, OPTIMIZE_FOR_SEQUENTIAL_KEY = off, XML_COMPRESSION = off)); NOTICE: parameter "pad_index" is currently ignored. NOTICE: parameter "ignore_dup_key" is currently ignored. NOTICE: parameter "statistics_norecompute" is currently ignored. NOTICE: parameter "statistics_incremental" is currently ignored. NOTICE: parameter "allow_row_locks" is currently ignored. NOTICE: parameter "allow_page_locks" is currently ignored. NOTICE: parameter "optimize_for_sequential_key" is currently ignored. NOTICE: parameter "xml_compression" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_with_1" for table "test_with_1" create table test_with_2(a int, CONSTRAINT PK_test_with_2 PRIMARY KEY(a) with (COMPRESSION_DELAY = 0 MINUTES)); NOTICE: parameter "compression_delay" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_with_2" for table "test_with_2" create table test_with_3(a int, CONSTRAINT PK_test_with_3 PRIMARY KEY(a) with (COMPRESSION_DELAY = 10080 minute)); NOTICE: parameter "compression_delay" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_with_3" for table "test_with_3" create table test_with_4(a int, CONSTRAINT PK_test_with_4 PRIMARY KEY(a) with (data_compression = COLUMNSTORE_ARCHIVE)); NOTICE: parameter "data_compression" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_test_with_4" for table "test_with_4" create table test_with_5(a int, PRIMARY KEY(a) with (pad_index = on, fillfactor = 20)); NOTICE: parameter "pad_index" is currently ignored. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_with_5_pkey" for table "test_with_5" create table test_with_6(a int, PRIMARY KEY(a) with (pad_index = on, fillfactor = 1)); NOTICE: parameter "pad_index" is currently ignored. NOTICE: parameter fillfactor will be set to 10 when it is less than 10. NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_with_6_pkey" for table "test_with_6" create table test_with_7(a int, UNIQUE(a) with (pad_index = on, fillfactor = 1)); NOTICE: parameter "pad_index" is currently ignored. NOTICE: parameter fillfactor will be set to 10 when it is less than 10. NOTICE: CREATE TABLE / UNIQUE will create implicit index "test_with_7_a_key" for table "test_with_7" ``` ## filegroup示例 ```sql create table t1(a int) on [primary]; create table t2(a int) on "default"; create table t3(id int) on [filegroup]; create table t4(id int) on filegroup; create table t5(id int) on 'filegroup'; create table t6(id int) on "filegroup"; create table t7(a int) textimage_on [primary]; create table t8(a int) textimage_on "default"; create table t9(a int) on "default" textimage_on [primary]; create table t10(a int) on "default" textimage_on "default"; create table t11(a int PRIMARY KEY WITH (PAD_INDEX = OFF) ON [primary]) ON [primary]; create table t12(a int UNIQUE WITH (XML_COMPRESSION = OFF) ON [primary]) ON [primary]; create table t13(a int, CONSTRAINT PK_t11 PRIMARY KEY(a) WITH (PAD_INDEX = OFF) ON [primary]) ON [primary]; create table t14(a int, CONSTRAINT PK_t12 UNIQUE(a) WITH (XML_COMPRESSION = OFF) ON [primary]) ON [primary]; ``` ## ASC | DESC示例 ```sql openGauss=# create table CONSTRAINT_DESC(id int not null, v1 varchar(30), constraint PK_CONSTRAINT_DESC primary key(id DESC)); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_constraint_desc" for table "constraint_desc" CREATE TABLE openGauss=# \d+ CONSTRAINT_DESC Table "public.constraint_desc" Column | Type | Modifiers | Storage | Stats target | Description --------+-----------------------+-----------+----------+--------------+------------- id | integer | not null | plain | | v1 | character varying(30) | | extended | | Indexes: "pk_constraint_desc" PRIMARY KEY, btree (id DESC) TABLESPACE pg_default Has OIDs: no Options: orientation=row, compression=no ``` ## 使用特殊前缀创建本地和全局临时表 ```sql openGauss=# CREATE TEMPORARY TABLE #ltt1 ( ID INTEGER NOT NULL, NAME CHAR(16) NOT NULL, ADDRESS VARCHAR(50) , POSTCODE CHAR(6) ) ON COMMIT PRESERVE ROWS; CREATE TABLE openGauss=# CREATE GLOBAL TEMPORARY TABLE ##gtt1 ( ID INTEGER NOT NULL, NAME CHAR(16) NOT NULL, ADDRESS VARCHAR(50) , POSTCODE CHAR(6) ) ON COMMIT PRESERVE ROWS; CREATE TABLE ``` ## 相关链接 [CREATE TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_table.html) --- --- url: /zh/docs/latest/ograc/sql_reference/create_table.md --- # CREATE TABLE ## 功能描述 CREATE TABLE用于创建表 ## 注意事项 * 创建当前用户的表需要有CREATE TABLE权限,创建其他普通用户的表需要有CREATE ANY TABLE权限,普通用户不可创建SYS表 * 自增列只支持int/bigint类型,一个表只支持一个自增列,自增列必须是主键或唯一索引 * 外键引用默认引用父表的主键,没有主键报错 * CHECK约束限制字段数量最大16个 * 创建本地临时表时需要开启LOCAL\_TEMPORARY\_TABLE\_ENABLED,表名以#开头,不支持ON COMMIT DELETE ROWS * 临时表的BLOB被定义为RAW(8000), CLOB被定义为VARCHAR(8000B) ## 语法格式 **stmt:** ```sql CREATE [[GLOBAL] TEMPORARY] TABLE [IF NOT EXISTS] [schema_name.]table_name {({column_def_clause}[,...] [external_constraint][,...])} | {AS query} ``` 共享语句尾部及各子句的完整定义参见 [CREATE TABLE 共享子句](shared/create_table_common_clauses.md)。 ## 参数说明 * **TEMPORARY**: 本地临时表 * **GLOBAL TEMPORARY**: 全局临时表 * **ON COMMIT DELETE ROWS**: 事务级临时表,事务结束时会清空数据,不会删除表定义。默认行为 * **ON COMMIT PRESERVE ROWS**: 会话级临时表,会话结束时会清空数据,不会删除表定义 * **CRMODE**: MVCC模式。PAGE是页级MVCC,默认值为CR\_MODE配置 * **SERIAL**: 自增列,和AUTO\_INCREMENT的区别在于SERIAL默认数据类型是BIGINT * **DEFAULT expr \[ON UPDATE expr]**: 列默认值。ON UPDATE expr是兼容语法,UPDATE行数据未指定该列时取update默认值填充 * **COLLATE**: 字符序,支持UTF8\_BIN(区分大小写)、UTF8\_GENERAL\_CI(不区分大小写)、UTF8\_UNICODE\_CI(不区分大小写)、GBK\_BIN(区分大小写)、GBK\_CHINESE\_CI(不区分大小写) * **REFERENCES \[schema\_name.]table\_name\[(column\_name)] ON DELETE CASCADE**: 外键级联设置。外表删除时本表删除 * **REFERENCES \[schema\_name.]table\_name\[(column\_name)] ON DELETE SET NULL**: 外键级联设置。外表删除时本表设置为NULL * **USING INDEX**: 为约束指定索引属性 * **INITRANS**: 初始化数据库事务槽个数 * **MAXTRANS**: 数据库事务槽最大个数 * **FORMAT ({ASF|CSF})**: 行格式,默认为ASF(Aligned Stream Format),临时表不支持CSF(Compact Stream Format) * **STORAGE ({INITIAL int \[K|M|G|T] | MAXSIZE {UNLIMITED | int \[K|M|G|T]}}\[ ...])**: INITIAL指定表初始大小, MAXSIZE表存储的最大值, UNLIMITED代表无限存储 * **RECORDS DELIMITED BY records\_delimiter FIELDS TERMINATED BY fields\_term**: 外部表记录分隔符和字段分隔符。records\_delimiter支持单字符或者newline,fields\_term支持单字符 * **ORGANIZATION EXTERNAL**: 外部表相关。外部表列不支持LOB类型 * **TYPE LOADER**: 数据库转换类型。LOADER是文本转换 * **DIRECTORY**: 外部表所在目录名称,需要使用CREATE DIRECTORY提前创建 * **ACCESS PARAMETERS**: 转换参数 * **LOCATION**: 文件名称 * **AUTO\_INCREMENT \[=] value**: 自增初始值 * **APPENDONLY {ON|OFF}**: 追加写。如果开启后不同线程写一张表会申请新的页做写入,减少锁等待,但页空间浪费较多。默认关闭 * **LOB (LOB\_item) STORE AS**: 指定lob字段(LOB\_ITEM)单独segment存储 * **ENABLE STORAGE IN ROW**: 行内存储 * **DISABLE STORAGE IN ROW**: 行外存储 ## 示例 ``` -- 1. 简单员工表 CREATE TABLE employees ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, salary DECIMAL(10,2) CHECK (salary > 0), dept_id INT ); -- 2. 带外键和注释 CREATE TABLE departments ( dept_id SERIAL PRIMARY KEY, dept_name VARCHAR(50) COMMENT '部门名称', manager_id INT ); -- 全局临时表 CREATE GLOBAL TEMPORARY TABLE temp_data ( session_id VARCHAR(50) ) ON COMMIT DELETE ROWS; -- 会话级临时表 CREATE TEMPORARY TABLE #session_cache ( key VARCHAR(100) PRIMARY KEY, value TEXT ) ON COMMIT PRESERVE ROWS; -- 列级约束 CREATE TABLE users ( user_id INT PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, email VARCHAR(100) UNIQUE, age INT CHECK (age >= 0), status VARCHAR(10) DEFAULT 'ACTIVE' ); -- 表级外键 CREATE TABLE orders ( order_id SERIAL, user_id INT, CONSTRAINT pk_order PRIMARY KEY (order_id), CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE ); -- 指定表空间和存储 CREATE TABLE large_logs ( log_id SERIAL PRIMARY KEY, log_time TIMESTAMP, message TEXT ) TABLESPACE log_ts PCTFREE 10 STORAGE (INITIAL 100M MAXSIZE 2G); -- 带BLOB的表 CREATE TABLE documents ( doc_id SERIAL PRIMARY KEY, doc_content BLOB ) LOB (doc_content) STORE AS (TABLESPACE lob_ts); -- CATS CREATE TABLE sales_summary AS SELECT product_id, SUM(quantity) as total_qty FROM sales GROUP BY product_id; -- 创建页级MVCC表 CREATE TABLE page_mvcc_table ( id SERIAL PRIMARY KEY, log_data TEXT, created_time TIMESTAMP ) CRMODE PAGE; -- 仅指定物理属性,使用默认表空间 CREATE TABLE logs ( log_id SERIAL PRIMARY KEY, log_time TIMESTAMP ) PCTFREE 5 INITRANS 2 MAXTRANS 255 STORAGE (INITIAL 100M MAXSIZE 1G); -- 使用ASF格式创建表 CREATE TABLE user_profiles ( user_id SERIAL PRIMARY KEY, profile_data JSONB, preferences JSONB, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) FORMAT ASF; -- 只指定DIRECTORY和LOCATION CREATE TABLE external_simple ( id INT, name VARCHAR(50) ) ORGANIZATION EXTERNAL ( DIRECTORY data_dir LOCATION 'simple.csv' ); ``` --- --- url: /zh/docs/latest/sql_reference/create_table.md --- # CREATE TABLE ## 功能描述 在当前数据库中创建一个新的空白表,该表由命令执行者所有。 ## 注意事项 * 列存表支持的数据类型请参考[列存表支持的数据类型](data_types_supported_by_column_store_tables.md)。 * 列存表不支持数组。 * 列存表不支持生成列。 * 列存表不支持创建全局临时表。 * 创建列存表的数量建议不超过1000个。 * 如果在建表过程中数据库系统发生故障,系统恢复后可能无法自动清除之前已创建的、大小为0的磁盘文件。此种情况出现概率小,不影响数据库系统的正常运行。 * 列存表的表级约束只支持PARTIAL CLUSTER KEY、UNIQUE、PRIAMRY KEY,不支持外键等表级约束。 * 列存表的字段约束只支持NULL、NOT NULL、DEFAULT常量值、UNIQUE和PRIMARY KEY。 * 列存表支持delta表,受参数enable\_delta\_store控制是否开启,受参数deltarow\_threshold控制进入delta表的阀值。 * 列存表的字段的字符集必须与数据库字符集一致。 * 使用JDBC时,支持通过PrepareStatement对DEFAULT值进行参数化设置。 * 每张表的列数最大为1600,具体取决于列的类型,所有列的大小加起来不能超过8192 byte(由于数据存储形式原因,实际上限略小于8192 byte),text、varchar、char等长度可变的类型除外。 * 被授予CREATE ANY TABLE权限的用户,可以在public模式和用户模式下创建表。如果想要创建包含serial类型列的表,还需要授予CREATE ANY SEQUENCE创建序列的权限。 * 不可与同一模式下已存在的synonym产生命名冲突。 * 仅支持在B兼容性数据库下指定COMMENT和可见性VISIBLE\INVISIBLE。 ## 语法格式 创建表。 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ({ column_name data_type [ CHARACTER SET | CHARSET charset ] [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ]) [ AUTO_INCREMENT [ = ] value ] [ [DEFAULT] CHARACTER SET | CHARSET [ = ] default_charset ] [ [DEFAULT] COLLATE [ = ] default_collation ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMMENT {=| } 'text' ]; ``` * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | GENERATED ALWAYS AS ( generation_expr ) [STORED] | GENERATED [ ALWAYS | BY DEFAULT ] AS IDENTITY [ ( seq_options ) ] | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE [KEY] index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中列的压缩可选项compress\_mode为: ``` { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } ``` * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { { column_name [ ( length ) ] | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中like选项like\_option为: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | IDENTITY | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | PARTITION | RELOPTIONS | ALL } ``` * 其中索引参数index\_parameters为: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * 其中seq\_options为: ``` { MAXVALUE | MINVALUE | START WITH | START | INCREMENT [ BY ] | CACHE | RESTART [ WITH ] } NumericOnly | { NOMAXVALUE | MINVALUE | NO MAXVALUE | NO MINVALUE | NOCYCLE | [ NO ] CYCLE } | OWNED BY name ``` ## 参数说明 * **UNLOGGED** 如果指定此关键字,则创建的表为非日志表。在非日志表中写入的数据不会被写入到预写日志中,这样就会比普通表快很多。但是非日志表在冲突、执行操作系统重启、数据库重启、主备切换、切断电源操作或异常关机后会被自动截断,会造成数据丢失的风险。非日志表中的内容也不会被复制到备服务器中。在非日志表中创建的索引也不会被自动记录。 使用场景:非日志表不能保证数据的安全性,用户应该在确保数据已经做好备份的前提下使用,例如系统升级时进行数据的备份。 故障处理:当异常关机等操作导致非日志表上的索引发生数据丢失时,用户应该对发生错误的索引进行重建。 * UNLOGGED表和表上的索引因为数据写入时不通过WAL日志机制,写入速度远高于普通表。因此,可以用于缓冲存储复杂查询的中间结果集,增强复杂查询的性能。 * UNLOGGED表无主备机制,在系统故障或异常断点等情况下,会有数据丢失风险,因此,不可用来存储基础数据。 * **GLOBAL | LOCAL** 创建临时表时可以在TEMP或TEMPORARY前指定GLOBAL或LOCAL关键字。如果指定GLOBAL关键字,openGauss会创建全局临时表,否则openGauss会创建本地临时表。 * **TEMPORARY | TEMP** 如果指定TEMP或TEMPORARY关键字,则创建的表为临时表。临时表分为全局临时表和本地临时表两种类型。创建临时表时如果指定GLOBAL关键字则为全局临时表,否则为本地临时表。 全局临时表的元数据对所有会话可见,会话结束后元数据继续存在。会话与会话之间的用户数据、索引和统计信息相互隔离,每个会话只能看到和更改自己提交的数据。全局临时表有两种模式:一种是基于会话级别的(ON COMMIT PRESERVE ROWS), 当会话结束时自动清空用户数据;一种是基于事务级别的(ON COMMIT DELETE ROWS), 当执行commit或rollback时自动清空用户数据。建表时如果没有指定ON COMMIT选项,则缺省为会话级别。与本地临时表不同,全局临时表建表时可以指定非pg\_temp\_开头的schema。 本地临时表只在当前会话可见,本会话结束后会自动删除。因此,在除当前会话连接的数据库节点故障时,仍然可以在当前会话上创建和使用临时表。由于临时表只在当前会话创建,对于涉及对临时表操作的DDL语句,会产生DDL失败的报错。因此,建议DDL语句中不要对临时表进行操作。TEMP和TEMPORARY等价。 * 临时表只在当前会话可见,会话结束后会自动删除。 > \[!TIP]须知 > > * 本地临时表通过每个会话独立的以pg\_temp开头的schema来保证只对当前会话可见,因此,不建议用户在日常操作中手动删除以pg\_temp、pg\_toast\_temp开头的schema。 > * 如果建表时不指定TEMPORARY/TEMP关键字,而指定表的schema为当前会话的pg\_temp\_开头的schema,则此表会被创建为临时表。 > * ALTER/DROP全局临时表和索引,如果其它会话正在使用它,禁止操作(ALTER INDEX index\_name REBUILD除外)。 > * 全局临时表的DDL只会影响当前会话的用户数据和索引。例如truncate、reindex、analyze只对当前会话有效。 > * 全局临时表功能可以通过设置GUC参数[max\_active\_global\_temporary\_table](../database_reference/global_temporary_table.md#section18307271684)控制是否启用。如果max\_active\_global\_temporary\_table=0,关闭全局临时表功能。 > * 临时表只对当前会话可见,因此不支持与\parallel on并行执行一起使用。 > * 临时表不支持主备切换。 > * 全局临时表不响应自动清理,在长链接场景使用时尽量使用on commit delete rows的全局临时表,或定期手动执行vacuum,否则可能导致clog日志不回收。 * **IF NOT EXISTS** 如果已经存在相同名称的表,不会报出错误,而会发出通知,告知通知此表已存在。 * **table\_name** 要创建的表名。 > \[!TIP]须知 > > * 物化视图的一些处理逻辑会通过表名的前缀来识别是不是物化视图日志表和物化视图关联表,因此,用户不要创建表名以mlog\_或matviewmap\_为前缀的表,否则会影响此表的一些功能。 * **column\_name** 新表中要创建的字段名。 * **constraint\_name** 建表时指定的约束名称。 > \[!TIP]须知 > > 在B模式数据库下(即sql\_compatibility = 'B')constraint\_name为可选项,在其他模式数据库下,必须加上constraint\_name。 * **index\_name** 索引名。 > \[!TIP]须知 > > * index\_name仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 对于外键约束,constraint\_name和index\_name同时指定时,索引名为constraint\_name。 > * 对于唯一键约束,constraint\_name和index\_name同时指定时,索引名以index\_name。 * **USING method** 指定创建索引的方法。 取值范围参考[参数说明](create_index.md)中的USING method。 > \[!TIP]须知 > > * USING method仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 在B模式下,未指定USING method时,对于Astore的存储方式,默认索引方法为btree;对于Ustore的存储方式,默认索引方法为ubtree。 * **ASC | DESC** ASC表示指定按升序排序(默认)。DESC指定按降序排序。 > \[!TIP]须知 > > ASC|DESC只在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库不支持。 * **expression** 创建一个基于该表的一个或多个字段的表达式索引约束,必须写在圆括弧中。 > \[!TIP]须知 > > 表达式索引只在B模式数据库下支持(即sql\_compatibility = 'B'),其他模式数据库不支持。 * **data\_type** 字段的数据类型。 * **column\_constraint** 字段的类型约束中,添加了mysql的ON UPDATE特性,归类于字段类型约束。与DEFAULT属性属于同类约束。该ON UPDATE属性用于,执行UPDATE操作timestamp字段为缺省时,则自动更新timestamp字段的时间截。如果更新字段的数据内容与原来的数据内容一致,则其他含有ON UPDATE的字段的时间截不会自动更新。 ```sql CREATE TABLE table_name(column_name timestamp ON UPDATE CURRENT_TIMESTAMP); ``` * **compress\_mode** 表字段的压缩选项。该选项指定表字段优先使用的压缩算法。行存表不支持压缩。 取值范围:DELTA、PREFIX、DICTIONARY、NUMSTR、NOCOMPRESS * DELTA压缩仅支持长度为1-8字节的数据类型(0 < pg\_type.typlen <= 8)。 * PREFIX、NUMSTR压缩仅支持变长数据类型(pg\_type.typlen = -1)和NULL结尾的C字符串(pg\_type.typlen = -2)。 * 该压缩选项与列存表自适应压缩算法无关,后者为列存表内部数据存储采用的压缩算法,不支持用户指定。 * **CHARACTER SET | CHARSET charset** 只在B模式数据库下(即sql\_compatibility = 'B')支持该语法,其他模式数据库不支持。指定表字段的字符集,单独指定时会将字段的字符序设置为指定的字符集的默认字符序。 * **COLLATE collation** COLLATE子句指定列的排序规则(字符序)(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。对于B模式数据库下(即sql\_compatibility = 'B')还支持utf8mb4\_bin、utf8mb4\_general\_ci、utf8mb4\_unicode\_ci、binary字符序。 > **说明:** > > * 仅字符类型支持指定字符集,指定为binary字符集或字符序实际是将字符类型转化为对应的二进制类型,若类型映射不存在则报错。当前仅有TEXT类型转化为BLOB的映射。 > * 除binary字符集和字符序外,当前仅支持指定与数据库编码相同的字符集。 > * 未显式指定字段字符集或字符序时,若指定了表的默认字符集或字符序,字段字符集和字符序将从表上继承。若表的默认字符集或字符序不存在,当b\_format\_behavior\_compat\_options = 'default\_collation'时,字段的字符集和字符序将继承当前数据库的字符集及其对应的默认字符序。 **表 1** B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍 * **LIKE source\_table \[ like\_option ... ]** LIKE子句声明一个表,新表自动从这个表中继承所有字段名及其数据类型和非空约束。 新表与源表之间在创建动作完毕之后是完全无关的。在源表做的任何修改都不会传播到新表中,并且也不可能在扫描源表的时候包含新表的数据。 被复制的列和约束并不使用相同的名称进行融合。如果明确的指定了相同的名称或者在另外一个LIKE子句中,将会报错。 * 源表上的字段缺省表达式只有在指定INCLUDING DEFAULTS时,才会复制到新表中。缺省是不包含缺省表达式的,即新表中的所有字段的缺省值都是NULL。 * 源表上的CHECK约束仅在指定INCLUDING CONSTRAINTS时,会复制到新表中,而其他类型的约束永远不会复制到新表中。非空约束总是复制到新表中。此规则同时适用于表约束和列约束。 * 如果指定了INCLUDING INDEXES,则源表上的索引也将在新表上创建,默认不建立索引。 * 如果指定了INCLUDING STORAGE,则复制列的STORAGE设置会复制到新表中,默认情况下不包含STORAGE设置。 * 如果指定了INCLUDING COMMENTS,则源表列、约束和索引的注释会复制到新表中。默认情况下,不复制源表的注释。 * 如果指定了INCLUDING PARTITION,则源表的分区定义会复制到新表中,同时新表将不能再使用PARTITION BY子句。默认情况下,不拷贝源表的分区定义。如果源表上带有索引,可以使用INCLUDING PARTITION INCLUDING INDEXES语法实现。如果对分区表只使用INCLUDING INDEXES,目标表定义将是普通表,但是索引是分区索引,最后结果会报错,因为普通表不支持分区索引。 * 如果指定了INCLUDING RELOPTIONS,则源表的存储参数(即源表的WITH子句)会复制到新表中。默认情况下,不复制源表的存储参数。 * INCLUDING ALL包含了INCLUDING DEFAULTS、INCLUDING CONSTRAINTS、INCLUDING INDEXES、INCLUDING STORAGE、INCLUDING COMMENTS、INCLUDING PARTITION和INCLUDING RELOPTIONS的内容。 * ATUO\_INCREMENT列需要为主键或唯一约束的第一个字段,若复制包含AUTO\_INCREAMENT列的表时指定EXCLUDING INDEX,将会报错。其中AUTO\_INCREAMENT只在B库中生效。 * 新表自动从这个表中继承所有字段名及其数据类型和非空约束,新表与源表之间在创建动作完毕之后是完全无关的。 * INCLUDING IDENTITY用于复制表列的identity属性,会创建新的序列而不会复制潜在序列的选项,新序列选项默认。该选项不支持分区表。 > \[!TIP]须知 > > * 如果源表包含serial、bigserial、smallserial、largeserial类型,或者源表字段的默认值是sequence,且sequence属于源表(通过CREATE SEQUENCE ... OWNED BY创建),这些Sequence不会关联到新表中,新表中会重新创建属于自己的sequence。这和之前版本的处理逻辑不同。如果用户希望源表和新表共享Sequence,需要首先创建一个共享的Sequence(避免使用OWNED BY),并配置为源表字段默认值,这样创建的新表会和源表共享该Sequence。 > > * 不建议将其他表私有的Sequence配置为源表字段的默认值,尤其是其他表只分布在特定的NodeGroup上,这可能导致CREATE TABLE ... LIKE执行失败。另外,如果源表配置其他表私有的Sequence,当该表删除时Sequence也会连带删除,这样源表的Sequence将不可用。如果用户希望多个表共享Sequence,建议创建共享的Sequence。 > > * 对于分区表EXCLUDING,需要配合INCLUDING ALL使用,如INCLUDING ALL EXCLUDING DEFAULTS,除源分区表的DEFAULTS,其它全包含。 > > * 如果源表是本地临时表,则新表也必须是本地临时表,否则会报错。 > > * 如果源表是hash或list分区表,则在CREATE TABLE ... (LIKE ... INCLUDIING PARTITION)时会报错,不支持复制hash或list分区表的分区,仅支持range分区。对于二级分区表,同样只支持range-range二级分区。 * **WITH ( { storage\_parameter = value } \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。用于表的WITH子句还可以包含OIDS=FALSE表示不分配OID。 > \[!NOTE]说明 > > 使用任意精度类型Numeric定义列时,建议指定精度p以及刻度s。在不指定精度和刻度时,会按输入的显示出来。 参数的详细描述如下所示。 * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数对于列存表没有意义。 取值范围:10~100 * ORIENTATION 指定表数据的存储方式,即行存方式、列存方式,该参数设置成功后就不再支持修改。 取值范围: * ROW,表示表的数据将以行式存储。 行存储适合于OLTP业务,适用于点查询或者增删操作较多的场景。 * COLUMN,表示表的数据将以列式存储。 列存储适合于数据仓库业务,此类型的表上会做大量的汇聚计算,且涉及的列操作较少。 默认值: 若指定表空间为普通表空间,默认值为ROW。 * STORAGE\_TYPE 指定存储引擎类型,该参数设置成功后就不再支持修改。 取值范围: * USTORE,表示表支持Inplace-Update存储引擎,仅支持行存储,不支持列存储。 * ASTORE,表示表支持Append-Only存储引擎,仅支持行存储,不支持列存储。 默认值: 不指定表时,默认是Append-Only存储。 * INIT\_TD 创建Ustore表时,指定初始化的TD个数,该参数只在创建Ustore表时才能设置生效。 取值范围:2~128,默认值为4。 * COMPRESSION 指定表数据的压缩级别,它决定了表数据的压缩比以及压缩时间。一般来讲,压缩级别越高,压缩比也越大,压缩时间也越长;反之亦然。实际压缩比取决于加载的表数据的分布特征。行存表默认增加COMPRESSION=NO字段。 取值范围: 列存表的有效值为YES/NO/LOW/MIDDLE/HIGH,默认值为LOW。 * COMPRESSLEVEL 指定表数据同一压缩级别下的不同压缩水平,它决定了同一压缩级别下表数据的压缩比以及压缩时间。对同一压缩级别进行了更加详细的划分,为用户选择压缩比和压缩时间提供了更多的空间。总体来讲,此值越大,表示同一压缩级别下压缩比越大,压缩时间越长;反之亦然。 取值范围:0~3,默认值为0。 * COMPRESSTYPE 行存表参数,设置行存表压缩算法。1代表pglz算法(不推荐使用),2代表zstd算法,3代表pgzstd算法(目前暂不支持),4代表zlib算法,默认不压缩。该参数允许修改,修改对已有数据、变更数据、新增数据同时生效。(仅支持Astore和Ustore下的普通表和分区表) 取值范围:0~4,默认值为0。 * COMPRESS\_LEVEL 行存表参数,设置行存表压缩算法等级,仅当COMPRESSTYPE为2或4时生效。压缩等级越高,表的压缩效果越好,表的访问速度越慢。该参数允许修改,修改对已有数据、变更数据、新增数据同时生效。 取值范围:-31~31,默认值为0。 * COMPRESS\_CHUNK\_SIZE 行存表参数,设置行存表压缩chunk块大小,仅当COMPRESSTYPE不为0时生效。chunk数据块越小,预期能达到的压缩效果越好,同时数据越离散,影响表的访问速度。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:与页面大小有关。在页面大小为8k场景,取值范围为:512、1024、2048、4096。 默认值:4096 * COMPRESS\_PREALLOC\_CHUNKS 行存表参数,设置行存表压缩chunk块预分配数量。预分配数量越大,表的压缩率相对越差,离散度越小,访问性能越好。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:0~7,默认值为0。 * 当COMPRESS\_CHUNK\_SIZE为512和1024时,支持预分配设置最大为7。 * 当COMPRESS\_CHUNK\_SIZE为2048时,支持预分配设置最大为3。 * 当COMPRESS\_CHUNK\_SIZE为4096时,支持预分配设置最大为1。 * COMPRESS\_BYTE\_CONVERT 行存表参数,设置行存表压缩字节转换预处理,仅当COMPRESSTYPE不为0时生效。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:布尔值,默认关闭。 * COMPRESS\_DIFF\_CONVERT 行存表参数,设置行存表压缩字节差分预处理。只能与compress\_byte\_convert一起使用。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:布尔值,默认关闭。 * AUTOVACUUM\_ENABLED 需数据库打开autovacuum功能模块时,单独设置此表是否进行autovacuum。 取值范围:布尔值,默认开启。 * AUTOVACUUM、AUTOANALYZE相关参数 参数有:AUTOVACUUM\_VACUUM\_THREASHOLD、AUTOVACUUM\_ANALYZE\_THREASHOLD、AUTOVACUUM\_VACUUM\_COST\_DELAY、AUTOVACUUM\_VACUUM\_COST\_LIMIT、AUTOVACUUM\_FREEZE\_MIN\_AGE、AUTOVACUUM\_FREEZE\_MAX\_AGE、AUTOVACUUM\_FREEZE\_TABLE\_AGE、AUTOVACUUM\_VACUUM\_SCALE\_FACTOR、AUTOVACUUM\_ANALYZE\_SCALE\_FACTOR 单独设置此表的autovacuum、autoanalyze相关功能参数配置,与同名GUC功能相同,优先生效此处的配置。 取值范围:与同名GUC相同 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000,默认60000。 * PARTIAL\_CLUSTER\_ROWS 指定了在数据加载过程中进行将局部聚簇存储的记录数目。该参数只对列存表有效。 取值范围:大于等于MAX\_BATCHROW,建议取值为MAX\_BATCHROW的整数倍。 * DELTAROW\_THRESHOLD 指定列存表导入时小于多少行的数据进入delta表,只在GUC参数enable\_delta\_store开启时生效。该参数只对列存表有效。 取值范围:0~9999,默认值为100 * segment 使用段页式的方式存储。本参数仅支持行存表。不支持列存表、临时表、unlog表。不支持Ustore存储引擎。 取值范围:on/off 默认值:off * dek\_cipher 透明数据加密密钥的密文。当开启enable\_tde选项时会自动申请创建,用户不可单独指定。通过密钥轮转功能可以对密钥进行更新。 取值范围:字符串。 默认值:不开启加密时默认为空。 * hasuids 参数开启:更新表元组时,为元组分配表级唯一标识id。 取值范围:on/off。 默认值:off。 * vacuum\_truncate 参数开启:VACUUM/AUTOVACUUM过程中尝试截断表末尾的空页面,并允许将截断页的磁盘空间返回到操作系统。仅非段页式的Astore表支持该选项。 取值范围:on/off。 默认值:on。 * collate 在B模式数据库下(即sql\_compatibility = 'B')用于记录表的默认字符序,一般只用于内部存储和导入导出,不推荐用户指定或修改。 取值范围:B模式数据库中独立支持的字符序的oid。 默认值:0。 * **WITHOUT OIDS** 等价于WITH(OIDS=FALSE)的语法。 * **ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }** ON COMMIT选项决定在事务中执行创建临时表操作,当事务提交时,此临时表的后续操作。有以下三个选项,当前支持PRESERVE ROWS和DELETE ROWS选项。 * PRESERVE ROWS(缺省值):提交时不对临时表做任何操作,临时表及其表数据保持不变。 * DELETE ROWS:提交时删除临时表中数据。 * DROP:提交时删除此临时表。只支持本地临时表,不支持全局临时表。 * **COMPRESS | NOCOMPRESS** 创建新表时,需要在CREATE TABLE语句中指定关键字COMPRESS,这样,当对该表进行批量插入时就会触发压缩特性。该特性会在页范围内扫描所有元组数据,生成字典、压缩元组数据并进行存储。指定关键字NOCOMPRESS则不对表进行压缩。行存表不支持压缩。 缺省值:NOCOMPRESS,即不对元组数据进行压缩。 * **TABLESPACE tablespace\_name** 创建新表时指定此关键字,表示新表将要在指定表空间内创建。如果没有声明,将使用默认表空间。 * **COMMNET {=| } text** 创建新表时指定此关键字,表示新表的注释内容。如果没有声明,则不创建注释。 * **CONSTRAINT constraint\_name** 列约束或表约束的名称。可选的约束子句用于声明约束,新行或者更新的行必须满足这些约束才能成功插入或更新。 定义约束有两种方法: * 列约束:作为一个列定义的一部分,仅影响该列。 * 表约束:不和某个列绑在一起,可以作用于多个列。 * **NOT NULL** 字段值不允许为NULL。 * **NULL** 字段值允许为NULL ,这是缺省值。 这个子句只是为和非标准SQL数据库兼容。不建议使用。 * **CHECK ( expression )** CHECK约束声明一个布尔表达式,每次要插入的新行或者要更新的行的新值必须使表达式结果为真或未知才能成功,否则会抛出一个异常并且不会修改数据库。 声明为字段约束的检查约束应该只引用该字段的数值,而在表约束里出现的表达式可以引用多个字段。 > \[!NOTE]说明 > > expression表达式中,如果存在“<>NULL”或“!=NULL”,这种写法是无效的,需要写成“is NOT NULL”。 * **DEFAULT default\_expr** DEFAULT子句给字段指定缺省值。该数值可以是任何不含变量的表达式(不允许使用子查询和对本表中的其他字段的交叉引用)。缺省表达式的数据类型必须和字段类型匹配。 缺省表达式将被用于任何未声明该字段数值的插入操作。如果没有指定缺省值则缺省值为NULL 。 * **GENERATED ALWAYS AS ( generation\_expr ) \[STORED]** 该子句将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,STORED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > > * STORED关键字可省略,与不省略STORED语义相同。 > * 生成表达式不能以任何方式引用当前行以外的其他数据。生成表达式不能引用其他生成列,不能引用系统列。生成表达式不能返回结果集,不能使用子查询,不能使用聚集函数,不能使用窗口函数。生成表达式调用的函数只能是不可变(IMMUTABLE)函数。 > * 不能为生成列指定默认值。 > * 生成列不能作为分区键的一部分。 > * 生成列不能和ON UPDATE约束字句的CASCADE,SET NULL,SET DEFAULT动作同时指定。生成列不能和ON DELETE约束字句的SET NULL,SET DEFAULT动作同时指定。 > * 修改和删除生成列的方法和普通列相同。删除生成列依赖的普通列,生成列被自动删除。不能改变生成列所依赖的列的类型。 > * 生成列不能被直接写入。在INSERT或UPDATE命令中, 不能为生成列指定值, 但是可以指定关键字DEFAULT。 > * 生成列的权限控制和普通列一样。 > * 列存表、内存表MOT不支持生成列。外表中仅postgres\_fdw支持生成列。 * **GENERATED \[ ALWAYS | BY DEFAULT ] AS IDENTITY \[ ( seq\_options ) ]** 该语句创建identity列,用于生成自增/自减的序列。 若在插入时不指定此列的值(或者指定为DEFAULT),则会默认生成。 当列定义为`GANERATED ALWAYS`时,若想插入用户值需要使用`OVERRIDING SYSTEM VALUE`子句,否则会报错,对于UPDATE只能更新为`DEFAULT`; 当列定义为`GANERATED BY DEFAULT`时,用户提供的值会优先于默认值。 `seq_options`可以用于指定序列的选项。 > \[!NOTE]说明 > > * 该列的数据类型仅为整型,NUMERIC类型,该列隐式包含`NOT NULL`约束。 > * 无法同时定义default,serial,auto\_increment,生成列,NULL约束。 > * 序列生成非事务操作,当列/表约束检查失败,触发器失败时该列已生成的值不会回滚。 > * 用户自定义的值不会影响该列的下一个值的生成, > * 可以定义多列,但同一列不能重复定义。 > * 不支持分区表。 * **AUTO\_INCREMENT** 该关键字将字段指定为自动增长列。 若在插入时不指定此列的值(或指定此列的值为0、NULL、DEFAULT),此列的值将由自增计数器自动增长得到。 若插入或更新此列为一个大于当前自增计数器的值,执行成功后,自增计数器将刷新为此值。 自增初始值由“AUTO\_INCREMENT \[ = ] value”子句设置,若不设置,默认为1。 > \[!NOTE]说明 > > * 仅在参数sql\_compatibility=B时可以指定自动增长列。 > * 自动增长列数据类型只能为整数类型、4字节或8字节浮点类型。 > * 每个表只能有一个自动增长列。 > * 自动增长列必须是主键约束或唯一约束的第一个字段。 > * 自动增长列不能指定DEFAULT缺省值。 > * CHECK约束的表达式中不能含有自动增长列。 > * 可以指定自动增长列允许NULL,若不指定,默认自动增长列含有NOT NULL约束。 > * 含有自动增长列的表创建时,会创建一个依赖于此列的序列作为自增计数器,不允许通过序列相关功能修改或删除此序列,可以查看序列的值。 > * 本地临时表中的自动增长列不会创建序列。 > * 自动增长列不支持列式存储。 > * 自增计数器自增和刷新操作不会回滚。 * **\[DEFAULT] CHARACTER SET | CHARSET \[ = ] default\_charset** 仅在sql\_compatibility='B'时支持该语法。指定表的默认字符集,单独指定时会将表的默认字符序设置为指定的字符集的默认字符序。 * **\[DEFAULT] COLLATE \[ = ] default\_collation** 仅在sql\_compatibility='B'时支持该语法。指定表的默认字符序,单独指定时会将表的默认字符集设置为指定的字符序对应的字符集。字符序参见[表1 B模式(即sql\_compatibility = 'B')下支持的字符集和字符序介绍](#table8163190152)。 > \[!NOTE]说明 > 未显式指定表的字符集或字符序时,若指定了模式的默认字符集或字符序,表字符集和字符序将从模式上继承。若模式的默认字符集或字符序不存在,当b\_format\_behavior\_compat\_options = 'default\_collation'时,表的字符集和字符序将继承当前数据库的字符集及其对应的默认字符序。 * **UNIQUE \[KEY] index\_parameters** **UNIQUE ( column\_name \[ ( length ) ] \[, ... ] ) index\_parameters** UNIQUE约束表示表里的一个字段或多个字段的组合必须在全表范围内唯一。 对于唯一约束,NULL被认为是互不相等的。 UNIQUE KEY只能在sql\_compatibility='B'时使用,与UNIQUE语义相同。 column\_name(length)是前缀键,详见:[前缀键说明](create_index.md#前缀键说明)。 * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** 主键约束声明表中的一个或者多个字段只能包含唯一的非NULL值。 一个表只能声明一个主键。 * **REFERENCES reftable \[ ( refcolum ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (column constraint)** **FOREIGN KEY ( column\_name \[, ... ] ) REFERENCES reftable \[ ( refcolumn \[, ... ] ) ] \[ MATCH matchtype ] \[ ON DELETE action ] \[ ON UPDATE action ] (table constraint)** 外键约束要求新表中一列或多列构成的组应该只包含、匹配被参考表中被参考字段值。若省略refcolum,则将使用reftable的主键。被参考列应该是被参考表中的唯一字段或主键。外键约束不能被定义在临时表和永久表之间。 参考字段与被参考字段之间存在三种类型匹配,分别是: * MATCH FULL:不允许一个多字段外键的字段为NULL,除非全部外键字段都是NULL。 * MATCH SIMPLE(缺省):允许任意外键字段为NULL。 * MATCH PARTIAL:目前暂不支持。 另外,当被参考表中的数据发生改变时,某些操作也会在新表对应字段的数据上执行。ON DELETE子句声明当被参考表中的被参考行被删除时要执行的操作。ON UPDATE子句声明当被参考表中的被参考字段数据更新时要执行的操作。对于ON DELETE子句、ON UPDATE子句的可能动作: * NO ACTION(缺省):删除或更新时,创建一个表明违反外键约束的错误。若约束可推迟,且若仍存在任何引用行,那这个错误将会在检查约束的时候产生。 * RESTRICT:删除或更新时,创建一个表明违反外键约束的错误。与NO ACTION相同,只是动作不可推迟。 * CASCADE:删除新表中任何引用了被删除行的行,或更新新表中引用行的字段值为被参考字段的新值。 * SET NULL:设置引用字段为NULL。 * SET DEFAULT:设置引用字段为它们的缺省值。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 * **DEFERRABLE | NOT DEFERRABLE** 这两个关键字设置该约束是否可推迟。一个不可推迟的约束将在每条命令之后马上检查。可推迟约束可以推迟到事务结尾使用SET CONSTRAINTS命令检查。缺省是NOT DEFERRABLE。目前,UNIQUE约束、主键约束、外键约束可以接受这个子句。所有其他约束类型都是不可推迟的。 > \[!NOTE]说明Ustore表不支持 DEFERRABLE 以及 INITIALLY DEFERRED 约束。 * **COMMENT text** 注释。 * **VISIBLE | INVISIBLE** 指定索引是否可见,如果没有声明则默认为VISIBLE。 * **PARTIAL CLUSTER KEY** 局部聚簇存储,列存表导入数据时按照指定的列(单列或多列),进行局部排序。 * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** 如果约束是可推迟的,则这个子句声明检查约束的缺省时间。 * 如果约束是INITIALLY IMMEDIATE(缺省),则在每条语句执行之后就立即检查它; * 如果约束是INITIALLY DEFERRED ,则只有在事务结尾才检查它。 约束检查的时间可以用SET CONSTRAINTS命令修改。 * **USING INDEX TABLESPACE tablespace\_name** 为UNIQUE或PRIMARY KEY约束相关的索引声明一个表空间。如果没有提供这个子句,这个索引将在default\_tablespace中创建,如果default\_tablespace为空,将使用数据库的缺省表空间。 * **ENCRYPTION\_TYPE = encryption\_type\_value** 为ENCRYPTED WITH约束中的加密类型,encryption\_type\_value的值为\[ DETERMINISTIC | RANDOMIZED ] ## 示例 * 创建简单的表。 ```sql openGauss=# CREATE TABLE tpcds.warehouse_t1 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); openGauss=# CREATE TABLE tpcds.warehouse_t2 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60), W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` * 创建表,并指定W\_STATE字段的缺省值为GA。 ```sql openGauss=# CREATE TABLE tpcds.warehouse_t3 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) DEFAULT 'GA', W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建表,并在事务结束时检查W_WAREHOUSE_NAME字段是否有重复。 openGauss=# CREATE TABLE tpcds.warehouse_t4 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE DEFERRABLE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` * 创建一个带有70%填充因子的表。 ```sql openGauss=# CREATE TABLE tpcds.warehouse_t5 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), UNIQUE(W_WAREHOUSE_NAME) WITH(fillfactor=70) ); --或者用下面的语法。 openGauss=# CREATE TABLE tpcds.warehouse_t6 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH(fillfactor=70); ``` * 创建表,并指定该表数据不写入预写日志。 ```sql openGauss=# CREATE UNLOGGED TABLE tpcds.warehouse_t7 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` * 创建表临时表。 ```sql openGauss=# CREATE TEMPORARY TABLE warehouse_t24 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建本地临时表,并指定提交事务时删除该临时表数据。 openGauss=# CREATE TEMPORARY TABLE warehouse_t25 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) ON COMMIT DELETE ROWS; --创建全局临时表,并指定会话结束时删除该临时表数据。 openGauss=# CREATE GLOBAL TEMPORARY TABLE gtt1 ( ID INTEGER NOT NULL, NAME CHAR(16) NOT NULL, ADDRESS VARCHAR(50) , POSTCODE CHAR(6) ) ON COMMIT PRESERVE ROWS; ``` * 创建表时,不希望因为表已存在而报错。 ```sql openGauss=# CREATE TABLE IF NOT EXISTS tpcds.warehouse_t8 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` * 创建普通表空间。 ```sql openGauss=# CREATE TABLESPACE DS_TABLESPACE1 RELATIVE LOCATION 'tablespace/tablespace_1'; --创建表时,指定表空间。 openGauss=# CREATE TABLE tpcds.warehouse_t9 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) TABLESPACE DS_TABLESPACE1; --创建表时,单独指定W_WAREHOUSE_NAME的索引表空间。 openGauss=# CREATE TABLE tpcds.warehouse_t10 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE USING INDEX TABLESPACE DS_TABLESPACE1, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ``` * 创建一个有主键约束的表。 ```sql openGauss=# CREATE TABLE tpcds.warehouse_t11 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); ---或是用下面的语法,效果完全一样。 openGauss=# CREATE TABLE tpcds.warehouse_t12 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), PRIMARY KEY(W_WAREHOUSE_SK) ); --或是用下面的语法,指定约束的名称。 openGauss=# CREATE TABLE tpcds.warehouse_t13 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CSTR_KEY1 PRIMARY KEY(W_WAREHOUSE_SK) ); --创建一个有复合主键约束的表。 openGauss=# CREATE TABLE tpcds.warehouse_t14 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CSTR_KEY2 PRIMARY KEY(W_WAREHOUSE_SK, W_WAREHOUSE_ID) ); ``` * 创建列存表。 ```sql openGauss=# CREATE TABLE tpcds.warehouse_t15 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH (ORIENTATION = COLUMN); --创建局部聚簇存储的列存表。 openGauss=# CREATE TABLE tpcds.warehouse_t16 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), PARTIAL CLUSTER KEY(W_WAREHOUSE_SK, W_WAREHOUSE_ID) ) WITH (ORIENTATION = COLUMN); --定义一个带压缩的列存表。 openGauss=# CREATE TABLE tpcds.warehouse_t17 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ) WITH (ORIENTATION = COLUMN, COMPRESSION=HIGH); ``` * 定义一个检查列约束。 ```sql openGauss=# CREATE TABLE tpcds.warehouse_t19 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY CHECK (W_WAREHOUSE_SK > 0), W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) CHECK (W_WAREHOUSE_NAME IS NOT NULL), W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); openGauss=# CREATE TABLE tpcds.warehouse_t20 ( W_WAREHOUSE_SK INTEGER PRIMARY KEY, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) CHECK (W_WAREHOUSE_NAME IS NOT NULL), W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2), CONSTRAINT W_CONSTR_KEY2 CHECK(W_WAREHOUSE_SK > 0 AND W_WAREHOUSE_NAME IS NOT NULL) ); ``` * 创建一个有外键约束的表。 ```sql openGauss=# CREATE TABLE tpcds.city_t23 ( W_CITY VARCHAR(60) PRIMARY KEY, W_ADDRESS TEXT ); openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) REFERENCES tpcds.city_t23(W_CITY), W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --或是用下面的语法,效果完全一样。 openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , FOREIGN KEY(W_CITY) REFERENCES tpcds.city_t23(W_CITY) ); --或是用下面的语法,指定约束的名称。 openGauss=# CREATE TABLE tpcds.warehouse_t23 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , CONSTRAINT W_FORE_KEY1 FOREIGN KEY(W_CITY) REFERENCES tpcds.city_t23(W_CITY) ); ``` * 向tpcds.warehouse\_t19表中增加一个varchar列。 ```sql openGauss=# ALTER TABLE tpcds.warehouse_t19 ADD W_GOODS_CATEGORY varchar(30); ``` * 给tpcds.warehouse\_t19表增加一个检查约束。 ```sql openGauss=# ALTER TABLE tpcds.warehouse_t19 ADD CONSTRAINT W_CONSTR_KEY4 CHECK (W_STATE IS NOT NULL); ``` * 在一个操作中改变两个现存字段的类型。 ```sql openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY TYPE varchar(80), ALTER COLUMN W_STREET_NAME TYPE varchar(100); --此语句与上面语句等效。 openGauss=# ALTER TABLE tpcds.warehouse_t19 MODIFY (W_GOODS_CATEGORY varchar(30), W_STREET_NAME varchar(60)); ``` * 给一个已存在字段添加非空约束。 ```sql openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY SET NOT NULL; ``` * 移除已存在字段的非空约束。 ```sql openGauss=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY DROP NOT NULL; ``` * 如果列存表中还未指定局部聚簇,向在一个列存表中添加局部聚簇列。 ```sql openGauss=# ALTER TABLE tpcds.warehouse_t17 ADD PARTIAL CLUSTER KEY(W_WAREHOUSE_SK); --查看约束的名称,并删除一个列存表中的局部聚簇列。 openGauss=# \d+ tpcds.warehouse_t17 Table "tpcds.warehouse_t17" Column | Type | Modifiers | Storage | Stats target | Description -------------------+-----------------------+-----------+----------+--------------+------------- w_warehouse_sk | integer | not null | plain | | w_warehouse_id | character(16) | not null | extended | | w_warehouse_name | character varying(20) | | extended | | w_warehouse_sq_ft | integer | | plain | | w_street_number | character(10) | | extended | | w_street_name | character varying(60) | | extended | | w_street_type | character(15) | | extended | | w_suite_number | character(10) | | extended | | w_city | character varying(60) | | extended | | w_county | character varying(30) | | extended | | w_state | character(2) | | extended | | w_zip | character(10) | | extended | | w_country | character varying(20) | | extended | | w_gmt_offset | numeric(5,2) | | main | | Partial Cluster : "warehouse_t17_cluster" PARTIAL CLUSTER KEY (w_warehouse_sk) Has OIDs: no Location Nodes: ALL DATANODES Options: compression=no, version=0.12 openGauss=# ALTER TABLE tpcds.warehouse_t17 DROP CONSTRAINT warehouse_t17_cluster; ``` * 将表移动到另一个表空间。 ```sql openGauss=# ALTER TABLE tpcds.warehouse_t19 SET TABLESPACE PG_DEFAULT; --创建模式joe。 openGauss=# CREATE SCHEMA joe; --将表移动到另一个模式中。 openGauss=# ALTER TABLE tpcds.warehouse_t19 SET SCHEMA joe; --重命名已存在的表。 openGauss=# ALTER TABLE joe.warehouse_t19 RENAME TO warehouse_t23; ``` * 从warehouse\_t23表中删除一个字段。 ```sql openGauss=# ALTER TABLE joe.warehouse_t23 DROP COLUMN W_STREET_NAME; ``` * 创建带INVISIBLE唯一索引的表,需要在B兼容性数据库下 ```sql openGauss=# CREATE TABLE tpcds.warehouse_t26 ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) UNIQUE, W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) , UNIQUE uni_t26 (W_WAREHOUSE_SK) INVISIBLE ) WITH(fillfactor=70); --删除表空间、模式joe和模式表warehouse。 openGauss=# DROP TABLE tpcds.warehouse_t1; openGauss=# DROP TABLE tpcds.warehouse_t2; openGauss=# DROP TABLE tpcds.warehouse_t3; openGauss=# DROP TABLE tpcds.warehouse_t4; openGauss=# DROP TABLE tpcds.warehouse_t5; openGauss=# DROP TABLE tpcds.warehouse_t6; openGauss=# DROP TABLE tpcds.warehouse_t7; openGauss=# DROP TABLE tpcds.warehouse_t8; openGauss=# DROP TABLE tpcds.warehouse_t9; openGauss=# DROP TABLE tpcds.warehouse_t10; openGauss=# DROP TABLE tpcds.warehouse_t11; openGauss=# DROP TABLE tpcds.warehouse_t12; openGauss=# DROP TABLE tpcds.warehouse_t13; openGauss=# DROP TABLE tpcds.warehouse_t14; openGauss=# DROP TABLE tpcds.warehouse_t15; openGauss=# DROP TABLE tpcds.warehouse_t16; openGauss=# DROP TABLE tpcds.warehouse_t17; openGauss=# DROP TABLE tpcds.warehouse_t18; openGauss=# DROP TABLE tpcds.warehouse_t20; openGauss=# DROP TABLE tpcds.warehouse_t21; openGauss=# DROP TABLE tpcds.warehouse_t22; openGauss=# DROP TABLE joe.warehouse_t23; openGauss=# DROP TABLE tpcds.warehouse_t24; openGauss=# DROP TABLE tpcds.warehouse_t25; openGauss=# DROP TABLE tpcds.warehouse_t26; openGauss=# DROP TABLESPACE DS_TABLESPACE1; openGauss=# DROP SCHEMA IF EXISTS joe CASCADE; ``` * 创建identity列 ```sql openGauss=# create table t1 (a int generated always as identity, b int); NOTICE: CREATE TABLE will create implicit sequence "t1_a_seq" for serial column "t1.a" CREATE TABLE openGauss=# \d+ t1 Table "public.t1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+---------------------------------------+---------+--------------+------------- a | integer | not null generated always as identity | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# create table t2 (a int generated by default as identity, b int); NOTICE: CREATE TABLE will create implicit sequence "t2_a_seq" for serial column "t2.a" CREATE TABLE openGauss=# \d+ t2 Table "public.t2" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+-------------------------------------------+---------+--------------+------------- a | integer | not null generated by default as identity | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no ``` * create table like (including identity) ```sql openGauss=# create table t2_1 (like t2); CREATE TABLE openGauss=# \d+ t2_1 Table "public.t2_1" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+-----------+---------+--------------+------------- a | integer | not null | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no openGauss=# create table t2_2 (like t2 including identity); NOTICE: CREATE TABLE will create implicit sequence "t2_2_a_seq" for serial column "t2_2.a" CREATE TABLE openGauss=# \d+ t2_2 Table "public.t2_2" Column | Type | Modifiers | Storage | Stats target | Description --------+---------+-------------------------------------------+---------+--------------+------------- a | integer | not null generated by default as identity | plain | | b | integer | | plain | | Has OIDs: no Options: orientation=row, compression=no ``` ## 相关链接 [ALTER TABLE](alter_table.md),[DROP TABLE](drop_table.md),[CREATE TABLESPACE](create_tablespace.md) --- --- url: /en/docs/latest-lite/sql_reference/create_table_as.md --- # CREATE TABLE AS ## Function **CREATE TABLE AS** creates a table from the results of a query. It creates a table and fills it with data obtained using **SELECT**. The table columns have the names and data types associated with the output columns of **SELECT** (except that you can override the **SELECT** output column names by giving an explicit list of new column names). **CREATE TABLE AS** queries a source table once and writes the data in a new table. The result in the query view changes with the source table. In contrast, the view re-computes and defines its **SELECT** statement at each query. ## Precautions * This statement cannot be used to create a partitioned table. * If an error occurs during table creation, after it is fixed, the system may fail to delete the disk files that are created before the last automatic clearance and whose size is not 0. This problem seldom occurs and does not affect system running of the database. ## Syntax ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] AS query [ WITH [ NO ] DATA ]; ``` ## Parameter Description * **UNLOGGED** Specifies that the table is created as an unlogged table. Data written to unlogged tables is not written to the WALs, which makes them considerably faster than ordinary tables. However, they are not crash-safe: an unlogged table is automatically truncated after a crash or unclean shutdown. Contents of an unlogged table are also not replicated to standby servers. Any indexes created on an unlogged table are automatically unlogged as well. * Usage scenario: Unlogged tables do not ensure data security. Users can back up data before using unlogged tables; for example, users should back up the data before a system upgrade. * Troubleshooting: If data is missing in the indexes of unlogged tables due to some unexpected operations such as an unclean shutdown, users should re-create the indexes with errors. * **GLOBAL | LOCAL** When creating a temporary table, you can specify the **GLOBAL** or **LOCAL** keyword before **TEMP** or **TEMPORARY**. If the keyword **GLOBAL** is specified, openGauss creates a global temporary table. Otherwise, openGauss creates a local temporary table. * **TEMPORARY | TEMP** If **TEMP** or **TEMPORARY** is specified, the created table is a temporary table. Temporary tables are classified into global temporary tables and local temporary tables. If the keyword **GLOBAL** is specified when a temporary table is created, the table is a global temporary table. Otherwise, the table is a local temporary table. The metadata of the global temporary table is visible to all sessions. After the sessions end, the metadata still exists. The user data, indexes, and statistics of a session are isolated from those of another session. Each session can only view and modify the data submitted by itself. Global temporary tables have two schemas: **ON COMMIT PRESERVE ROWS** and **ON COMMIT PRESERVE ROWS**. In session-based **ON COMMIT PRESERVE ROWS** schema, user data is automatically cleared when a session ends. In transaction-based **ON COMMIT DELETE ROWS** schema, user data is automatically cleared when the commit or rollback operation is performed. If the **ON COMMIT** option is not specified during table creation, the session level is used by default. Different from local temporary tables, you can specify a schema that does not start with **pg\_temp\_** when creating a global temporary table. A local temporary table is automatically dropped at the end of the current session. Therefore, you can create and use temporary tables in the current session as long as the connected database node in the session is normal. Temporary tables are created only in the current session. If a DDL statement involves operations on temporary tables, a DDL error will be generated. Therefore, you are not advised to perform operations on temporary tables in DDL statements. **TEMP** is equivalent to **TEMPORARY**. > \[!TIP]NOTICE > > * Local temporary tables are visible to the current session through the schema starting with **pg\_temp** start. Users should not delete schema started with **pg\_temp** or **pg\_toast\_temp**. > * If **TEMPORARY** or **TEMP** is not specified when you create a table but its schema is set to that starting with **pg\_temp\_** in the current session, the table will be created as a temporary table. > * If global temporary tables and indexes are being used by other sessions, do not perform **ALTER** or **DROP**. > * The DDL of a global temporary table affects only the user data and indexes of the current session. For example, **TRUNCATE**, **REINDEX**, and **ANALYZE** are valid only for the current session. * **table\_name** Specifies the name of the table to be created. Value range: a string. It must comply with the naming convention. * **column\_name** Specifies the name of a column to be created in the new table. Value range: a string. It must comply with the naming convention. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. See details of parameters below. * FILLFACTOR The fill factor of a table is a percentage from 10 to 100. **100** (complete filling) is the default value. When a smaller fill factor is specified, **INSERT** operations pack table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives **UPDATE** a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter is only valid for row–store tables. Value range: 10–100 * ORIENTATION Value range: **COLUMN**: The data will be stored in columns. **ROW** (default value): The data will be stored in rows. * COMPRESSION Specifies the compression level of table data. It determines the compression ratio and time. Generally, the higher the level of compression, the higher the ratio, the longer the time; and the lower the level of compression, the lower the ratio, the shorter the time. The actual compression ratio depends on the distribution mode of table data loaded. Value range: The valid values for column-store tables are **YES**, **NO**, **LOW**, **MIDDLE**, and **HIGH**, and the default value is **LOW**. Row-store tables do not support compression. * MAX\_BATCHROW Specifies the maximum number of rows in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000 * **ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }** **ON COMMIT** determines what to do when you commit a temporary table creation operation. The three options are as follows. Currently, only **PRESERVE ROWS** and **DELETE ROWS** can be used. * **PRESERVE ROWS** (default): No special action is taken at the ends of transactions. The temporary table and its table data are unchanged. * **DELETE ROWS**: All rows in the temporary table will be deleted at the end of each transaction block. * **DROP**: The temporary table will be dropped at the end of the current transaction block. Only local temporary tables can be dropped. Global temporary tables cannot be dropped. * **COMPRESS / NOCOMPRESS** Specifies keyword **COMPRESS** during the creation of a table, so that the compression feature is triggered in case of bulk **INSERT** operations. If this feature is enabled, a scan is performed for all tuple data within the page to generate a dictionary and then the tuple data is compressed and stored. If **NOCOMPRESS** is specified, the table is not compressed. Row-store tables do not support compression. Default value: **NOCOMPRESS**, that is, tuple data is not compressed before storage. * **TABLESPACE tablespace\_name** Specifies that the new table will be created in the **tablespace\_name** tablespace. If not specified, the default tablespace is used. * **AS query** Specifies a **SELECT** or **VALUES** command, or an **EXECUTE** command that runs a prepared **SELECT** or **VALUES** query. * **\[ WITH \[ NO ] DATA ]** Specifies whether the data produced by the query should be copied to the new table. By default, the data will be copied. If the value **NO** is used, only the table structure will be copied. ## Examples ``` -- Create the tpcds.store_returns table. openGauss=# CREATE TABLE tpcds.store_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, sr_item_sk VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER ); -- Create the tpcds.store_returns_t1 table and insert numbers that are greater than 16 in the sr_item_sk column of the tpcds.store_returns table. openGauss=# CREATE TABLE tpcds.store_returns_t1 AS SELECT * FROM tpcds.store_returns WHERE sr_item_sk > '4795'; -- Copy tpcds.store_returns to create the tpcds.store_returns_t2 table. openGauss=# CREATE TABLE tpcds.store_returns_t2 AS table tpcds.store_returns; -- Delete the table. openGauss=# DROP TABLE tpcds.store_returns_t1 ; openGauss=# DROP TABLE tpcds.store_returns_t2 ; openGauss=# DROP TABLE tpcds.store_returns; ``` ## Helpful Links [CREATE TABLE](create_table.md) and [SELECT](select.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-create-table-as.md --- # CREATE TABLE AS ## Function **CREATE TABLE AS** creates a table based on the results of a query. It creates a table and fills it with data obtained using **SELECT**. The table columns have the names and data types associated with the output columns of **SELECT** (except that you can override the **SELECT** output column names by giving an explicit list of new column names). **CREATE TABLE AS** queries a source table once and writes the data in a new table. The result in the query view changes with the source table. In contrast, the view re-computes and defines its **SELECT** statement at each query. ## Precautions * This section describes only the new syntax of Dolphin. The original syntax of openGauss is not deleted or modified. ## Syntax ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ AS ] query [ WITH [ NO ] DATA ]; ``` ## Parameter Description * **\[ AS ] query** Specifies a **SELECT** or **VALUES** command, or an **EXECUTE** command that runs a prepared **SELECT**, or **VALUES** query. The AS keyword is optional. However, if the query contains the WITH statement, you must use parentheses to enclose the query. The following is an example: ``` CREATE TABLE t_new (WITH temp_t(a, b) AS (SELECT a, b FROM t_old) SELECT * FROM temp_t); ``` ## Examples ``` --Create the tpcds.store_returns table. openGauss=# CREATE TABLE tpcds.store_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, sr_item_sk VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER ); --Create the tpcds.store_returns_t1 table and insert numbers that are greater than 16 in the sr_item_sk column of the tpcds.store_returns table: openGauss=# CREATE TABLE tpcds.store_returns_t1 AS SELECT * FROM tpcds.store_returns WHERE sr_item_sk > '4795'; --Copy tpcds.store_returns to create the tpcds.store_returns_t2 table. openGauss=# CREATE TABLE tpcds.store_returns_t2 AS table tpcds.store_returns; --Delete a table. openGauss=# DROP TABLE tpcds.store_returns_t1 ; openGauss=# DROP TABLE tpcds.store_returns_t2 ; openGauss=# DROP TABLE tpcds.store_returns; ``` ## Helpful Links [CREATE TABLE](https://docs.opengauss.org/en/docs/latest/sql_reference/create_table.html), [SELECT](https://docs.opengauss.org/en/docs/latest/sql_reference/select.html) --- --- url: /en/docs/latest/sql_reference/create_table_as.md --- # CREATE TABLE AS ## Function **CREATE TABLE AS** creates a table from the results of a query. It creates a table and fills it with data obtained using **SELECT**. The table columns have the names and data types associated with the output columns of **SELECT** (except that you can override the **SELECT** output column names by giving an explicit list of new column names). **CREATE TABLE AS** queries a source table once and writes the data in a new table. The result in the query view changes with the source table. In contrast, the view re-computes and defines its **SELECT** statement at each query. ## Precautions * This statement cannot be used to create a partitioned table. * If an error occurs during table creation, after it is fixed, the system may fail to delete the disk files that are created before the last automatic clearance and whose size is not 0. This problem seldom occurs and does not affect system running of the database. ## Syntax ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] AS query [ WITH [ NO ] DATA ]; ``` ## Parameter Description * **UNLOGGED** Specifies that the table is created as an unlogged table. Data written to unlogged tables is not written to the WALs, which makes them considerably faster than ordinary tables. However, they are not crash-safe: an unlogged table is automatically truncated after a crash or unclean shutdown. Contents of an unlogged table are also not replicated to standby servers. Any indexes created on an unlogged table are automatically unlogged as well. * Usage scenario: Unlogged tables do not ensure data security. Users can back up data before using unlogged tables; for example, users should back up the data before a system upgrade. * Troubleshooting: If data is missing in the indexes of unlogged tables due to some unexpected operations such as an unclean shutdown, users should re-create the indexes with errors. * **GLOBAL | LOCAL** When creating a temporary table, you can specify the **GLOBAL** or **LOCAL** keyword before **TEMP** or **TEMPORARY**. If the keyword **GLOBAL** is specified, openGauss creates a global temporary table. Otherwise, openGauss creates a local temporary table. * **TEMPORARY | TEMP** If **TEMP** or **TEMPORARY** is specified, the created table is a temporary table. Temporary tables are classified into global temporary tables and local temporary tables. If the keyword **GLOBAL** is specified when a temporary table is created, the table is a global temporary table. Otherwise, the table is a local temporary table. The metadata of the global temporary table is visible to all sessions. After the sessions end, the metadata still exists. The user data, indexes, and statistics of a session are isolated from those of another session. Each session can only view and modify the data submitted by itself. Global temporary tables have two schemas: **ON COMMIT PRESERVE ROWS** and **ON COMMIT PRESERVE ROWS**. In session-based **ON COMMIT PRESERVE ROWS** schema, user data is automatically cleared when a session ends. In transaction-based **ON COMMIT DELETE ROWS** schema, user data is automatically cleared when the commit or rollback operation is performed. If the **ON COMMIT** option is not specified during table creation, the session level is used by default. Different from local temporary tables, you can specify a schema that does not start with **pg\_temp\_** when creating a global temporary table. A local temporary table is automatically dropped at the end of the current session. Therefore, you can create and use temporary tables in the current session as long as the connected database node in the session is normal. Temporary tables are created only in the current session. If a DDL statement involves operations on temporary tables, a DDL error will be generated. Therefore, you are not advised to perform operations on temporary tables in DDL statements. **TEMP** is equivalent to **TEMPORARY**. > \[!TIP]NOTICE > > * Local temporary tables are visible to the current session through the schema starting with **pg\_temp** start. Users should not delete schema started with **pg\_temp** or **pg\_toast\_temp**. > * If **TEMPORARY** or **TEMP** is not specified when you create a table but its schema is set to that starting with **pg\_temp\_** in the current session, the table will be created as a temporary table. > * If global temporary tables and indexes are being used by other sessions, do not perform **ALTER** or **DROP**. > * The DDL of a global temporary table affects only the user data and indexes of the current session. For example, **TRUNCATE**, **REINDEX**, and **ANALYZE** are valid only for the current session. * **table\_name** Specifies the name of the table to be created. Value range: a string. It must comply with the naming convention. * **column\_name** Specifies the name of a column to be created in the new table. Value range: a string. It must comply with the naming convention. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. See details of parameters below. * FILLFACTOR The fill factor of a table is a percentage from 10 to 100. **100** (complete filling) is the default value. When a smaller fill factor is specified, **INSERT** operations pack table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives **UPDATE** a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter is only valid for row–store tables. Value range: 10–100 * ORIENTATION Value range: **COLUMN**: The data will be stored in columns. **ROW** (default value): The data will be stored in rows. * COMPRESSION Specifies the compression level of table data. It determines the compression ratio and time. Generally, the higher the level of compression, the higher the ratio, the longer the time; and the lower the level of compression, the lower the ratio, the shorter the time. The actual compression ratio depends on the distribution mode of table data loaded. Value range: The valid values for column-store tables are **YES**, **NO**, **LOW**, **MIDDLE**, and **HIGH**, and the default value is **LOW**. Row-store tables do not support compression. * MAX\_BATCHROW Specifies the maximum number of rows in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000 * **ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }** **ON COMMIT** determines what to do when you commit a temporary table creation operation. The three options are as follows. Currently, only **PRESERVE ROWS** and **DELETE ROWS** can be used. * **PRESERVE ROWS** (default): No special action is taken at the ends of transactions. The temporary table and its table data are unchanged. * **DELETE ROWS**: All rows in the temporary table will be deleted at the end of each transaction block. * **DROP**: The temporary table will be dropped at the end of the current transaction block. Only local temporary tables can be dropped. Global temporary tables cannot be dropped. * **COMPRESS / NOCOMPRESS** Specifies keyword **COMPRESS** during the creation of a table, so that the compression feature is triggered in case of bulk **INSERT** operations. If this feature is enabled, a scan is performed for all tuple data within the page to generate a dictionary and then the tuple data is compressed and stored. If **NOCOMPRESS** is specified, the table is not compressed. Row-store tables do not support compression. Default value: **NOCOMPRESS**, that is, tuple data is not compressed before storage. * **TABLESPACE tablespace\_name** Specifies that the new table will be created in the **tablespace\_name** tablespace. If not specified, the default tablespace is used. * **AS query** Specifies a **SELECT** or **VALUES** command, or an **EXECUTE** command that runs a prepared **SELECT** or **VALUES** query. * **\[ WITH \[ NO ] DATA ]** Specifies whether the data produced by the query should be copied to the new table. By default, the data will be copied. If the value **NO** is used, only the table structure will be copied. ## Examples ``` -- Create the tpcds.store_returns table. openGauss=# CREATE TABLE tpcds.store_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, sr_item_sk VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER ); -- Create the tpcds.store_returns_t1 table and insert numbers that are greater than 16 in the sr_item_sk column of the tpcds.store_returns table. openGauss=# CREATE TABLE tpcds.store_returns_t1 AS SELECT * FROM tpcds.store_returns WHERE sr_item_sk > '4795'; -- Copy tpcds.store_returns to create the tpcds.store_returns_t2 table. openGauss=# CREATE TABLE tpcds.store_returns_t2 AS table tpcds.store_returns; -- Delete the table. openGauss=# DROP TABLE tpcds.store_returns_t1 ; openGauss=# DROP TABLE tpcds.store_returns_t2 ; openGauss=# DROP TABLE tpcds.store_returns; ``` ## Helpful Links [CREATE TABLE](create_table.md) and [SELECT](select.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CREATE-TABLE-AS.md --- # CREATE TABLE AS ## 功能描述 根据查询结果创建表。 CREATE TABLE AS创建一个表并且用来自SELECT命令的结果填充该表。该表的字段和SELECT输出字段的名称及数据类型相关。不过用户可以通过明确地给出一个字段名称列表来覆盖SELECT输出字段的名称。 CREATE TABLE AS对源表进行一次查询,然后将数据写入新表中,而查询视图结果会根据源表的变化而有所改变。相比之下,每次做查询的时候,视图都重新计算定义它的SELECT语句。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 ## 语法格式 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ AS ] query [ WITH [ NO ] DATA ]; ``` ## 参数说明 * **\[ AS ] query** 一个SELECT VALUES命令。 AS关键字可选,但若query中带有WITH语句,则必须使用括号将query包围,参考语句: ``` CREATE TABLE t_new (WITH temp_t(a, b) AS (SELECT a, b FROM t_old) SELECT * FROM temp_t); ``` ## 示例 ``` --创建一个表tpcds.store_returns表。 openGauss=# CREATE TABLE tpcds.store_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, sr_item_sk VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER ); --创建一个表tpcds.store_returns_t1并插入tpcds.store_returns表中sr_item_sk字段中大于16的数值。 openGauss=# CREATE TABLE tpcds.store_returns_t1 AS SELECT * FROM tpcds.store_returns WHERE sr_item_sk > '4795'; --使用tpcds.store_returns拷贝一个新表tpcds.store_returns_t2。 openGauss=# CREATE TABLE tpcds.store_returns_t2 AS table tpcds.store_returns; --删除表。 openGauss=# DROP TABLE tpcds.store_returns_t1 ; openGauss=# DROP TABLE tpcds.store_returns_t2 ; openGauss=# DROP TABLE tpcds.store_returns; ``` ## 相关链接 [CREATE TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/create_table_1.html),[SELECT](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/SELECT.html) --- --- url: /zh/docs/latest-lite/sql_reference/create_table_as.md --- # CREATE TABLE AS ## 功能描述 根据查询结果创建表。 CREATE TABLE AS创建一个表并且用来自SELECT命令的结果填充该表。该表的字段和SELECT输出字段的名称及数据类型相关。不过用户可以通过明确地给出一个字段名称列表来覆盖SELECT输出字段的名称。 CREATE TABLE AS对源表进行一次查询,然后将数据写入新表中,而查询视图结果会根据源表的变化而有所改变。相比之下,每次做查询的时候,视图都重新计算定义它的SELECT语句。 ## 注意事项 * 分区表不能采用此方式进行创建。 * 如果在建表过程中数据库系统发生故障,系统恢复后可能无法自动清除之前已创建的、大小非0的磁盘文件。此种情况出现概率小,不影响数据库系统的正常运行。 ## 语法格式 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ DISTRIBUTE BY { REPLICATION | { [HASH] ( cloume_name ) } } ] [ TO { GROUP group_name | NODE ( nodename [ , ... ] ) } ] AS query [ WITH [ NO ] DATA ]; ``` B模式下支持: ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name [ ({ column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ]} | table_constraint [, ... ]) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ REPLACE | IGNORE ] AS query [ WITH [ NO ] DATA ]; ``` * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中列的压缩可选项compress\_mode为: ``` { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } ``` * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { { column_name | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` > > \[!TIP]须知 > > * 更多参数细节说明可参考[CREATE TABLE](create_table.md)章节。 ## 参数说明 * **UNLOGGED** 指定表为非日志表。在非日志表中写入的数据不会被写入到预写日志中,这样就会比普通表快很多。但是,它也是不安全的,非日志表在冲突或异常关机后会被自动删截。非日志表中的内容也不会被复制到备用服务器中。在该类表中创建的索引也不会被自动记录。 * 使用场景:非日志表不能保证数据的安全性,用户应该在确保数据已经做好备份的前提下使用,例如系统升级时进行数据的备份。 * 故障处理:当异常关机等操作导致非日志表上的索引发生数据丢失时,用户应该对发生错误的索引进行重建。 * **GLOBAL | LOCAL** 创建临时表时可以在TEMP或TEMPORARY前指定GLOBAL或LOCAL关键字。如果指定GLOBAL关键字,openGauss会创建全局临时表,否则openGauss会创建本地临时表。 * **TEMPORARY | TEMP** 如果指定TEMP或TEMPORARY关键字,则创建的表为临时表。临时表分为全局临时表和本地临时表两种类型。创建临时表时如果指定GLOBAL关键字则为全局临时表,否则为本地临时表。 全局临时表的元数据对所有会话可见,会话结束后元数据继续存在。会话与会话之间的用户数据、索引和统计信息相互隔离,每个会话只能看到和更改自己提交的数据。全局临时表有两种模式:一种是基于会话级别的(ON COMMIT PRESERVE ROWS), 当会话结束时自动清空用户数据;一种是基于事务级别的(ON COMMIT DELETE ROWS), 当执行commit或rollback时自动清空用户数据。建表时如果没有指定ON COMMIT选项,则缺省为会话级别。与本地临时表不同,全局临时表建表时可以指定非pg\_temp\_开头的schema。 本地临时表只在当前会话可见,本会话结束后会自动删除。因此,在除当前会话连接的数据库节点故障时,仍然可以在当前会话上创建和使用临时表。由于临时表只在当前会话创建,对于涉及对临时表操作的DDL语句,会产生DDL失败的报错。因此,建议DDL语句中不要对临时表进行操作。TEMP和TEMPORARY等价。 > \[!TIP]须知 > > * 本地临时表通过每个会话独立的以pg\_temp开头的schema来保证只对当前会话可见,因此,不建议用户在日常操作中手动删除以pg\_temp,pg\_toast\_temp开头的schema。 > * 如果建表时不指定TEMPORARY/TEMP关键字,而指定表的schema为当前会话的pg\_temp\_开头的schema,则此表会被创建为临时表。 > * ALTER/DROP全局临时表和索引,如果其它会话正在使用它,禁止操作。 > * 全局临时表的DDL只会影响当前会话的用户数据和索引。例如truncate、reindex、analyze只对当前会话有效。 * **table\_name** 要创建的表名。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新表中要创建的字段名。 取值范围:字符串,要符合标识符的命名规范。 注:若没有指定字段类型,则替换源表字段名;若指定字段类型,请参考**data\_type**参数介绍。 * **data\_type** 指定新表中字段的类型。 若源表中不含该字段名,则新增该字段。 若源表中含有该字段名,且源表中的字段类型不可转化为指定data\_type类型,则报错;否则,新表中该字段类型改为指定类型。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。参数的详细说明如下所示。 * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数只对行存表有效。 取值范围:10~100 * ORIENTATION 取值范围: COLUMN:表的数据将以列式存储。 ROW(缺省值):表的数据将以行式存储。 * COMPRESSION 指定表数据的压缩级别,它决定了表数据的压缩比以及压缩时间。一般来讲,压缩级别越高,压缩比也越大,压缩时间也越长;反之亦然。实际压缩比取决于加载的表数据的分布特征。 取值范围: 列存表的有效值为YES/NO/LOW/MIDDLE/HIGH,默认值为LOW。 行存表不支持压缩。 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000 * **ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }** ON COMMIT选项决定在事务中执行创建临时表操作,当事务提交时,此临时表的后续操作。有以下三个选项,当前仅支持PRESERVE ROWS和DELETE ROWS选项。 * PRESERVE ROWS(缺省值):提交时不对临时表执行任何操作,临时表及其表数据保持不变。 * DELETE ROWS:提交时删除临时表中数据。 * DROP:提交时删除此临时表。只支持删除本地临时表,不支持删除全局临时表。 * **COMPRESS / NOCOMPRESS** 创建一个新表时,需要在创建表语句中指定关键字COMPRESS,这样,当对该表进行批量插入时就会触发压缩特性。该特性会在页范围内扫描所有元组数据,生成字典、压缩元组数据并进行存储。指定关键字NOCOMPRESS则不对表进行压缩。行存表不支持压缩。该参数已废弃,列存表请使用COMPRESSION修改压缩等级。 缺省值:NOCOMPRESS,即不对元组数据进行压缩。 * **TABLESPACE tablespace\_name** 指定新表将要在tablespace\_name表空间内创建。如果没有声明,将使用默认表空间。 * **\[ REPLACE / IGNORE ]** 若有唯一性约束列,插入数据时,对重复数据的处理行为进行设置。 * **DISTRIBUTE BY** 指定表如何分布和复制。当前版本不支持。 * **TO { GROUP group\_name | GROUP ( nodename \[ , ... ] ) }** TO GROUP指定表所在的GROUP,TO NODE主要供内部扩容工具使用。当前版本不支持。 * **AS query** 一个SELECT VALUES命令。 * **\[ WITH \[ NO ] DATA ]** 创建表时,是否也插入查询到的数据。默认是要数据,选择“NO”参数时,则不要数据。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 ## 示例 ``` --创建一个表tpcds.store_returns表。 openGauss=# CREATE TABLE tpcds.store_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, sr_item_sk VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER ); --创建一个表tpcds.store_returns_t1并插入tpcds.store_returns表中sr_item_sk字段中大于16的数值。 openGauss=# CREATE TABLE tpcds.store_returns_t1 AS SELECT * FROM tpcds.store_returns WHERE sr_item_sk > '4795'; --使用tpcds.store_returns拷贝一个新表tpcds.store_returns_t2。 openGauss=# CREATE TABLE tpcds.store_returns_t2 AS table tpcds.store_returns; --B模式下 openGauss=# CREATE TABLE tpcds.store_returns_t3(newcol INTEGER) AS table tpcds.store_returns; --删除表。 openGauss=# DROP TABLE tpcds.store_returns_t1 ; openGauss=# DROP TABLE tpcds.store_returns_t2 ; openGauss=# DROP TABLE tpcds.store_returns_t3 ; openGauss=# DROP TABLE tpcds.store_returns; ``` ## 相关链接 [CREATE TABLE](create_table.md),[SELECT](select.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CREATE-TABLE-AS.md --- # CREATE TABLE AS ## 功能描述 根据查询结果创建表。 CREATE TABLE AS创建一个表并且用来自SELECT命令的结果填充该表。该表的字段和SELECT输出字段的名称及数据类型相关。不过用户可以通过明确地给出一个字段名称列表来覆盖SELECT输出字段的名称。 CREATE TABLE AS对源表进行一次查询,然后将数据写入新表中,而查询视图结果会根据源表的变化而有所改变。相比之下,每次做查询的时候,视图都重新计算定义它的SELECT语句。 ## 注意事项 * 本章节只包含dolphin新增的语法,原openGauss的语法未做删除和修改。 ## 语法格式 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ AS ] query [ WITH [ NO ] DATA ]; ``` ## 参数说明 * **\[ AS ] query** 一个SELECT VALUES命令。 AS关键字可选,但若query中带有WITH语句,则必须使用括号将query包围,参考语句: ``` CREATE TABLE t_new (WITH temp_t(a, b) AS (SELECT a, b FROM t_old) SELECT * FROM temp_t); ``` ## 示例 ``` --创建一个表tpcds.store_returns表。 openGauss=# CREATE TABLE tpcds.store_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, sr_item_sk VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER ); --创建一个表tpcds.store_returns_t1并插入tpcds.store_returns表中sr_item_sk字段中大于16的数值。 openGauss=# CREATE TABLE tpcds.store_returns_t1 AS SELECT * FROM tpcds.store_returns WHERE sr_item_sk > '4795'; --使用tpcds.store_returns拷贝一个新表tpcds.store_returns_t2。 openGauss=# CREATE TABLE tpcds.store_returns_t2 AS table tpcds.store_returns; --删除表。 openGauss=# DROP TABLE tpcds.store_returns_t1 ; openGauss=# DROP TABLE tpcds.store_returns_t2 ; openGauss=# DROP TABLE tpcds.store_returns; ``` ## 相关链接 [CREATE TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/create_table.html),[SELECT](https://docs.opengauss.org/zh/docs/latest/sql_reference/select.html) --- --- url: /zh/docs/latest/sql_reference/create_table_as.md --- # CREATE TABLE AS ## 功能描述 根据查询结果创建表。 CREATE TABLE AS创建一个表并且用来自SELECT命令的结果填充该表。该表的字段和SELECT输出字段的名称及数据类型相关。不过用户可以通过明确地给出一个字段名称列表来覆盖SELECT输出字段的名称。 CREATE TABLE AS对源表进行一次查询,然后将数据写入新表中,而查询视图结果会根据源表的变化而有所改变。相比之下,每次做查询的时候,视图都重新计算定义它的SELECT语句。 ## 注意事项 * 分区表不能采用此方式进行创建。 * 如果在建表过程中数据库系统发生故障,系统恢复后可能无法自动清除之前已创建的、大小非0的磁盘文件。此种情况出现概率小,不影响数据库系统的正常运行。 ## 语法格式 ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name [ (column_name [, ...] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ DISTRIBUTE BY { REPLICATION | { [HASH] ( cloume_name ) } } ] [ TO { GROUP group_name | NODE ( nodename [ , ... ] ) } ] AS query [ WITH [ NO ] DATA ]; ``` B模式下支持: ``` CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name [ ({ column_name data_type [ compress_mode ] [ COLLATE collation ] [ column_constraint [ ... ] ]} | table_constraint [, ... ]) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ REPLACE | IGNORE ] AS query [ WITH [ NO ] DATA ]; ``` * 其中列约束column\_constraint为: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_expr | AUTO_INCREMENT | ON UPDATE update_expr | UNIQUE index_parameters | ENCRYPTED WITH ( COLUMN_ENCRYPTION_KEY = column_encryption_key, ENCRYPTION_TYPE = encryption_type_value ) | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 其中列的压缩可选项compress\_mode为: ``` { DELTA | PREFIX | DICTIONARY | NUMSTR | NOCOMPRESS } ``` * 其中表约束table\_constraint为: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { { column_name | ( expression ) } [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters [ VISIBLE | INVISIBLE ] | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ (refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] | PARTIAL CLUSTER KEY ( column_name [, ... ] ) } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` > \[!TIP]须知 > > * 更多参数细节说明可参考[CREATE TABLE](create_table.md)章节。 ## 参数说明 * **UNLOGGED** 指定表为非日志表。在非日志表中写入的数据不会被写入到预写日志中,这样就会比普通表快很多。但是,它也是不安全的,非日志表在冲突或异常关机后会被自动删截。非日志表中的内容也不会被复制到备用服务器中。在该类表中创建的索引也不会被自动记录。 * 使用场景:非日志表不能保证数据的安全性,用户应该在确保数据已经做好备份的前提下使用,例如系统升级时进行数据的备份。 * 故障处理:当异常关机等操作导致非日志表上的索引发生数据丢失时,用户应该对发生错误的索引进行重建。 * **GLOBAL | LOCAL** 创建临时表时可以在TEMP或TEMPORARY前指定GLOBAL或LOCAL关键字。如果指定GLOBAL关键字,openGauss会创建全局临时表,否则openGauss会创建本地临时表。 * **TEMPORARY | TEMP** 如果指定TEMP或TEMPORARY关键字,则创建的表为临时表。临时表分为全局临时表和本地临时表两种类型。创建临时表时如果指定GLOBAL关键字则为全局临时表,否则为本地临时表。 全局临时表的元数据对所有会话可见,会话结束后元数据继续存在。会话与会话之间的用户数据、索引和统计信息相互隔离,每个会话只能看到和更改自己提交的数据。全局临时表有两种模式:一种是基于会话级别的(ON COMMIT PRESERVE ROWS), 当会话结束时自动清空用户数据;一种是基于事务级别的(ON COMMIT DELETE ROWS), 当执行commit或rollback时自动清空用户数据。建表时如果没有指定ON COMMIT选项,则缺省为会话级别。与本地临时表不同,全局临时表建表时可以指定非pg\_temp\_开头的schema。 本地临时表只在当前会话可见,本会话结束后会自动删除。因此,在除当前会话连接的数据库节点故障时,仍然可以在当前会话上创建和使用临时表。由于临时表只在当前会话创建,对于涉及对临时表操作的DDL语句,会产生DDL失败的报错。因此,建议DDL语句中不要对临时表进行操作。TEMP和TEMPORARY等价。 > \[!TIP]须知 > > * 本地临时表通过每个会话独立的以pg\_temp开头的schema来保证只对当前会话可见,因此,不建议用户在日常操作中手动删除以pg\_temp、pg\_toast\_temp开头的schema。 > > * 如果建表时不指定TEMPORARY/TEMP关键字,而指定表的schema为当前会话的pg\_temp\_开头的schema,则此表会被创建为临时表。 > > * ALTER/DROP全局临时表和索引,如果其它会话正在使用它,禁止操作。 > > * 全局临时表的DDL只会影响当前会话的用户数据和索引。例如truncate、reindex、analyze只对当前会话有效。 * **table\_name** 要创建的表名。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新表中要创建的字段名。 取值范围:字符串,要符合标识符的命名规范。 注:若没有指定字段类型,则替换源表字段名;若指定字段类型,请参考**data\_type**参数介绍。 * **data\_type** 指定新表中字段的类型。 若源表中不含该字段名,则新增该字段。 若源表中含有该字段名,且源表中的字段类型不可转化为指定data\_type类型,则报错;否则,新表中该字段类型改为指定类型。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。参数的详细说明如下所示。 * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数只对行存表有效。 取值范围:10~100 * ORIENTATION 取值范围: COLUMN:表的数据将以列式存储。 ROW(缺省值):表的数据将以行式存储。 * COMPRESSION 指定表数据的压缩级别,它决定了表数据的压缩比以及压缩时间。一般来讲,压缩级别越高,压缩比也越大,压缩时间也越长;反之亦然。实际压缩比取决于加载的表数据的分布特征。 取值范围: 列存表的有效值为YES/NO/LOW/MIDDLE/HIGH,默认值为LOW。 行存表不支持压缩。 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000 * **ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP }** ON COMMIT选项决定在事务中执行创建临时表操作,当事务提交时,此临时表的后续操作。有以下三个选项,当前仅支持PRESERVE ROWS和DELETE ROWS选项。 * PRESERVE ROWS(缺省值):提交时不对临时表执行任何操作,临时表及其表数据保持不变。 * DELETE ROWS:提交时删除临时表中数据。 * DROP:提交时删除此临时表。只支持删除本地临时表,不支持删除全局临时表。 * **COMPRESS / NOCOMPRESS** 创建一个新表时,需要在创建表语句中指定关键字COMPRESS,这样,当对该表进行批量插入时就会触发压缩特性。该特性会在页范围内扫描所有元组数据,生成字典、压缩元组数据并进行存储。指定关键字NOCOMPRESS则不对表进行压缩。行存表不支持压缩。该参数已废弃,列存表请使用COMPRESSION修改压缩等级。 缺省值:NOCOMPRESS,即不对元组数据进行压缩。 * **TABLESPACE tablespace\_name** 指定新表将要在tablespace\_name表空间内创建。如果没有声明,将使用默认表空间。 * **\[ REPLACE / IGNORE ]** 若有唯一性约束列,插入数据时,对重复数据的处理行为进行设置。 * **DISTRIBUTE BY** 指定表如何分布和复制。当前版本不支持。 * **TO { GROUP group\_name | GROUP ( nodename \[ , ... ] ) }** TO GROUP指定表所在的GROUP,TO NODE主要供内部扩容工具使用。当前版本不支持。 * **AS query** 一个SELECT VALUES命令。 * **\[ WITH \[ NO ] DATA ]** 创建表时,是否也插入查询到的数据。默认是要数据,选择“NO”参数时,则不要数据。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 ## 示例 ``` --创建一个表tpcds.store_returns表。 openGauss=# CREATE TABLE tpcds.store_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, sr_item_sk VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER ); --创建一个表tpcds.store_returns_t1并插入tpcds.store_returns表中sr_item_sk字段中大于16的数值。 openGauss=# CREATE TABLE tpcds.store_returns_t1 AS SELECT * FROM tpcds.store_returns WHERE sr_item_sk > '4795'; --使用tpcds.store_returns拷贝一个新表tpcds.store_returns_t2。 openGauss=# CREATE TABLE tpcds.store_returns_t2 AS table tpcds.store_returns; --B模式下 openGauss=# CREATE TABLE tpcds.store_returns_t3(newcol INTEGER) AS table tpcds.store_returns; --删除表。 openGauss=# DROP TABLE tpcds.store_returns_t1 ; openGauss=# DROP TABLE tpcds.store_returns_t2 ; openGauss=# DROP TABLE tpcds.store_returns_t3 ; openGauss=# DROP TABLE tpcds.store_returns; ``` ## 相关链接 [CREATE TABLE](create_table.md),[SELECT](select.md) --- --- url: /en/docs/latest-lite/sql_reference/create_table_inherits.md --- # CREATE TABLE INHERITS ## Function **CREATE TABLE AS** creates a inheritance table from the results of a query. The child table of an inherited table can fully inherit the parent table structure, or add columns base on the parent table structure, and can inherit multiple parent tables or perform secondary inheritance. The inheritance table has a configurable GUC parameter **sql\_inheritance** (default on) controls whether operations on the parent table can access the child table. By default, the parent table can query all data including the child table. When sql\_inheritance closed, the parent table can only query/update itself. The inheritance table has the following characteristics: * Table access permissions are not automatically inherited. * use **/d+ father** to view all child tables of the parent table. * Temporary tables can inherit both temporary and regular tables, while regular tables cannot inherit temporary tables. * When the columns of multiple parent tables are the same, they will be merged, and if they are different, an error will be thrown. * When there are child tables, the parent table cannot be deleted. If the parent table is deleted using cascade, the child table will also be deleted. * When not using including all clause, the child table will only inherit the non null constraints, default value constraints, and check constraints of the parent table (the modification of these constraints by the parent table will be synchronized with the child table). * When using including all clause, child tables can inherit additional index constraints, unique constraints, primary key constraints, and foreign key of the parent table (but modifications made by the parent table to these constraints will not synchronize with the child table). * When not using like parent\_name clause, the parent table deletes a column, the child table columns will also be deleted. * When using like parent\_name clause, the child table has independent columns with the same name as the parent table, and deleting columns from the parent table will not affect the child table. * If the foreign key f\_id specifies the foreign table t1, and t2 is a child table of t1. There is data with id 3 in t2, but there is no data with id 3 in t1, then f\_id cannot be 3, cause foreign key constraint only contains the data of the specified table and does not include the child tables of that table. ## Precautions * The inheritance table function conflicts with the multi table update function of MySQL, and it is not allowed to create an inheritance table in the B database. * It does not support the coexistence of inheritance and partitioned tables or MOT tables (and other foreign table). * Supports ustore and segment page, but cannot use the "like parent\_name including all" statement in ustore and segment page. * Column storage does not support inheriting tables. ## Syntax ``` CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] TABLE table_name( [ {LIKE parent_name} [INCLUDING ALL]} ] ) [ INHERITS ( parent_table [, ... ] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ]; ``` ## Parameter Description * **UNLOGGED** Specifies that the table is created as an unlogged table. Data written to unlogged tables is not written to the WALs, which makes them considerably faster than ordinary tables. However, they are not crash-safe: an unlogged table is automatically truncated after a crash or unclean shutdown. Contents of an unlogged table are also not replicated to standby servers. Any indexes created on an unlogged table are automatically unlogged as well. * Usage scenario: Unlogged tables do not ensure data security. Users can back up data before using unlogged tables; for example, users should back up the data before a system upgrade. * Troubleshooting: If data is missing in the indexes of unlogged tables due to some unexpected operations such as an unclean shutdown, users should re-create the indexes with errors. * **GLOBAL | LOCAL** When creating a temporary table, you can specify the **GLOBAL** or **LOCAL** keyword before **TEMP** or **TEMPORARY**. If the keyword **GLOBAL** is specified, openGauss creates a global temporary table. Otherwise, openGauss creates a local temporary table. * **TEMPORARY | TEMP** If **TEMP** or **TEMPORARY** is specified, the created table is a temporary table. Temporary tables are classified into global temporary tables and local temporary tables. If the keyword **GLOBAL** is specified when a temporary table is created, the table is a global temporary table. Otherwise, the table is a local temporary table. The metadata of the global temporary table is visible to all sessions. After the sessions end, the metadata still exists. The user data, indexes, and statistics of a session are isolated from those of another session. Each session can only view and modify the data submitted by itself. Global temporary tables have two schemas: **ON COMMIT PRESERVE ROWS** and **ON COMMIT PRESERVE ROWS**. In session-based **ON COMMIT PRESERVE ROWS** schema, user data is automatically cleared when a session ends. In transaction-based **ON COMMIT DELETE ROWS** schema, user data is automatically cleared when the commit or rollback operation is performed. If the **ON COMMIT** option is not specified during table creation, the session level is used by default. Different from local temporary tables, you can specify a schema that does not start with **pg\_temp\_** when creating a global temporary table. A local temporary table is automatically dropped at the end of the current session. Therefore, you can create and use temporary tables in the current session as long as the connected database node in the session is normal. Temporary tables are created only in the current session. If a DDL statement involves operations on temporary tables, a DDL error will be generated. Therefore, you are not advised to perform operations on temporary tables in DDL statements. **TEMP** is equivalent to **TEMPORARY**. > \[!TIP]NOTICE > > * Local temporary tables are visible to the current session through the schema starting with **pg\_temp** start. Users should not delete schema started with **pg\_temp** or **pg\_toast\_temp**. > * If **TEMPORARY** or **TEMP** is not specified when you create a table but its schema is set to that starting with **pg\_temp\_** in the current session, the table will be created as a temporary table. > * If global temporary tables and indexes are being used by other sessions, do not perform **ALTER** or **DROP**. > * The DDL of a global temporary table affects only the user data and indexes of the current session. For example, **TRUNCATE**, **REINDEX**, and **ANALYZE** are valid only for the current session. * **table\_name** Specifies the name of the child table to be created. Value range: a string. It must comply with the naming convention. * **parent\_name** Specifies the name of parent table to inherit. Value range: a string. It must comply with the naming convention. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. See details of parameters below. * FILLFACTOR The fill factor of a table is a percentage from 10 to 100. **100** (complete filling) is the default value. When a smaller fill factor is specified, **INSERT** operations pack table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives **UPDATE** a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter is only valid for row–store tables. Value range: 10–100 * ORIENTATION Value range: **COLUMN**: The data will be stored in columns. **ROW** (default value): The data will be stored in rows. * COMPRESSION Specifies the compression level of table data. It determines the compression ratio and time. Generally, the higher the level of compression, the higher the ratio, the longer the time; and the lower the level of compression, the lower the ratio, the shorter the time. The actual compression ratio depends on the distribution mode of table data loaded. Value range: The valid values for column-store tables are **YES**, **NO**, **LOW**, **MIDDLE**, and **HIGH**, and the default value is **LOW**. Row-store tables do not support compression. * MAX\_BATCHROW Specifies the maximum number of rows in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000 * **TABLESPACE tablespace\_name** Specifies that the new table will be created in the **tablespace\_name** tablespace. If not specified, the default tablespace is used. ## Examples ``` --Create two parent tables openGauss=# CREATE TABLE father ( id int NOT NULL, md_attr CHARACTER VARYING(32) UNIQUE, wai_id int references fa_wai(ID), num int DEFAULT 2, salary REAL CHECK(SALARY > 0), CONSTRAINT pk_father_z82rgvsefn PRIMARY KEY (id) ); openGauss=# CREATE TABLE father2 ( id int UNIQUE, md_attr CHARACTER VARYING(32) not null, CONSTRAINT pk_father2_z82rgvsefn PRIMARY KEY (id) ); --Create a child table, when parent table deletes columns, child table columns will be deleted openGauss=# CREATE TABLE kid_2021() inherits(father); --Create a child table using like parent_name clause, --when the parent table deletes columns, child table columns will not be deleted openGauss=# CREATE TABLE kid_2021(like father) inherits(father); --Create a subtable using like father including all clause --to inherit additional primary key constraints and unique constraints openGauss=# CREATE TABLE kid_2022(like father including all) inherits(father); --Multiple tables inherit, parent tables with the same column will be merged openGauss=# CREATE TABLE kid_2023() inherits(father,father2); --Temporary tables can be child tables of regular tables or temporary tables, --but cannot be parent tables of regular tables. openGauss=# CREATE TEMPORARY TABLES kid_2024() inherits(father); --Query the data of the parent and child tables, you can add * to the table name or omit it openGauss=# select * from father*; openGauss=# select * from father; --Only query the data of the parent table openGauss=# select * from only father; --drop tables openGauss=# drop table father cascade; openGauss=# drop table father2 cascade; ``` ## Helpful Links [CREATE TABLE](create_table.md) and [ALTER TABLE INHERIT](alter_table_inherit.md) --- --- url: /en/docs/latest/sql_reference/create_table_inherits.md --- # CREATE TABLE INHERITS ## Function **CREATE TABLE AS** creates a inheritance table from the results of a query. The child table of an inherited table can fully inherit the parent table structure, or add columns base on the parent table structure, and can inherit multiple parent tables or perform secondary inheritance. The inheritance table has a configurable GUC parameter **sql\_inheritance** (default on) controls whether operations on the parent table can access the child table. By default, the parent table can query all data including the child table. When sql\_inheritance closed, the parent table can only query/update itself. The inheritance table has the following characteristics: * Table access permissions are not automatically inherited. * use **/d+ father** to view all child tables of the parent table. * Temporary tables can inherit both temporary and regular tables, while regular tables cannot inherit temporary tables. * When the columns of multiple parent tables are the same, they will be merged, and if they are different, an error will be thrown. * When there are child tables, the parent table cannot be deleted. If the parent table is deleted using cascade, the child table will also be deleted. * When not using including all clause, the child table will only inherit the non null constraints, default value constraints, and check constraints of the parent table (the modification of these constraints by the parent table will be synchronized with the child table). * When using including all clause, child tables can inherit additional index constraints, unique constraints, primary key constraints, and foreign key of the parent table (but modifications made by the parent table to these constraints will not synchronize with the child table). * When not using like parent\_name clause, the parent table deletes a column, the child table columns will also be deleted. * When using like parent\_name clause, the child table has independent columns with the same name as the parent table, and deleting columns from the parent table will not affect the child table. * If the foreign key f\_id specifies the foreign table t1, and t2 is a child table of t1. There is data with id 3 in t2, but there is no data with id 3 in t1, then f\_id cannot be 3, cause foreign key constraint only contains the data of the specified table and does not include the child tables of that table. ## Precautions * The inheritance table function conflicts with the multi table update function of MySQL, and it is not allowed to create an inheritance table in the B database. * It does not support the coexistence of inheritance and partitioned tables or MOT tables (and other foreign table). * Supports ustore and segment page, but cannot use the "like parent\_name including all" statement in ustore and segment page. * Column storage does not support inheriting tables. ## Syntax ``` CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] TABLE table_name( [ {LIKE parent_name} [INCLUDING ALL]} ] ) [ INHERITS ( parent_table [, ... ] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ]; ``` ## Parameter Description * **UNLOGGED** Specifies that the table is created as an unlogged table. Data written to unlogged tables is not written to the WALs, which makes them considerably faster than ordinary tables. However, they are not crash-safe: an unlogged table is automatically truncated after a crash or unclean shutdown. Contents of an unlogged table are also not replicated to standby servers. Any indexes created on an unlogged table are automatically unlogged as well. * Usage scenario: Unlogged tables do not ensure data security. Users can back up data before using unlogged tables; for example, users should back up the data before a system upgrade. * Troubleshooting: If data is missing in the indexes of unlogged tables due to some unexpected operations such as an unclean shutdown, users should re-create the indexes with errors. * **GLOBAL | LOCAL** When creating a temporary table, you can specify the **GLOBAL** or **LOCAL** keyword before **TEMP** or **TEMPORARY**. If the keyword **GLOBAL** is specified, openGauss creates a global temporary table. Otherwise, openGauss creates a local temporary table. * **TEMPORARY | TEMP** If **TEMP** or **TEMPORARY** is specified, the created table is a temporary table. Temporary tables are classified into global temporary tables and local temporary tables. If the keyword **GLOBAL** is specified when a temporary table is created, the table is a global temporary table. Otherwise, the table is a local temporary table. The metadata of the global temporary table is visible to all sessions. After the sessions end, the metadata still exists. The user data, indexes, and statistics of a session are isolated from those of another session. Each session can only view and modify the data submitted by itself. Global temporary tables have two schemas: **ON COMMIT PRESERVE ROWS** and **ON COMMIT PRESERVE ROWS**. In session-based **ON COMMIT PRESERVE ROWS** schema, user data is automatically cleared when a session ends. In transaction-based **ON COMMIT DELETE ROWS** schema, user data is automatically cleared when the commit or rollback operation is performed. If the **ON COMMIT** option is not specified during table creation, the session level is used by default. Different from local temporary tables, you can specify a schema that does not start with **pg\_temp\_** when creating a global temporary table. A local temporary table is automatically dropped at the end of the current session. Therefore, you can create and use temporary tables in the current session as long as the connected database node in the session is normal. Temporary tables are created only in the current session. If a DDL statement involves operations on temporary tables, a DDL error will be generated. Therefore, you are not advised to perform operations on temporary tables in DDL statements. **TEMP** is equivalent to **TEMPORARY**. > \[!TIP]NOTICE > > * Local temporary tables are visible to the current session through the schema starting with **pg\_temp** start. Users should not delete schema started with **pg\_temp** or **pg\_toast\_temp**. > * If **TEMPORARY** or **TEMP** is not specified when you create a table but its schema is set to that starting with **pg\_temp\_** in the current session, the table will be created as a temporary table. > * If global temporary tables and indexes are being used by other sessions, do not perform **ALTER** or **DROP**. > * The DDL of a global temporary table affects only the user data and indexes of the current session. For example, **TRUNCATE**, **REINDEX**, and **ANALYZE** are valid only for the current session. * **table\_name** Specifies the name of the child table to be created. Value range: a string. It must comply with the naming convention. * **parent\_name** Specifies the name of parent table to inherit. Value range: a string. It must comply with the naming convention. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. See details of parameters below. * FILLFACTOR The fill factor of a table is a percentage from 10 to 100. **100** (complete filling) is the default value. When a smaller fill factor is specified, **INSERT** operations pack table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives **UPDATE** a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter is only valid for row–store tables. Value range: 10–100 * ORIENTATION Value range: **COLUMN**: The data will be stored in columns. **ROW** (default value): The data will be stored in rows. * COMPRESSION Specifies the compression level of table data. It determines the compression ratio and time. Generally, the higher the level of compression, the higher the ratio, the longer the time; and the lower the level of compression, the lower the ratio, the shorter the time. The actual compression ratio depends on the distribution mode of table data loaded. Value range: The valid values for column-store tables are **YES**, **NO**, **LOW**, **MIDDLE**, and **HIGH**, and the default value is **LOW**. Row-store tables do not support compression. * MAX\_BATCHROW Specifies the maximum number of rows in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000 * **TABLESPACE tablespace\_name** Specifies that the new table will be created in the **tablespace\_name** tablespace. If not specified, the default tablespace is used. ## Examples ``` --Create two parent tables openGauss=# CREATE TABLE father ( id int NOT NULL, md_attr CHARACTER VARYING(32) UNIQUE, wai_id int references fa_wai(ID), num int DEFAULT 2, salary REAL CHECK(SALARY > 0), CONSTRAINT pk_father_z82rgvsefn PRIMARY KEY (id) ); openGauss=# CREATE TABLE father2 ( id int UNIQUE, md_attr CHARACTER VARYING(32) not null, CONSTRAINT pk_father2_z82rgvsefn PRIMARY KEY (id) ); --Create a child table, when parent table deletes columns, child table columns will be deleted openGauss=# CREATE TABLE kid_2021() inherits(father); --Create a child table using like parent_name clause, --when the parent table deletes columns, child table columns will not be deleted openGauss=# CREATE TABLE kid_2021(like father) inherits(father); --Create a subtable using like father including all clause --to inherit additional primary key constraints and unique constraints openGauss=# CREATE TABLE kid_2022(like father including all) inherits(father); --Multiple tables inherit, parent tables with the same column will be merged openGauss=# CREATE TABLE kid_2023() inherits(father,father2); --Temporary tables can be child tables of regular tables or temporary tables, --but cannot be parent tables of regular tables. openGauss=# CREATE TEMPORARY TABLES kid_2024() inherits(father); --Query the data of the parent and child tables, you can add * to the table name or omit it openGauss=# select * from father*; openGauss=# select * from father; --Only query the data of the parent table openGauss=# select * from only father; --drop tables openGauss=# drop table father cascade; openGauss=# drop table father2 cascade; ``` ## Helpful Links [CREATE TABLE](create_table.md) and [ALTER TABLE INHERIT](alter_table_inherit.md) --- --- url: /zh/docs/latest-lite/sql_reference/create_table_inherits.md --- # CREATE TABLE INHERITS ## 功能描述 根据查询结果创建继承表。继承表的子表可以完全继承父表结构,也可以在父表结构的基础上添加字段,并且可以继承多父表或进行次级继承。 继承表有一个可设置的guc参数sql\_inheritance(默认为on),它控制父表的操作是否可以访问子表,默认情况下父表可以查询包含子表在内的所有数据,关闭它时父表的只能查询/更新自己。 继承表具有以下特点: * 表访问权限并不会被自动继承。 * 可以用/d+ father来查看父表下所有子表。 * 临时表可以继承临时表和普通表,普通表不能继承临时表。 * 当多个父表的字段相同时会进行融合,不同则会抛出错误。 * 存在子表时无法删除父表,用cascade删除父表的话,子表也会被删除。 * 子表不使用including all子句只会继承父表的非空、默认值和检查三种约束(父表对这几种约束的修改会同步作用于子表)。 * 子表使用including all子句才可以额外继承索引、唯一、主键、外键约束(但父表对这几种约束的修改不会同步作用于子表)。 * 子表不使用like parent\_name子句时,父表对列进行删除的话,子表列也会被删除。 * 子表使用like parent\_name子句时,子表拥有和父表同名的独立字段,当父表对列进行删除时不会作用于子表。 * 假如外键f\_id指定外表t1,而t2是t1的子表,t2中存在id为3的数据,但t1中不存在id为3的数据,那么f\_id不能是3,外键约束只包含指定的外表的数据,不包含该外表的子表。 ## 注意事项 * 继承表功能和mysql的多表更新功能冲突,不可以在B库建继承表。 * 不支持继承和分区表或者MOT表(及其他外表)同时存在的情况。 * 支持Ustore和段页式,但这两种情况不能使用"like fathername including all"语句。 * 列存不支持继承表。 ## 语法格式 ``` CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] TABLE table_name( [ {LIKE parent_name} [INCLUDING ALL]} ] ) [ INHERITS ( parent_table [, ... ] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ]; ``` > * 更多参数细节说明可参考[CREATE TABLE](create_table.md)章节。 ## 参数说明 * **UNLOGGED** 指定表为非日志表。在非日志表中写入的数据不会被写入到预写日志中,这样就会比普通表快很多。但是,它也是不安全的,非日志表在冲突或异常关机后会被自动删截。非日志表中的内容也不会被复制到备用服务器中。在该类表中创建的索引也不会被自动记录。 * 使用场景:非日志表不能保证数据的安全性,用户应该在确保数据已经做好备份的前提下使用,例如系统升级时进行数据的备份。 * 故障处理:当异常关机等操作导致非日志表上的索引发生数据丢失时,用户应该对发生错误的索引进行重建。 * **GLOBAL | LOCAL** 创建临时表时可以在TEMP或TEMPORARY前指定GLOBAL或LOCAL关键字。如果指定GLOBAL关键字,openGauss会创建全局临时表,否则openGauss会创建本地临时表。 * **TEMPORARY | TEMP** 如果指定TEMP或TEMPORARY关键字,则创建的表为临时表。临时表分为全局临时表和本地临时表两种类型。创建临时表时如果指定GLOBAL关键字则为全局临时表,否则为本地临时表。 全局临时表的元数据对所有会话可见,会话结束后元数据继续存在。会话与会话之间的用户数据、索引和统计信息相互隔离,每个会话只能看到和更改自己提交的数据。全局临时表有两种模式:一种是基于会话级别的(ON COMMIT PRESERVE ROWS), 当会话结束时自动清空用户数据;一种是基于事务级别的(ON COMMIT DELETE ROWS), 当执行commit或rollback时自动清空用户数据。建表时如果没有指定ON COMMIT选项,则缺省为会话级别。与本地临时表不同,全局临时表建表时可以指定非pg\_temp\_开头的schema。 本地临时表只在当前会话可见,本会话结束后会自动删除。因此,在除当前会话连接的数据库节点故障时,仍然可以在当前会话上创建和使用临时表。由于临时表只在当前会话创建,对于涉及对临时表操作的DDL语句,会产生DDL失败的报错。因此,建议DDL语句中不要对临时表进行操作。TEMP和TEMPORARY等价。 > \[!TIP]须知 > > * 本地临时表通过每个会话独立的以pg\_temp开头的schema来保证只对当前会话可见,因此,不建议用户在日常操作中手动删除以pg\_temp,pg\_toast\_temp开头的schema。 > * 如果建表时不指定TEMPORARY/TEMP关键字,而指定表的schema为当前会话的pg\_temp\_开头的schema,则此表会被创建为临时表。 > * ALTER/DROP全局临时表和索引,如果其它会话正在使用它,禁止操作。 > * 全局临时表的DDL只会影响当前会话的用户数据和索引。例如truncate、reindex、analyze只对当前会话有效。 * **table\_name** 要创建的继承表子表的表名。 取值范围:字符串,要符合标识符的命名规范。 * **parent\_name** 要继承的父表的表名。 取值范围:字符串,要符合标识符的命名规范。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。参数的详细说明如下所示。 * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数只对行存表有效。 取值范围:10~100 * ORIENTATION 取值范围: COLUMN:表的数据将以列式存储。 ROW(缺省值):表的数据将以行式存储。 * COMPRESSION 指定表数据的压缩级别,它决定了表数据的压缩比以及压缩时间。一般来讲,压缩级别越高,压缩比也越大,压缩时间也越长;反之亦然。实际压缩比取决于加载的表数据的分布特征。 取值范围: 列存表的有效值为YES/NO/LOW/MIDDLE/HIGH,默认值为LOW。 行存表不支持压缩。 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000 * **TABLESPACE tablespace\_name** 指定新表将要在tablespace\_name表空间内创建。如果没有声明,将使用默认表空间。 ## 示例 ``` --创建两张父表 openGauss=# CREATE TABLE father ( id int NOT NULL, md_attr CHARACTER VARYING(32) UNIQUE, num int DEFAULT 2, salary REAL CHECK(SALARY > 0), CONSTRAINT pk_father_z82rgvse PRIMARY KEY (id) ); openGauss=# CREATE TABLE father2 ( id int UNIQUE, md_attr CHARACTER VARYING(32) not null, CONSTRAINT pk_father2_z82rgvse PRIMARY KEY (id) ); --创建一张子表,父表删除列时子表列会被删除 openGauss=# CREATE TABLE kid_2021() inherits(father); --使用like father创建一张子表,父表删除列时子表列不会被删除 openGauss=# CREATE TABLE kid_2021(like father) inherits(father); --使用like father including all创建一张子表,可额外继承主键约束和唯一约束 openGauss=# CREATE TABLE kid_2022(like father including all) inherits(father); --多表继承,父表同列会被合并 openGauss=# CREATE TABLE kid_2023() inherits(father,father2); --临时表可以是普通表的子表,但不可以是普通表的父表,临时表可以继承临时表 openGauss=# CREATE TEMPORARY TABLES kid_2024() inherits(father); --查询父表及子表的数据,可以在表名加上*,也可以省略不加 openGauss=# select * from father*; openGauss=# select * from father; --只查询父表的数据 openGauss=# select * from only father; --删除表 openGauss=# drop table father cascade; openGauss=# drop table father2 cascade; ``` ## 相关链接 [CREATE TABLE](create_table.md),[ALTER TABLE INHERIT](alter_table_inherit.md) --- --- url: /zh/docs/latest/sql_reference/create_table_inherits.md --- # CREATE TABLE INHERITS ## 功能描述 根据查询结果创建继承表。继承表的子表可以完全继承父表结构,也可以在父表结构的基础上添加字段,并且可以继承多父表或进行次级继承。 继承表有一个可设置的guc参数sql\_inheritance(默认为on),它控制父表的操作是否可以访问子表,默认情况下父表可以查询包含子表在内的所有数据,关闭它时父表的只能查询/更新自己。 继承表具有以下特点: * 表访问权限并不会被自动继承。 * 可以用/d+ father来查看父表下所有子表。 * 临时表可以继承临时表和普通表,普通表不能继承临时表。 * 当多个父表的字段相同时会进行融合,不同则会抛出错误。 * 存在子表时无法删除父表,用cascade删除父表的话,子表也会被删除。 * 子表不使用including all子句只会继承父表的非空、默认值和检查三种约束(父表对这几种约束的修改会同步作用于子表)。 * 子表使用including all子句才可以额外继承索引、唯一、主键、外键约束(但父表对这几种约束的修改不会同步作用于子表)。 * 子表不使用like parent\_name子句时,父表对列进行删除的话,子表列也会被删除。 * 子表使用like parent\_name子句时,子表拥有和父表同名的独立字段,当父表对列进行删除时不会作用于子表。 * 假如外键f\_id指定外表t1,而t2是t1的子表,t2中存在id为3的数据,但t1中不存在id为3的数据,那么f\_id不能是3,外键约束只包含指定的外表的数据,不包含该外表的子表。 ## 注意事项 * 继承表功能和mysql的多表更新功能冲突,不可以在B库建继承表。 * 不支持继承和分区表或者MOT表(及其他外表)同时存在的情况。 * 支持Ustore和段页式,但这两种情况不能使用"like fathername including all"语句。 * 列存不支持继承表。 ## 语法格式 ``` CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] TABLE table_name( [ {LIKE parent_name} [INCLUDING ALL]} ] ) [ INHERITS ( parent_table [, ... ] ) ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ TABLESPACE tablespace_name ]; ``` > * 更多参数细节说明可参考[CREATE TABLE](create_table.md)章节。 ## 参数说明 * **UNLOGGED** 指定表为非日志表。在非日志表中写入的数据不会被写入到预写日志中,这样就会比普通表快很多。但是,它也是不安全的,非日志表在冲突或异常关机后会被自动删截。非日志表中的内容也不会被复制到备用服务器中。在该类表中创建的索引也不会被自动记录。 * 使用场景:非日志表不能保证数据的安全性,用户应该在确保数据已经做好备份的前提下使用,例如系统升级时进行数据的备份。 * 故障处理:当异常关机等操作导致非日志表上的索引发生数据丢失时,用户应该对发生错误的索引进行重建。 * **GLOBAL | LOCAL** 创建临时表时可以在TEMP或TEMPORARY前指定GLOBAL或LOCAL关键字。如果指定GLOBAL关键字,openGauss会创建全局临时表,否则openGauss会创建本地临时表。 * **TEMPORARY | TEMP** 如果指定TEMP或TEMPORARY关键字,则创建的表为临时表。临时表分为全局临时表和本地临时表两种类型。创建临时表时如果指定GLOBAL关键字则为全局临时表,否则为本地临时表。 全局临时表的元数据对所有会话可见,会话结束后元数据继续存在。会话与会话之间的用户数据、索引和统计信息相互隔离,每个会话只能看到和更改自己提交的数据。全局临时表有两种模式:一种是基于会话级别的(ON COMMIT PRESERVE ROWS), 当会话结束时自动清空用户数据;一种是基于事务级别的(ON COMMIT DELETE ROWS), 当执行commit或rollback时自动清空用户数据。建表时如果没有指定ON COMMIT选项,则缺省为会话级别。与本地临时表不同,全局临时表建表时可以指定非pg\_temp\_开头的schema。 本地临时表只在当前会话可见,本会话结束后会自动删除。因此,在除当前会话连接的数据库节点故障时,仍然可以在当前会话上创建和使用临时表。由于临时表只在当前会话创建,对于涉及对临时表操作的DDL语句,会产生DDL失败的报错。因此,建议DDL语句中不要对临时表进行操作。TEMP和TEMPORARY等价。 > \[!TIP]须知 > > * 本地临时表通过每个会话独立的以pg\_temp开头的schema来保证只对当前会话可见,因此,不建议用户在日常操作中手动删除以pg\_temp,pg\_toast\_temp开头的schema。 > * 如果建表时不指定TEMPORARY/TEMP关键字,而指定表的schema为当前会话的pg\_temp\_开头的schema,则此表会被创建为临时表。 > * ALTER/DROP全局临时表和索引,如果其它会话正在使用它,禁止操作。 > * 全局临时表的DDL只会影响当前会话的用户数据和索引。例如truncate、reindex、analyze只对当前会话有效。 * **table\_name** 要创建的继承表子表的表名。 取值范围:字符串,要符合标识符的命名规范。 * **parent\_name** 要继承的父表的表名。 取值范围:字符串,要符合标识符的命名规范。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。参数的详细说明如下所示。 * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数只对行存表有效。 取值范围:10~100 * ORIENTATION 取值范围: COLUMN:表的数据将以列式存储。 ROW(缺省值):表的数据将以行式存储。 * COMPRESSION 指定表数据的压缩级别,它决定了表数据的压缩比以及压缩时间。一般来讲,压缩级别越高,压缩比也越大,压缩时间也越长;反之亦然。实际压缩比取决于加载的表数据的分布特征。 取值范围: 列存表的有效值为YES/NO/LOW/MIDDLE/HIGH,默认值为LOW。 行存表不支持压缩。 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000 * **TABLESPACE tablespace\_name** 指定新表将要在tablespace\_name表空间内创建。如果没有声明,将使用默认表空间。 ## 示例 ``` --创建两张父表 openGauss=# CREATE TABLE father ( id int NOT NULL, md_attr CHARACTER VARYING(32) UNIQUE, num int DEFAULT 2, salary REAL CHECK(SALARY > 0), CONSTRAINT pk_father_z82rgvse PRIMARY KEY (id) ); openGauss=# CREATE TABLE father2 ( id int UNIQUE, md_attr CHARACTER VARYING(32) not null, CONSTRAINT pk_father2_z82rgvse PRIMARY KEY (id) ); --创建一张子表,父表删除列时子表列会被删除 openGauss=# CREATE TABLE kid_2021() inherits(father); --使用like father创建一张子表,父表删除列时子表列不会被删除 openGauss=# CREATE TABLE kid_2021(like father) inherits(father); --使用like father including all创建一张子表,可额外继承主键约束和唯一约束 openGauss=# CREATE TABLE kid_2022(like father including all) inherits(father); --多表继承,父表同列会被合并 openGauss=# CREATE TABLE kid_2023() inherits(father,father2); --临时表可以是普通表的子表,但不可以是普通表的父表,临时表可以继承临时表 openGauss=# CREATE TEMPORARY TABLES kid_2024() inherits(father); --查询父表及子表的数据,可以在表名加上*,也可以省略不加 openGauss=# select * from father*; openGauss=# select * from father; --只查询父表的数据 openGauss=# select * from only father; --删除表 openGauss=# drop table father cascade; openGauss=# drop table father2 cascade; ``` ## 相关链接 [CREATE TABLE](create_table.md),[ALTER TABLE INHERIT](alter_table_inherit.md) --- --- url: /en/docs/latest-lite/sql_reference/create_table_partition.md --- # CREATE TABLE PARTITION ## Function **CREATE TABLE PARTITION** creates a partitioned table. Partitioning refers to splitting what is logically one large table into smaller physical pieces based on specific schemes. The table based on the logic is called a partitioned table, and each physical piece is called a partition. Data is stored on these physical partitions, instead of the logical partitioned table. The common forms of partitioning include range partitioning, interval partitioning, hash partitioning, list partitioning, and value partitioning. Currently, row-store tables support range partitioning, interval partitioning, hash partitioning, and list partitioning. Column-store tables support only range partitioning. In range partitioning, a table is partitioned based on ranges defined by 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. The partitioning policy for range partitioning refers to how data is inserted into partitions. Currently, range partitioning only allows the use of the range partitioning policy. In range partitioning, a 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. Interval partitioning is a special type of range partitioning. Compared with range partitioning, interval value definition is added. When no matching partition can be found for an inserted record, a partition can be automatically created based on the interval value. Interval partitioning supports only table-based partitioning of a list where the data type can be TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE] and DATE. Interval partitioning policy: A record is mapped to a created partition based on the partition key value. If the record can be mapped to a created partition, the record is inserted into the corresponding partition. Otherwise, a partition is automatically created based on the partition key value and table definition information, and then the record is inserted into the new partition. The data range of the new partition is equal to the interval value. In hash partitioning, a modulus and a remainder are specified for each partition based on a column in the table, and records to be inserted into the table are allocated to the corresponding partition, the rows in each partition must meet the following condition: The value of the partition key divided by the specified modulus generates the remainder specified for the partition key. In hash 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. List partitioning is to allocate the records to be inserted into a table to the corresponding partition based on the key values in each partition. The key values do not overlap in different partitions. Create a partition for each group of key values to store corresponding data. In list 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. Partitioning can provide several benefits: * Query performance can be improved drastically in certain situations, particularly when most of the heavily accessed rows of the table are in a single partition or a small number of partitions. Partitioning narrows the range of data search and improves data access efficiency. * In the case of an insert or update operation on most portions of a single partition, performance can be improved by taking advantage of continuous scan of that partition instead of partitions scattered across the whole table. * Frequent loading or deletion operations on records in a separate partition can be accomplished by reading or removing that partition. It also entirely avoids the **VACUUM** overload caused by bulk **DELETE** operations (only for range partitioning). ## Precautions * If the constraint key of the unique constraint and primary key constraint contains all partition keys, a local index is created for the constraints. Otherwise, a global index is created. * Currently, hash partitioning and list partitioning support only single-column partitioning, and do not support multi-column partitioning. * When you have the **INSERT** permission on an interval partitioned table, partitions can be automatically created when you run **INSERT** to write data to the table. * In the **PARTITION FOR (values)** syntax for partitioned tables, values can only be constants. * In the **PARTITION FOR (values)** syntax for partitioned tables, if data type conversion is required for values, you are advised to use forcible type conversion to prevent the implicit type conversion result from being inconsistent with the expected result. * The maximum number of partitions is 1048575. Generally, it is impossible to create so many partitions, because too many partitions may cause insufficient memory. Create partitions based on the value of **local\_syscache\_threshold**. The memory used by the partitioned tables is about (number of partitions x 3/1024) MB. Theoretically, the memory occupied by the partitions cannot be greater than the value of **local\_syscache\_threshold**. In addition, some space must be reserved for other functions. * Currently, the statement specifying a partition cannot perform global index scan. ## Syntax ``` CREATE TABLE [ IF NOT EXISTS ] partition_table_name ( [ { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] }[, ... ] ] ) [ AUTO_INCREMENT [ = ] value ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMMENT {=| } 'text' ] PARTITION BY { {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_less_than_item [COMMENT {=| } 'text'][...][, ... ] )} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_start_end_item [COMMENT {=| } 'text'][...][, ... ] )} | {LIST | HASH (partition_key) (PARTITION partition_name [VALUES (list_values_clause)] opt_table_space [COMMENT {=| } 'text'][...])} } [ { ENABLE | DISABLE } ROW MOVEMENT ]; ``` * **column\_constraint** is as follows: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_e xpr | GENERATED ALWAYS AS ( generation_expr ) STORED | AUTO_INCREMENT UNIQUE index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * **table\_constraint** is as follows: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * **like\_option** is as follows: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS| ALL } ``` * **index\_parameters** is as follows: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * partition\_less\_than\_item: ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } ) [TABLESPACE tablespace_name] ``` * partition\_start\_end\_item: ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` * COMMENT {=| } 'text': In the partition of a partitioned table, this column is meaningless and is used only for syntax compatibility. An alarm is displayed when the syntax is used in the database. ## Parameter Description * **IF NOT EXISTS** Sends a notice, but does not throw an error, if a table with the same name exists. * **partition\_table\_name** Specifies the name of a partitioned table. Value range: a string. It must comply with the identifier naming convention. * **column\_name** Specifies the name of a column to be created in the new table. Value range: a string. It must comply with the identifier naming convention. * **data\_type** Specifies the data type of the column. * **COLLATE collation** Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the **select \* from pg\_collation;** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **CONSTRAINT constraint\_name** Specifies the name of a column or table constraint. The optional constraint clauses specify constraints that new or updated rows must satisfy for an insert or update operation to succeed. There are two ways to define constraints: * A column constraint is defined as part of a column definition, and it is bound to a particular column. * A table constraint is not bound to a particular column but can apply to more than one column. > \[!TIP]NOTICE > > constraint\_name is optional in B-compatible mode (**sql\_compatibility = 'B'**). For other modes, constraint\_name must be added. * **index\_name** Specifies an index name. > \[!TIP]NOTICE > > * index\_name is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * For foreign key constraints, if constraint\_name and index\_name are specified at the same time, constraint\_name is used as the index name. > * For a unique key constraint, if both constraint\_name and index\_name are specified, index\_name is used as the index name. * **USING method** Specifies the name of the index method to be used. For details about the value range, see [USING method](create_index.md#en-us_topic_0283136578_en-us_topic_0237122106_en-us_topic_0059777455_s82e47e35c54c477094dcafdc90e5d85a). > \[!TIP]NOTICE > > * The USING method is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * In B-compatible mode, if USING method is not specified, the default index method is btree for ASTORE or ubtree for USTORE. * **ASC | DESC** **ASC** specifies an ascending (default) sort order. **DESC** specifies a descending sort order. > \[!TIP]NOTICE > > ASC|DESC is supported only in B-compatible databases (sql\_compatibility = 'B'). * **LIKE source\_table \[ like\_option ... ]** Specifies a table from which the new table automatically copies all column names, their data types, and their not-null constraints. Unlike **INHERITS**, the new table and original table are decoupled after creation is complete. Changes to the original table will not be applied to the new table, and it is not possible to include data of the new table in scans of the original table. * Default expressions for the copied column definitions will be copied only if **INCLUDING DEFAULTS** is specified. The default behavior is to exclude default expressions, resulting in the copied columns in the new table having default values **NULL**. * If **INCLUDING GENERATED** is specified, the generated expression of the source table column is copied to the new table. By default, the generated expression is not copied. * Not-null constraints are always copied to the new table. **CHECK** constraints will only be copied if **INCLUDING CONSTRAINTS** is specified; other types of constraints will never be copied. These rules also apply to column constraints and table constraints. * Unlike those of **INHERITS**, columns and constraints copied by **LIKE** are not merged with similarly named columns and constraints. If the same name is specified explicitly or in another **LIKE** clause, an error is reported. * Any indexes on the original table will not be created on the new table, unless the **INCLUDING INDEXES** clause is specified. * **STORAGE** settings for the copied column definitions are copied only if **INCLUDING STORAGE** is specified. The default behavior is to exclude **STORAGE** settings. * If **INCLUDING COMMENTS** is specified, comments for the copied columns, constraints, and indexes are copied. The default behavior is to exclude comments. * If **INCLUDING RELOPTIONS** is specified, the new table will copy the storage parameter (that is, **WITH** clause) of the source table. The default behavior is to exclude partition definition of the storage parameter of the source table. * **INCLUDING ALL** contains the meaning of **INCLUDING DEFAULTS**, **INCLUDING CONSTRAINTS**, **INCLUDING INDEXES**, **INCLUDING STORAGE**, **INCLUDING COMMENTS**, **INCLUDING PARTITION**, and **INCLUDING RELOPTIONS**. * **AUTO\_INCREMENT \[ = ] value** This clause specifies an initial value for an auto-increment column. The value must be a positive integer and cannot exceed 2127-1. > \[!TIP]NOTICE > > This clause takes effect only when **sql\_compatibility** is set to **B**. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. Optional parameters are as follows: * FILLFACTOR The fill factor of a table is a percentage from 10 to 100. **100** (complete filling) is the default value. When a smaller fill factor is specified, **INSERT** operations pack table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives **UPDATE** a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter has no meaning for column-store tables. Value range: 10–100 * ORIENTATION Determines the storage mode of the data in the table. Value range: * **COLUMN**: The data will be stored in columns. * **ROW** (default value): The data will be stored in rows. > \[!TIP]NOTICE > > **orientation** cannot be modified. * COMPRESSTYPE Sets the preprocessing of row-store table compression differentiation. This parameter can be used together only with **COMPRESS\_BYTE\_CONVERT**. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * COMPRESS\_LEVEL Specifies the row-store table compression algorithm level. This parameter is valid only when **COMPRESSTYPE** is set to **2** or **4**. A higher compression level indicates a better table compression effect and a slower table access speed. (Only common tables in the Astore engine are supported.) Value range: –31 to 31. The default value is **0**. * COMPRESS\_CHUNK\_SIZE Specifies the size of a row-store table compression chunk. A smaller chunk size indicates a better compression effect, and a larger data dispersion degree indicates a slower table access speed. (Only common tables in the Astore engine are supported.) Value range: subject to the page size. When the page size is 8 KB, the value can be **512**, **1024**, **2048**, or **4096**. Default value: **4096** * COMPRESS\_PREALLOC\_CHUNKS Specifies the number of pre-allocated row-store table compression chunks. A larger number of pre-allocated chunks indicates a lower table compression ratio, and a smaller data dispersion degree indicates a better access performance. (Only common tables in the Astore engine are supported.) Value range: 0 to 7. The default value is **0**. * The maximum value of this parameter is **7** when **COMPRESS\_CHUNK\_SIZE** is set to **512** or **1024**. * The maximum value of this parameter is **3** when **COMPRESS\_CHUNK\_SIZE** is set to **2048**. * The maximum value of this parameter is **1** when **COMPRESS\_CHUNK\_SIZE** is set to **4096**. * COMPRESS\_BYTE\_CONVERT Sets the preprocessing of row-store table compression byte conversion. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * COMPRESS\_DIFF\_CONVERT Sets the preprocessing of row-store table compression differentiation. This parameter can be used together only with **COMPRESS\_BYTE\_CONVERT**. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * STORAGE\_TYPE Specifies the storage engine type. This parameter cannot be modified once it is set. Value range: * **USTORE** indicates that tables support the inplace-update storage engine. Note that the **track\_counts** and **track\_activities** parameters must be enabled when the Ustore table is used. Otherwise, space expansion may occur. * **ASTORE** indicates that tables support the append-only storage engine. Default value: If no table is specified, data is stored in append-only mode by default. * COMPRESSION * Valid values for column-store tables are **LOW**, **MIDDLE**, **HIGH**, **YES**, and **NO**, and the compression level increases accordingly. The default is **LOW**. * Row-store tables do not support compression. * MAX\_BATCHROW Specifies the maximum number of rows in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000. The default value is **60000**. * PARTIAL\_CLUSTER\_ROWS Specifies the number of records to be partially clustered for storage during data loading. The parameter is only valid for column-store tables. Value range: greater than or equal to **MAX\_BATCHROW**. You are advised to set this parameter to an integer multiple of **MAX\_BATCHROW**. * DELTAROW\_THRESHOLD A reserved parameter. The parameter is only valid for column-store tables. Value range: 0 to 9999 * segment The data is stored in segment-page mode. This parameter supports only row-store tables. Column-store tables, temporary tables, and unlogged tables are not supported. The Ustore storage engine is not supported. Value range: **on** and **off** Default value: **off** * **COMPRESS / NOCOMPRESS** Specifies keyword **COMPRESS** during the creation of a table, so that the compression feature is triggered in case of bulk **INSERT** operations. If this feature is enabled, a scan is performed for all tuple data within the page to generate a dictionary and then the tuple data is compressed and stored. If **NOCOMPRESS** is specified, the table is not compressed. Row-store tables do not support compression. Default value: **NOCOMPRESS**, that is, tuple data is not compressed before storage. * **TABLESPACE tablespace\_name** Specifies that the new table will be created in the **tablespace\_name** tablespace. If not specified, the default tablespace is used. * **PARTITION BY RANGE(partition\_key)** Creates a range partition. **partition\_key** is the name of the partition key. (1) Assume that the **VALUES LESS THAN** syntax is used. > \[!TIP]NOTICE > > In this case, a maximum of four partition keys are supported. Data types supported by the partition keys are as follows: SMALLINT, INTEGER, BIGINT, DECIMAL, NUMERIC, REAL, DOUBLE PRECISION, CHARACTER VARYING(\*n\_), VARCHAR(\*n\_), CHARACTER(\*n\_), CHAR(\*n\_), CHARACTER, CHAR, TEXT, NVARCHAR, NVARCHAR2, NAME, TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE], and DATE. (2) Assume that the **START END** syntax is used. > \[!TIP]NOTICE > > In this case, only one partition key is supported. Data types supported by the partition key are as follows: **SMALLINT**, **INTEGER**, **BIGINT**, **DECIMAL**, **NUMERIC**, **REAL**, **DOUBLE PRECISION**, **TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]**, **TIMESTAMP\[(p)] \[WITH TIME ZONE]**, and **DATE**. (3) Assume that the **INTERVAL** syntax is used. > \[!TIP]NOTICE > > In this case, only one partition key is supported. In this case, the data types supported by the partition key are TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE] and DATE. * **PARTITION partition\_name VALUES LESS THAN ( { partition\_value | MAXVALUE } )** Specifies the information of partitions. **partition\_name** is the name of a range partition. **partition\_value** is the upper limit of a range partition, and the value depends on the type of **partition\_key**. *MAXVALUE* usually specifies the upper limit of the last range partition. > \[!TIP]NOTICE > > * Each partition requires an upper limit. > * The data type of the upper limit must be the same as that of the partition key. > * In a partition list, partitions are arranged in ascending order of upper limits. A partition with a smaller upper limit value is placed before another partition with a larger one. * **PARTITION partition\_name {START (partition\_value) END (partition\_value) EVERY (interval\_value)} |**{START (partition\_value) END (partition\_value|MAXVALUE)} | {START(partition\_value)} | **{END (partition\_value | MAXVALUE)**} Specifies the information of partitions. * **partition\_name**: name or name prefix of a range partition. It is the name prefix only in the following cases (assuming that **partition\_name** is **p1**): * If **START**+**END**+**EVERY** is used, the names of partitions will be defined as **p1\_1**, **p1\_2**, and the like. For example, if **PARTITION p1 START(1) END(4) EVERY(1)** is defined, the generated partitions are \[1, 2), \[2, 3), and \[3, 4), and their names are **p1\_1**, **p1\_2**, and **p1\_3**. In this case, **p1** is a name prefix. * If the defined statement is in the first place and has **START** specified, the range (*MINVALUE*, **START**) will be automatically used as the first actual partition, and its name will be **p1\_0**. The other partitions are then named **p1\_1**, **p1\_2**, and the like. For example, if **PARTITION p1 START(1), PARTITION p2 START(2)** is defined, generated partitions are (*MINVALUE*, 1), \[1, 2), and \[2, *MAXVALUE*), and their names will be **p1\_0**, **p1\_1**, and **p2**. In this case, **p1** is a name prefix and **p2** is a partition name. **MINVALUE** means the minimum value. * **partition\_value**: start value or end value of a range partition. The value depends on **partition\_key** and cannot be *MAXVALUE*. * **interval\_value**: width of each partition for dividing the \[**START**, **END**) range. It cannot be *MAXVALUE*. If the value of (**END** – **START**) divided by **EVERY** has a remainder, the width of only the last partition is less than the value of **EVERY**. * *MAXVALUE* usually specifies the upper limit of the last range partition. > \[!TIP]NOTICE > > 1. If the defined statement is in the first place and has **START** specified, the range (*MINVALUE*, **START**) will be automatically used as the first actual partition. > 2. The **START END** syntax must comply with the following rules: > * The value of **START** (if any, same for the following situations) in each **partition\_start\_end\_item** must be smaller than that of **END**. > * In two adjacent **partition\_start\_end\_item** statements, the value of the first **END** must be equal to that of the second **START**. > * The value of **EVERY** in each **partition\_start\_end\_item** must be a positive number (in ascending order) and must be smaller than **END** minus **START**. > * Each partition includes the start value (unless it is *MINVALUE*) and excludes the end value. The format is as follows: \[**START**, **END**). > * Partitions created by the same **partition\_start\_end\_item** belong to the same tablespace. > * If **partition\_name** is a name prefix of a partition, the length must not exceed 57 bytes. If there are more than 57 bytes, the prefix will be automatically truncated. > * When creating or modifying a partitioned table, ensure that the total number of partitions in the table does not exceed the maximum value **1048575**. > 3. In statements for creating partitioned tables, **START END** and **LESS THAN** cannot be used together. > 4. The **START END** syntax in a partitioned table creation SQL statement will be replaced by the **VALUES LESS THAN** syntax when **gs\_dump** is executed. * **INTERVAL ('interval\_expr') \[ STORE IN (tablespace\_name \[, ... ] ) ]** Defines interval partitioning. * **interval\_expr**: interval for automatically creating partitions, for example, 1 day or 1 month. * **STORE IN (tablespace\_name \[, ... ] )**: Specifies the list of tablespaces for storing automatically created partitions. If this parameter is specified, the automatically created partitions are cyclically selected from the tablespace list. Otherwise, the default tablespace of the partition table is used. > \[!TIP]NOTICE > > Column-store tables do not support interval partitioning. * **PARTITION BY LIST(partition\_key)** Create a list partition. **partition\_key** is the name of the partition key. * For **partition\_key**, the list partitioning policy supports only one column of partition keys. * If the clause is **VALUES (list\_values\_clause)**, **list\_values\_clause** contains the key values of the corresponding partition. It is recommended that the number of key values of each partition be less than or equal to 64. Partition keys support the following data types: INT1, INT2, INT4, INT8, NUMERIC, VARCHAR(\*n\_), CHAR, BPCHAR, NVARCHAR, NVARCHAR2, TIMESTAMP\[(\*p\_)] \[WITHOUT TIME ZONE], TIMESTAMP\[(*p*)] \[WITH TIME ZONE], and DATE. The number of partitions cannot exceed 1048575. * **PARTITION BY HASH(partition\_key)** Create a hash partition. **partition\_key** is the name of the partition key. For **partition\_key**, the hash partitioning policy supports only one column of partition keys. Partition keys support the following data types: INT1, INT2, INT4, INT8, NUMERIC, VARCHAR(\*n\_), CHAR, BPCHAR, TEXT, NVARCHAR, NVARCHAR2, TIMESTAMP\[(\*p\_)] \[WITHOUT TIME ZONE], TIMESTAMP\[(*p*)] \[WITH TIME ZONE], and DATE. The number of partitions cannot exceed 1048575. * **{ ENABLE | DISABLE } ROW MOVEMENT** Sets row movement. If the tuple value is updated on the partition key during the **UPDATE** action, the partition where the tuple is located is altered. Setting this parameter enables error messages to be reported or movement of the tuple between partitions. Value range: * **ENABLE** (default value): Row movement is enabled. * **DISABLE**: Row movement is disabled. > \[!TIP]NOTICE > > Currently, list and hash partitioned tables do not support **ROW MOVEMENT**. * **NOT NULL** The column is not allowed to contain null values. **ENABLE** can be omitted. * **NULL** Specifies that the column is allowed to contain null values. This is the default setting. This clause is only provided for compatibility with non-standard SQL databases. It is not recommended. * **CHECK (condition) \[ NO INHERIT ]** Specifies an expression producing a Boolean result where the insert or update operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A check constraint specified as a column constraint should reference only the column's values, while an expression appearing in a table constraint can reference multiple columns. A constraint marked with **NO INHERIT** will not propagate to child tables. **ENABLE** can be omitted. * **DEFAULT default\_expr** Assigns a default data value for a column. The value can be any variable-free expressions. (Subqueries and cross-references to other columns in the current table are not allowed.) The data type of the default expression must match the data type of the column. The default expression will be used in any insert operation that does not specify a value for the column. If there is no default value for a column, then the default value is null. * GENERATED ALWAYS AS ( generation\_expr ) STORED This clause creates a column as a generated column. The value of the generated column is calculated by **generation\_expr** when data is written (inserted or updated). **STORED** indicates that the value of the generated column is stored as a common column. > \[!NOTE]NOTE > > * The generation expression cannot refer to data other than the current row in any way. The generation expression cannot reference other generation columns or system columns. The generation expression cannot return a result set. No subquery, aggregate function, or window function can be used. The function called by the generation expression can only be an immutable function. > * Default values cannot be specified for generated columns. > * The generated column cannot be used as a part of the partition key. > * Do not specify the generated column and the CASCADE, SET NULL, and SET DEFAULT actions of the ON UPDATE constraint at the same time. Do not specify the generated column and the SET NULL, and SET DEFAULT actions of the ON DELETE constraint at the same time. > * The method of modifying and deleting generated columns is the same as that of common columns. Delete the common column that the generated column depends on. The generated column is automatically deleted. The type of the column on which the generated column depends cannot be changed. > * The generated column cannot be directly written. In the INSERT or UPDATE statement, values cannot be specified for generated columns, but the keyword DEFAULT can be specified. > * The permission control for generated columns is the same as that for common columns. > * Columns cannot be generated for column-store tables and MOTs. In foreign tables, only **postgres\_fdw** supports generated columns. * **AUTO\_INCREMENT** Specifies an auto-increment column. For details, see [AUTO\_INCREMENT](create_table.md). * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** Specifies that a group of one or more columns of a table can contain only unique values. For the purpose of a unique constraint, null is not considered equal. * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** Specifies that a column or columns of a table can contain only unique (non-duplicate) and non-null values. Only one primary key can be specified for a table. * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(default): Enable constraints, create indexes, and enforce constraints on both existing data and newly added data. * ENABLE NOVALIDATE: Enable constraints and create indexes. For CHECK constraints, the constraints are only enforced for newly added data, regardless of the existing data in the table. For UNIQUE and PRIMARY KEY, indexes need to be established, so the constraints will be enforced for the existing data. * DISABLE( NOVALIDATE)(default): Disable constraints, delete indexes, and operations such as modifying the data of the constraint columns can be performed. * DISABLE VALIDATE: Disable constraints and delete indexes. Insertion, update and deletion operations on the table cannot be performed. * **DEFERRABLE | NOT DEFERRABLE** Controls whether the constraint can be deferred. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable can be postponed until the end of the transaction using the **SET CONSTRAINTS** command. **NOT DEFERRABLE** is the default value. Currently, only UNIQUE constraints, primary key constraints, and foreign key constraints accept this clause. All the other constraints are not deferrable. * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** If a constraint is deferrable, this clause specifies the default time to check the constraint. * If the constraint is **INITIALLY IMMEDIATE** (default value), it is checked after each statement. * If the constraint is **INITIALLY DEFERRED**, it is checked only at the end of the transaction. The constraint check time can be altered using the **SET CONSTRAINTS** statement. * **USING INDEX TABLESPACE tablespace\_name** Allows selection of the tablespace in which the index associated with a **UNIQUE** or **PRIMARY KEY** constraint will be created. If not specified, **default\_tablespace** is consulted, or the default tablespace in the database if **default\_tablespace** is empty. ## Examples * Example 1: Create a range-partitioned table **tpcds.web\_returns\_p1**. The table has eight partitions and their partition keys are of the integer type. The ranges of the partitions are: wr\_returned\_date\_sk < 2450815, 2450815 ≤ wr\_returned\_date\_sk < 2451179, 2451179 ≤ wr\_returned\_date\_sk < 2451544, 2451544 ≤ wr\_returned\_date\_sk < 2451910, 2451910 ≤ wr\_returned\_date\_sk < 2452275, 2452275 ≤ wr\_returned\_date\_sk < 2452640, 2452640 ≤ wr\_returned\_date\_sk < 2453005, and wr\_returned\_date\_sk ≥ 2453005. ``` -- Create the tpcds.web_returns table. openGauss=# CREATE TABLE tpcds.web_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a range-partitioned table tpcds.web_returns_p1. openGauss=# CREATE TABLE tpcds.web_returns_p1 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) ); -- Import data from the example data table. openGauss=# INSERT INTO tpcds.web_returns_p1 SELECT * FROM tpcds.web_returns; -- Delete the P8 partition. openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION P8; -- Add a partition WR_RETURNED_DATE_SK with values ranging from 2453005 to 2453105. openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P8 VALUES LESS THAN (2453105); -- Add a partition WR_RETURNED_DATE_SK with values ranging from 2453105 to MAXVALUE. openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P9 VALUES LESS THAN (MAXVALUE); -- Delete the P8 partition. openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION FOR (2453005); -- Rename the P7 partition to P10. openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION P7 TO P10; -- Rename the P6 partition to P11. openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION FOR (2452639) TO P11; -- Query the number of rows in the P10 partition. openGauss=# SELECT count(*) FROM tpcds.web_returns_p1 PARTITION (P10); count -------- 0 (1 row) -- Query the number of rows in the P1 partition. openGauss=# SELECT COUNT(*) FROM tpcds.web_returns_p1 PARTITION FOR (2450815); count -------- 0 (1 row) ``` * Example 2: Create a range-partitioned table **tpcds.web\_returns\_p2**. The table has eight partitions and their partition keys are of the integer type. The upper limit of the eighth partition is *MAXVALUE*. The ranges of the partitions are: wr\_returned\_date\_sk < 2450815, 2450815 ≤ wr\_returned\_date\_sk < 2451179, 2451179 ≤ wr\_returned\_date\_sk < 2451544, 2451544 ≤ wr\_returned\_date\_sk < 2451910, 2451910 ≤ wr\_returned\_date\_sk < 2452275, 2452275 ≤ wr\_returned\_date\_sk < 2452640, 2452640 ≤ wr\_returned\_date\_sk < 2453005, and wr\_returned\_date\_sk ≥ 2453005. The tablespace of the **tpcds.web\_returns\_p2** partitioned table is **example1**. Partitions **P1** to **P7** have no specified tablespaces, and use the **example1** tablespace of the **tpcds.web\_returns\_p2** partitioned table. The tablespace of the **P8** partitioned table is **example2**. Assume that the following data directories of the database nodes are empty directories for which user **dwsadmin** has the read and write permissions: **/pg\_location/mount1/path1**, **/pg\_location/mount2/path2**, **/pg\_location/mount3/path3**, and **/pg\_location/mount4/path4**. ``` openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; openGauss=# CREATE TABLE tpcds.web_returns_p2 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) TABLESPACE example1 PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; -- Create a partitioned table using LIKE. openGauss=# CREATE TABLE tpcds.web_returns_p3 (LIKE tpcds.web_returns_p2 INCLUDING PARTITION); -- Change the tablespace of the P1 partition to example2. openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P1 TABLESPACE example2; -- Change the tablespace of the P2 partition to example3. openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P2 TABLESPACE example3; -- Split the P8 partition at 2453010. openGauss=# ALTER TABLE tpcds.web_returns_p2 SPLIT PARTITION P8 AT (2453010) INTO ( PARTITION P9, PARTITION P10 ); -- Merge the P6 and P7 partitions into one. openGauss=# ALTER TABLE tpcds.web_returns_p2 MERGE PARTITIONS P6, P7 INTO PARTITION P8; -- Modify the migration attribute of the partitioned table. openGauss=# ALTER TABLE tpcds.web_returns_p2 DISABLE ROW MOVEMENT; -- Delete tables and tablespaces. openGauss=# DROP TABLE tpcds.web_returns_p1; openGauss=# DROP TABLE tpcds.web_returns_p2; openGauss=# DROP TABLE tpcds.web_returns_p3; openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; ``` * Example 3: Use **START END** to create and modify a range-partitioned table. Assume that **/home/omm/startend\_tbs1**, **/home/omm/startend\_tbs2**, **/home/omm/startend\_tbs3**, and **/home/omm/startend\_tbs4** are empty directories for which user omm has the read and write permissions. ``` -- Create tablespaces. openGauss=# CREATE TABLESPACE startend_tbs1 LOCATION '/home/omm/startend_tbs1'; openGauss=# CREATE TABLESPACE startend_tbs2 LOCATION '/home/omm/startend_tbs2'; openGauss=# CREATE TABLESPACE startend_tbs3 LOCATION '/home/omm/startend_tbs3'; openGauss=# CREATE TABLESPACE startend_tbs4 LOCATION '/home/omm/startend_tbs4'; -- Create a temporary schema. openGauss=# CREATE SCHEMA tpcds; openGauss=# SET CURRENT_SCHEMA TO tpcds; -- Create a partitioned table with the partition key of the integer type. openGauss=# CREATE TABLE tpcds.startend_pt (c1 INT, c2 INT) TABLESPACE startend_tbs1 PARTITION BY RANGE (c2) ( PARTITION p1 START(1) END(1000) EVERY(200) TABLESPACE startend_tbs2, PARTITION p2 END(2000), PARTITION p3 START(2000) END(2500) TABLESPACE startend_tbs3, PARTITION p4 START(2500), PARTITION p5 START(3000) END(5000) EVERY(1000) TABLESPACE startend_tbs4 ) ENABLE ROW MOVEMENT; -- View the information of the partitioned table. openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs1 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p5_2 | {5000} | startend_tbs4 startend_pt | | startend_tbs1 (12 rows) -- Import data and check the data volume in a partition. openGauss=# INSERT INTO tpcds.startend_pt VALUES (GENERATE_SERIES(0, 4999), GENERATE_SERIES(0, 4999)); openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION FOR (0); count ------- 1 (1 row) openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION (p3); count ------- 500 (1 row) -- Add partitions [5000, 5300), [5300, 5600), [5600, 5900), and [5900, 6000). openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p6 START(5000) END(6000) EVERY(300) TABLESPACE startend_tbs4; -- Add the partition p7, specified by MAXVALUE. openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p7 END(MAXVALUE); -- Rename the partition p7 to p8. openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION p7 TO p8; -- Delete the partition p8. openGauss=# ALTER TABLE tpcds.startend_pt DROP PARTITION p8; -- Rename the partition where 5950 is located to p71. openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION FOR(5950) TO p71; -- Split the partition [4000, 5000) where 4500 is located. openGauss=# ALTER TABLE tpcds.startend_pt SPLIT PARTITION FOR(4500) INTO(PARTITION q1 START(4000) END(5000) EVERY(250) TABLESPACE startend_tbs3); -- Change the tablespace of the partition p2 to startend_tbs4. openGauss=# ALTER TABLE tpcds.startend_pt MOVE PARTITION p2 TABLESPACE startend_tbs4; -- View the partition status. openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs4 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p6_1 | {5300} | startend_tbs4 p6_2 | {5600} | startend_tbs4 p6_3 | {5900} | startend_tbs4 p71 | {6000} | startend_tbs4 q1_1 | {4250} | startend_tbs3 q1_2 | {4500} | startend_tbs3 q1_3 | {4750} | startend_tbs3 q1_4 | {5000} | startend_tbs3 startend_pt | | startend_tbs1 (19 rows) -- Delete tables and tablespaces. openGauss=# DROP SCHEMA tpcds CASCADE; openGauss=# DROP TABLESPACE startend_tbs1; openGauss=# DROP TABLESPACE startend_tbs2; openGauss=# DROP TABLESPACE startend_tbs3; openGauss=# DROP TABLESPACE startend_tbs4; ``` * Example 4: Create interval partitioned table **sales**. The table initially contains two partitions and the partition key is of the DATE type. Ranges of the two partitions are as follows: **time\_id** < '2019-02-01 00:00:00' and '2019-02-01 00:00:00' ≤ **time\_id** < '2019-02-02 00:00:00', respectively. ``` -- Create table sales. openGauss=# CREATE TABLE sales (prod_id NUMBER(6), cust_id NUMBER, time_id DATE, channel_id CHAR(1), promo_id NUMBER(6), quantity_sold NUMBER(3), amount_sold NUMBER(10,2) ) PARTITION BY RANGE (time_id) INTERVAL('1 day') ( PARTITION p1 VALUES LESS THAN ('2019-02-01 00:00:00'), PARTITION p2 VALUES LESS THAN ('2019-02-02 00:00:00') ); -- Insert data into partition p1. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-01-10 00:00:00', 'a', 1, 1, 1); -- Insert data into partition p2. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-01 00:00:00', 'a', 1, 1, 1); -- View the partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (2 rows) -- If the data to be inserted does not match any partition, create a partition and insert the data into the new partition. -- The range of the new partition is '2019-02-05 00:00:00' ≤ time_id < '2019-02-06 00:00:00'. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-05 00:00:00', 'a', 1, 1, 1); -- If the data to be inserted does not match any partition, create a partition and insert the data into the new partition. -- The range of the new partition is '2019-02-03 00:00:00' ≤ time_id < '2019-02-04 00:00:00'. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-03 00:00:00', 'a', 1, 1, 1); -- View the partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- sys_p1 | i | {"2019-02-06 00:00:00"} sys_p2 | i | {"2019-02-04 00:00:00"} p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (4 rows) ``` * Example 5: Create list partitioned table **test\_list**. The table initially contains four partitions and the partition key is of the INT type. The ranges of the four partitions are 2000, 3000, 4000, and 5000 respectively. ``` -- Create the test_list table. openGauss=# create table test_list (col1 int, col2 int) partition by list(col1) ( partition p1 values (2000), partition p2 values (3000), partition p3 values (4000), partition p4 values (5000) ); -- Insert data. openGauss=# INSERT INTO test_list VALUES(2000, 2000); INSERT 0 1 openGauss=# INSERT INTO test_list VALUES(3000, 3000); INSERT 0 1 -- View the partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} p4 | l | {5000} (4 rows) -- The inserted data does not match the partition, and an error is reported. openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- Add a partition. openGauss=# alter table test_list add partition p5 values (6000); ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p5 | l | {6000} p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (5 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); INSERT 0 1 -- Exchange data between the partitioned table and ordinary table. openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ 2000 | 2000 (1 row) openGauss=# alter table test_list exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 2000 | 2000 (1 row) -- Truncate the partition. openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ 3000 | 3000 (1 row) openGauss=# alter table test_list truncate partition p2; ALTER TABLE openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ (0 rows) -- Delete the partition. openGauss=# alter table test_list drop partition p5; ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (4 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- Delete the partitioned table. openGauss=# drop table test_list; ``` * Example 6: Create a hash partitioned table **test\_hash**. The table initially contains two partitions and the partition key is of the INT type. ``` -- Create the test_hash table. openGauss=# create table test_hash (col1 int, col2 int) partition by hash(col1) ( partition p1, partition p2 ); -- Insert data. openGauss=# INSERT INTO test_hash VALUES(1, 1); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(2, 2); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(3, 3); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(4, 4); INSERT 0 1 -- View the partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_hash' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | h | {0} p2 | h | {1} (2 rows) -- View the data. openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ 1 | 1 2 | 2 (2 rows) -- Exchange data between the partitioned table and ordinary table. openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# alter table test_hash exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) -- Truncate the partition. openGauss=# alter table test_hash truncate partition p2; ALTER TABLE openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ (0 rows) -- Delete the partitioned table. openGauss=# drop table test_hash; ``` ## Helpful Links [ALTER TABLE PARTITION](alter_table_partition.md) and [DROP TABLE](drop_table.md) --- --- url: >- /en/docs/latest/extension_reference/extension_reference/plugin/dolphin-create-table-partition.md --- # CREATE TABLE PARTITION ## Function Creates a partitioned table. Partitioning refers to splitting what is logically one large table into smaller physical pieces based on specific schemes. The table based on the logic is called a partitioned table, and each physical piece is called a partition. Data is stored on these physical partitions, instead of the logical partitioned table. The common forms of partitioning include range partitioning, interval partitioning, hash partitioning, list partitioning, and value partitioning. Currently, row-store tables support range partitioning, interval partitioning, hash partitioning, and list partitioning. Column-store tables support only range partitioning. In range partitioning, the table is partitioned into ranges defined by a key column or set of columns, with no overlap between the ranges of values assigned to different partitions. Each range has a dedicated partition for data storage. The partitioning policy for Range Partitioning refers to how data is inserted into partitions. Currently, range partitioning only allows the use of the range partitioning policy. In range partitioning, a 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. Interval partitioning is a special type of range partitioning. Compared with range partitioning, interval value definition is added. When no matching partition can be found for an inserted record, a partition can be automatically created based on the interval value. Interval partitioning supports only table-based partitioning of a list where the data type can be TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE], and DATE. Interval partitioning policy: A record is mapped to a created partition based on the partition key value. If the record can be mapped to a created partition, the record is inserted into the corresponding partition. Otherwise, a partition is automatically created based on the partition key value and table definition information, and then the record is inserted into the new partition. The data range of the new partition is equal to the interval value. In hash partitioning, a modulus and a remainder are specified for each partition based on a column in the table, and records to be inserted into the table are allocated to the corresponding partition, the rows in each partition must meet the following condition: The value of the partition key divided by the specified modulus generates the remainder specified for the partition key. In hash 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. List partitioning is to allocate the records to be inserted into a table to the corresponding partition based on the key values in each partition. The key values do not overlap in different partitions. Create a partition for each group of key values to store corresponding data. In list 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. Partitioning can provide several benefits: * Query performance can be improved drastically in certain situations, particularly when most of the heavily accessed rows of the table are in a single partition or a small number of partitions. Partitioning narrows the range of data search and improves data access efficiency. * When queries or updates access a large percentage of a single partition, performance can be dramatically improved by taking advantage of sequential scan of that partition instead of reads scattered across the whole table. * Frequent loading or deletion operations on records in a separate partition can be accomplished by reading or removing that partition. It also entirely avoids the **VACUUM** overload caused by bulk **DELETE** operations (only for range partitioning). Compared with the kernel syntax, the rebuild, remove, check, repair, optimize, truncate, analyze, exchange of Dolphin is modified in B compatibility mode. ## Precautions * If the constraint key of the unique constraint and primary key constraint contains all partition keys, a local index is created for the constraints. Otherwise, a global index is created. * Currently, hash partitioning and list partitioning support only single-column partitioning, and do not support multi-column partitioning. * When you have the **INSERT** permission for an interval partitioned table, partitions can be automatically created when you run **INSERT** to write data to the table. * In the **PARTITION FOR (values)** syntax for partitioned tables, values can only be constants. * In the **PARTITION FOR (values)** syntax for partitioned tables, if data type conversion is required for values, you are advised to use forcible type conversion to prevent the implicit type conversion result from being inconsistent with the expected result. * The maximum number of partitions is 1048575. Generally, it is impossible to create so many partitions, because too many partitions may cause insufficient memory. Create partitions based on the value of **local\_syscache\_threshold**. The memory used by the partitioned tables is about (number of partitions x 3/1024) MB. Theoretically, the memory occupied by the partitions cannot be greater than the value of **local\_syscache\_threshold**. In addition, some space must be reserved for other functions. * table\_indexclause is used to create a partitioned table index. The index is a local index and cannot be a global index. ## Syntax ``` CREATE TABLE [ IF NOT EXISTS ] partition_table_name ( [ { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | table_indexclause | LIKE source_table [ like_option [...] ] }[, ... ] ] ) [create_option] PARTITION BY { {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_less_than_item [, ... ] )} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_start_end_item [, ... ] )} | {LIST (partition_key) [ PARTITIONS opt_partitions_num ] (PARTITION partition_name [VALUES [IN] (list_values_clause) ] opt_table_space )} | {HASH (partition_key) [ PARTITIONS opt_partitions_num ] [ (PARTITION partition_name opt_table_space) ]} | {KEY (opt_partition_key) [ PARTITIONS opt_partitions_num ] [ (PARTITION partition_name opt_table_space) ]} } [ { ENABLE | DISABLE } ROW MOVEMENT ]; [create_option] Where create\_option is: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMPRESSION [=] compression_arg ] [ ENGINE [=] engine_name ] In addition to the WITH option, you can enter the same create\_option for multiple times. The latest input prevails. ``` * column\_constraint: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_e xpr | GENERATED ALWAYS AS ( generation_expr ) STORED | UNIQUE index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * table\_constraint: ``` [ CONSTRAINT constraint_name ] { CHECK ( expression ) | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters | FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * table\_indexclause: ``` {INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option]... ``` * Values of index\_type are as follows: ``` USING {BTREE | HASH | GIN | GIST | PSORT | UBTREE} ``` * Values of key\_part are as follows: ``` {col_name [ ( length ) ] | (expr)} [ASC | DESC] ``` * `col_name ( length )` is the prefix key, `column\_name` is the column name of the prefix key, and `length` is the prefix length. The prefix key uses the prefix of the specified column data as the index key value, which reduces the storage space occupied by the index. Indexes can be used for filter and join conditions that contain prefix key columns. > \[!NOTE]NOTE > > * The prefix key supports the following index methods: btree and ubtree. > * The data type of the prefix key column must be binary or character (excluding special characters). > * The prefix length must be a positive integer that does not exceed 2676 and cannot exceed the maximum length of the column. For the binary type, the prefix length is measured in bytes. For non-binary character types, the prefix length is measured in characters. The actual length of the key value is restricted by the internal page. If a column contains multi-byte characters or an index has multiple keys, the length of the index line may exceed the upper limit. As a result, an error is reported. Consider this situation when setting a long prefix length. * The index\_option parameter is as follows: ``` index_option:{ COMMENT 'string' | index_type } ``` The sequence and quantity of COMMENT and index\_type can be random, but only the last value of the same column takes effect. * like\_option: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS| ALL } ``` * index\_parameters: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * partition\_less\_than\_item: ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } ) [TABLESPACE tablespace_name] ``` * partition\_start\_end\_item: ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` ## Parameter Description * **IF NOT EXISTS** Does not throw an error if a relationship with the same name existed. A notice is issued in this case. * **partition\_table\_name** Specifies the name of the partitioned table. Value range: String, which must comply with the naming convention. * **column\_name** Specifies the name of a column to be created in the new table. Value range: String, which must comply with the naming convention. * **data\_type** Specifies the data type of the column. * **COLLATE collation** Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the **select \* from pg\_collation** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **CONSTRAINT constraint\_name** Specifies the name of a column or table constraint. The optional constraint clauses specify constraints that new or updated rows must satisfy for an INSERT or UPDATE operation to succeed. There are two ways to define constraints: * A column constraint is defined as part of a column definition, and it is bound to a particular column. * A table constraint is not bound to a particular column and can apply to more than one column. * **LIKE source\_table \[ like\_option ... ]** The LIKE clause specifies a table from which the new table automatically copies all column names, their data types, and their non-null constraints. Unlike INHERITS, the new table and original table are decoupled after creation is complete. Changes to the source table will not be applied to the new table, and it is not possible to include data of the new table in scans of the source table. * Default expressions for the copied column definitions will only be copied if **INCLUDING DEFAULTS** is specified. The default behavior is to exclude default expressions, resulting in the copied columns in the new table having default values **NULL**. * If **INCLUDING GENERATED** is specified, the generated expression of the source table column is copied to the new table. By default, the generated expression is not copied. * Non-null constraints are always copied to the new table. CHECK constraints will only be copied if **INCLUDING CONSTRAINTS** is specified; other types of constraints will never be copied. These rules also apply to column constraints and table constraints. * Unlike those of INHERITS, columns and constraints copied by LIKE are not merged with similarly named columns and constraints. If the same name is specified explicitly or in another LIKE clause, an error is reported. * Any indexes on the original table will not be created on the new table, unless the **INCLUDING INDEXES** clause is specified. * **STORAGE** settings for the copied column definitions are copied only if **INCLUDING STORAGE** is specified. The default behavior is to exclude **STORAGE** settings. * Comments for the copied columns, constraints, and indexes will be copied only if **INCLUDING COMMENTS** is specified. The default behavior is to exclude comments. * If **INCLUDING RELOPTIONS** is specified, the new table will copy the storage parameter (WITH clause of the source table) of the source table. The default behavior is to exclude partition definition of the storage parameter of the original table. * **INCLUDING ALL** contains the meaning of **INCLUDING DEFAULTS**, **INCLUDING CONSTRAINTS**, **INCLUDING INDEXES**, **INCLUDING STORAGE**, **INCLUDING COMMENTS**, **INCLUDING PARTITION**, and **INCLUDING RELOPTIONS**. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. Optional parameters are as follows: * FILLFACTOR The fill factor of a table is a percentage from 10 to 100. **100** (complete filling) is the default value. When a smaller fill factor is specified, INSERT operations fill table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives UPDATE a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter has no meaning for column-store tables. Value range: 10 to 100 * ORIENTATION Determines the data storage mode of the table. Value range: * **COLUMN**: The data will be stored in columns. * **ROW** (default value): The data will be stored in rows. > \[!TIP]NOTICE > **ORIENTATION** cannot be modified. * STORAGE\_TYPE Specifies the storage engine type. This parameter cannot be modified once it is set. Value range: * **USTORE** indicates that tables support the inplace-update storage engine. Note that the **track\_counts** and **track\_activities** parameters must be enabled when the Ustore table is used. Otherwise, space expansion may occur. * **ASTORE** indicates that tables support the append-only storage engine. * Default value. If no table is specified, data is stored in append-only mode by default. * COMPRESSION * Value range: **LOW**, **MIDDLE**, **HIGH**, **YES**, and **NO** for column-store tables, with compression level increasing in ascending order. The default value is **LOW**. * Row-store tables cannot be compressed. * MAX\_BATCHROW Specifies the maximum number of records in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000. The default value is **60000**. * PARTIAL\_CLUSTER\_ROWS Specifies the number of records to be partially clustered for storage during data loading. The parameter is only valid for column-store table. Value range: greater than or equal to **MAX\_BATCHROW**. You are advised to set this parameter to an integer multiple of **MAX\_BATCHROW**. * DELTAROW\_THRESHOLD A reserved parameter. The parameter is only valid for column-store table. Value range: 0 to 9999 * segment The data is stored in segment-page mode. This parameter supports only row-store tables. Column-store tables, temporary tables, and unlogged tables are not supported. The Ustore storage engine is not supported. Value range: **on** and **off** Default value: **off** * **COMPRESS / NOCOMPRESS** Specifies keyword COMPRESS during the creation of a table, so that the compression feature is triggered in case of BULK INSERT operations. If this feature is enabled, a scan is performed for all tuple data within the page to generate a dictionary and then the tuple data is compressed and stored. If **NOCOMPRESS** is specified, the table is not compressed. Row-store tables cannot be compressed. Default value: **NOCOMPRESS**, tuple data is not compressed before storage. * **TABLESPACE tablespace\_name** Specifies that the new table will be created in the **tablespace\_name** tablespace. If the tablespace is not specified, the default tablespace is used. * **PARTITION BY RANGE(partition\_key)** Creates a range partition. **partition\_key** is the name of the partition key. (1) Assume that the **VALUES LESS THAN** syntax is used. > \[!TIP]NOTICE > In this case, a maximum of four partition keys are supported. Data types supported by the partition keys are as follows: TINYINT\[UNSIGNED], SMALLINT\[UNSIGNED], INTEGER\[UNSIGNED], BIGINT\[UNSIGNED], DECIMAL, NUMERIC, REAL, DOUBLE PRECISION, CHARACTER VARYING(n), VARCHAR(n), CHARACTER(n), CHAR(n), CHARACTER, CHAR, TEXT, NVARCHAR, NVARCHAR2, NAME, TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE], and DATE. (2) Assume that the **START END** syntax is used. > \[!TIP]NOTICE > In this case, only one partition key is supported. Data types supported by the partition keys are as follows: TINYINT\[UNSIGNED], SMALLINT\[UNSIGNED], INTEGER\[UNSIGNED], BIGINT\[UNSIGNED], DECIMAL, NUMERIC, REAL, DOUBLE PRECISION, TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE], and DATE. (3) Assume that the **INTERVAL** syntax is used. > \[!TIP]NOTICE > In this case, only one partition key is supported. In this case, the data types supported by the partition key are TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE], and DATE. * **PARTITION partition\_name VALUES LESS THAN ( { partition\_value | MAXVALUE } )** Indicates specifying the partition information, where **partition\_name** indicates the name of a range partition, **partition\_value** indicates the upper boundary of a range partition and its value is determined by the type of **partition\_key**. **MAXVALUE** specifies the upper boundary of the last range partition. > \[!TIP]NOTICE > > * Upper boundaries must be specified 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. * **PARTITION partition\_name {START (partition\_value) END (partition\_value) EVERY (interval\_value)}** | **{START (partition\_value) END (partition\_value|MAXVALUE)**} | {START(partition\_value)\*\*} | **{END (partition\_value | MAXVALUE)**} Specifies the information of partitions. * **partition\_name**: name or name prefix of a range partition. It is the name prefix only in the following cases (assuming that **partition\_name** is **p1**): * If START+END+EVERY is used, the names of partitions will be defined as **p1\_1**, **p1\_2**, and the like. For example, if "PARTITION p1 START(1) END(4) EVERY(1)" is defined, the generated partitions are \[1, 2), \[2, 3), and \[3, 4), and their names are p1\_1, p1\_2, and p1\_3 respectively. That is, p1 is the name prefix. * If the defined statement is in the first place and has **START** specified, the range (*MINVALUE*, **START**) will be automatically used as the first actual partition, and its name will be **p1\_0**. The other partitions are then named **p1\_1**, **p1\_2**, and so on. For example, if the complete definition is "PARTITION p1 START(1), PARTITION p2 START(2)", the generated partitions are (MINVALUE, 1), \[1, 2) and \[2, MAXVALUE), and their names are p1\_0, p1\_1, and p2. That is, p1 is the name prefix and p2 is the partition name. **MINVALUE** indicates the minimum value. * partition\_value: start point value or end point value of a range partition. The value depends on partition\_key and cannot be MAXVALUE. * **interval\_value**: width of each partition for dividing the \[**START**, **END**) range. It cannot be **MAXVALUE**. If the value of (**END** – **START**) divided by **EVERY** has a remainder, the width of only the last partition is less than the value of **EVERY**. * **MAXVALUE**: maximum value. It is usually used to set the upper boundary for the last range partition. > \[!TIP]NOTICE > > 1. If the defined statement is in the first place and has **START** specified, the range (**MINVALUE**, **START**) will be automatically used as the first actual partition. > 2. The **START END** syntax must comply with the following rules: > * The value of START (if any, same for the following situations) in each partition\_start\_end\_item must be smaller than that of END. > * For two adjacent partition\_start\_end\_item, the END value of the first partition\_start\_end\_item must be equal to the START value of the second partition\_start\_end\_item. > * The value of EVERY in each partition\_start\_end\_item must be in ascending order and must be smaller than the value of END – START. > * Each partition includes the start value (unless it is **MINVALUE**) and excludes the end value. The format is as follows: \[Start value, end value). > * Partitions created by a partition\_start\_end\_item belong to the same tablespace. > * If **partition\_name** is a name prefix of a partition, the length must not exceed 57 bytes. If there are more than 57 bytes, the prefix will be automatically truncated. > * When creating or modifying a partitioned table, ensure that the total number of partitions in the table does not exceed the maximum value **1048575**. > 3. In statements for creating partitioned tables, **START END** and **LESS THAN** cannot be used together. > 4. The **START END** syntax in a partitioned table creation SQL statement will be replaced with the **VALUES LESS THAN** syntax when **gs\_dump** is executed. * **INTERVAL ('interval\_expr') \[ STORE IN (tablespace\_name \[, ... ] ) ]** Defines interval partitioning. * **interval\_expr**: interval for automatically creating partitions, for example, 1 day or 1 month. * STORE IN (tablespace\_name \[, ... ] ): Specifies the list of tablespaces for storing automatically created partitions. If this parameter is specified, the automatically created partitions are cyclically selected from the tablespace list. Otherwise, the default tablespace of the partitioned table is used. > \[!TIP]NOTICE > Column-store tables do not support interval partitioning. * **PARTITION BY LIST(partition\_key)** Create a list partition. partition\_key indicates the name of the partition key. * For **partition\_key**, the list partitioning policy supports only one column of partition keys. * If the clause is VALUES (list\_values\_clause), list\_values\_clause contains the key values of the corresponding partition. It is recommended that the number of key values of each partition be less than or equal to 64. Data types supported by the partition keys are as follows: INT1\[UNSIGNED], INT2\[UNSIGNED], INT4\[UNSIGNED], INT8\[UNSIGNED], NUMERIC, VARCHAR(n), CHAR, BPCHAR, NVARCHAR, NVARCHAR2, TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE], and DATE. The number of partitions cannot exceed 1048575. * **PARTITION BY HASH(partition\_key)** Create a hash partition. partition\_key indicates the name of the partition key. For **partition\_key**, the hash partitioning policy supports only one column of partition keys. Data types supported by the partition keys are as follows: INT1\[UNSIGNED], INT2\[UNSIGNED], INT4\[UNSIGNED], INT8\[UNSIGNED], NUMERIC, VARCHAR(n), CHAR, BPCHAR, TEXT, NVARCHAR, NVARCHAR2, TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE], and DATE. The number of partitions cannot exceed 1048575. * **PARTITION BY KEY(opt\_partition\_key)** Create a key partition. opt\_partition\_key is optional, and it indicates the name of the partition key. For **opt\_partition\_key**, when user explicitly provides the partition key, the key partitioning policy supports only one column of partition keys. When no partition keys are provided, the table's primary key is used. Currently composite primary keys are not supported. Data types supported by the partition keys are as follows: INT1\[UNSIGNED], INT2\[UNSIGNED], INT4\[UNSIGNED], INT8\[UNSIGNED], NUMERIC, VARCHAR(n), CHAR, BPCHAR, TEXT, NVARCHAR, NVARCHAR2, TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE], and DATE. The number of partitions cannot exceed 1048575. * **{ ENABLE | DISABLE } ROW MOVEMENT** Specifies whether to enable row movement. If the tuple value is updated on the partition key during the **UPDATE** operation, the partition where the tuple is located is altered. Setting of this parameter enables error messages to be reported or movement of the tuple between partitions. Value range: * **ENABLE** (default value): Row movement is enabled. * **DISABLE**: Row movement is disabled. > \[!TIP]NOTICE > Currently, list and hash partitioned tables do not support **ROW MOVEMENT**. * **NOT NULL** The column is not allowed to contain null values. **ENABLE** can be omitted. * **NULL** Indicates that the column is allowed to contain **NULL** values. This is the default setting. This clause is only provided for compatibility with non-standard SQL databases. It is not recommended. * **CHECK (condition) \[ NO INHERIT ]** The CHECK constraint specifies an expression producing a Boolean result where the INSERT or UPDATE operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A check constraint specified as a column constraint should reference only the column's values, while an expression in a table constraint can reference multiple columns. A constraint marked with **NO INHERIT** will not propagate to child tables. **ENABLE** can be omitted. * **DEFAULT default\_expr** Assigns a default data value to a column. The value can be any variable-free expressions (Subqueries and cross-references to other columns in the current table are not allowed). The data type of the default expression must match that of the column. The default expression will be used in any INSERT operation that does not specify a value for the column. If there is no default value for a column, then the default value is **NULL**. * GENERATED ALWAYS AS ( generation\_expr ) STORED This clause creates a column as a generated column. The value of the generated column is calculated by **generation\_expr** when data is written (inserted or updated). **STORED** indicates that the value of the generated column is stored as a common column. > \[!NOTE]NOTE > > * The generation expression cannot refer to data other than the current row in any way. The generation expression cannot reference other generation columns or system columns. The generation expression cannot return a result set. No subquery, aggregate function, or window function can be used. The function called by the generation expression can only be an immutable function. > > * Default values cannot be specified for generated columns. > > * The generated column cannot be used as a part of the partition key. > > * Do not specify the generated column and the CASCADE, SET NULL, and SET DEFAULT actions of the ON UPDATE constraint at the same time. Do not specify the generated column and the SET NULL, and SET DEFAULT actions of the ON DELETE constraint at the same time. > > * The method of modifying and deleting generated columns is the same as that of common columns. Delete the common column that the generated column depends on. The generated column is automatically deleted. The type of the column on which the generated column depends cannot be changed. > > * The generated column cannot be directly written. In the INSERT or UPDATE statement, values cannot be specified for generated columns, but the keyword DEFAULT can be specified. > > * The permission control for generated columns is the same as that for common columns. > > * Columns cannot be generated for column-store tables and MOTs. In foreign tables, only postgres\_fdw supports generated columns. * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** The UNIQUE constraint specifies that a group of one or more columns of a table can contain only unique values. For the UNIQUE constraint, **NULL** is not considered equal. * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** Specifies that a column or columns of a table can contain only unique (non-duplicate) and non-**NULL** values. Only one primary key can be specified for a table. * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(default): Enable constraints, create indexes, and enforce constraints on both existing data and newly added data. * ENABLE NOVALIDATE: Enable constraints and create indexes. For CHECK constraints, the constraints are only enforced for newly added data, regardless of the existing data in the table. For UNIQUE and PRIMARY KEY, indexes need to be established, so the constraints will be enforced for the existing data. * DISABLE( NOVALIDATE)(default): Disable constraints, delete indexes, and operations such as modifying the data of the constraint columns can be performed. * DISABLE VALIDATE: Disable constraints and delete indexes. Insertion, update and deletion operations on the table cannot be performed. * **DEFERRABLE | NOT DEFERRABLE** They determine whether the constraint is deferrable. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable can be postponed until the end of the transaction using the **SET CONSTRAINTS** command. **NOT DEFERRABLE** is the default value. Currently, only UNIQUE constraints, primary key constraints, and foreign key constraints accept this clause. All the other constraints are not deferrable. * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** If a constraint is deferrable, this clause specifies the default time to check the constraint. * If the constraint is **INITIALLY IMMEDIATE** (default value), it is checked after each statement. * If the constraint is **INITIALLY DEFERRED**, it is checked only at the end of the transaction. The constraint check time can be altered using the **SET CONSTRAINTS** statement. * **USING INDEX TABLESPACE tablespace\_name** Allows selection of the tablespace in which the index associated with a **UNIQUE** or **PRIMARY KEY** constraint will be created. If not specified, the index is created in **default\_tablespace**. If **default\_tablespace** is empty, the default tablespace of the database is used. ## Examples * Example 1: Create a range-partitioned table **tpcds.web\_returns\_p1**. The table has eight partitions and their partition keys are of type integer. The partition ranges are wr\_returned\_date\_sk< 2450815, 2450815<= wr\_returned\_date\_sk< 2451179, 2451179<=wr\_returned\_date\_sk< 2451544, 2451544 <= wr\_returned\_date\_sk< 2451910, 2451910 <= wr\_returned\_date\_sk< 2452275, 2452275 <= wr\_returned\_date\_sk< 2452640, 2452640 <= wr\_returned\_date\_sk< 2453005, and wr\_returned\_date\_sk>=2453005. ``` --Create a table named tpcds.web_returns. openGauss=# CREATE TABLE tpcds.web_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --Create a partitioned table named tpcds.web_returns_p1. openGauss=# CREATE TABLE tpcds.web_returns_p1 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) ); --Import data from the example data table. openGauss=# INSERT INTO tpcds.web_returns_p1 SELECT * FROM tpcds.web_returns; --Delete partition **P8**. openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION P8; --Add a partition **WR_RETURNED_DATE_SK** with values ranging from 2453005 to 2453105. openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P8 VALUES LESS THAN (2453105); --Add a partition **WR_RETURNED_DATE_SK** with values ranging from 2453105 to **MAXVALUE**. openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P9 VALUES LESS THAN (MAXVALUE); --Delete partition **P8**. openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION FOR (2453005); --Rename the **P7** partition as **P10**. openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION P7 TO P10; --Rename the **P6** partition as **P11**. openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION FOR (2452639) TO P11; --Query rows in the **P10** partition. openGauss=# SELECT count(*) FROM tpcds.web_returns_p1 PARTITION (P10); count -------- 0 (1 row) --Query the number of rows in the **P1** partition. openGauss=# SELECT COUNT(*) FROM tpcds.web_returns_p1 PARTITION FOR (2450815); count -------- 0 (1 row) ``` * Example 2: Create a range partitioned table **tpcds.web\_returns\_p2**. The table has eight partitions and their partition keys are of type integer. The upper limit of the eighth partition is **MAXVALUE**. The ranges of the eight partitions are wr\_returned\_date\_sk< 2450815, 2450815<= wr\_returned\_date\_sk< 2451179, 2451179<=wr\_returned\_date\_sk< 2451544, 2451544 <= wr\_returned\_date\_sk< 2451910, 2451910 <= wr\_returned\_date\_sk< 2452275, 2452275 <= wr\_returned\_date\_sk< 2452640, 2452640 <= wr\_returned\_date\_sk< 2453005, and wr\_returned\_date\_sk>=2453005. The tablespace of the **tpcds.web\_returns\_p2** partitioned table is **example1**. Partitions **P1** to **P7** have no specified tablespaces, and use the **example1** tablespace of the **tpcds.web\_returns\_p2** partitioned table. The tablespace of the **P8** partitioned table is **example2**. Assume that the following data directories of the database nodes are empty directories for which user **dwsadmin** has the read and write permissions: **/pg\_location/mount1/path1**, **/pg\_location/mount2/path2**, **/pg\_location/mount3/path3**, and **/pg\_location/mount4/path4**. ``` openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; openGauss=# CREATE TABLE tpcds.web_returns_p2 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) TABLESPACE example1 PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --Create a partitioned table using **LIKE**. openGauss=# CREATE TABLE tpcds.web_returns_p3 (LIKE tpcds.web_returns_p2 INCLUDING PARTITION); --Change the tablespace of the **P1** partition to **example2**. openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P1 TABLESPACE example2; --Change the tablespace of the **P2** partition to **example3**. openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P2 TABLESPACE example3; --Split the **P8** partition at 2453010. openGauss=# ALTER TABLE tpcds.web_returns_p2 SPLIT PARTITION P8 AT (2453010) INTO ( PARTITION P9, PARTITION P10 ); --Merge the **P6** and **P7** partitions into one. openGauss=# ALTER TABLE tpcds.web_returns_p2 MERGE PARTITIONS P6, P7 INTO PARTITION P8; --Modify the migration attribute of a partitioned table. openGauss=# ALTER TABLE tpcds.web_returns_p2 DISABLE ROW MOVEMENT; --Drop tables and tablespaces. openGauss=# DROP TABLE tpcds.web_returns_p1; openGauss=# DROP TABLE tpcds.web_returns_p2; openGauss=# DROP TABLE tpcds.web_returns_p3; openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; ``` * Example 3: Use **START END** to create and modify a range partitioned table. Assume that **/home/omm/startend\_tbs1**, **/home/omm/startend\_tbs2**, **/home/omm/startend\_tbs3**, and **/home/omm/startend\_tbs4** are empty directories on which user **omm** has the read and write permissions. ``` -- Creating Tablespaces openGauss=# CREATE TABLESPACE startend_tbs1 LOCATION '/home/omm/startend_tbs1'; openGauss=# CREATE TABLESPACE startend_tbs2 LOCATION '/home/omm/startend_tbs2'; openGauss=# CREATE TABLESPACE startend_tbs3 LOCATION '/home/omm/startend_tbs3'; openGauss=# CREATE TABLESPACE startend_tbs4 LOCATION '/home/omm/startend_tbs4'; -- Create a temporary schema. openGauss=# CREATE SCHEMA tpcds; openGauss=# SET CURRENT_SCHEMA TO tpcds; -- Create a partitioned table with the partition key of type integer. openGauss=# CREATE TABLE tpcds.startend_pt (c1 INT, c2 INT) TABLESPACE startend_tbs1 PARTITION BY RANGE (c2) ( PARTITION p1 START(1) END(1000) EVERY(200) TABLESPACE startend_tbs2, PARTITION p2 END(2000), PARTITION p3 START(2000) END(2500) TABLESPACE startend_tbs3, PARTITION p4 START(2500), PARTITION p5 START(3000) END(5000) EVERY(1000) TABLESPACE startend_tbs4 ) ENABLE ROW MOVEMENT; -- View the information of the partitioned table. openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs1 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p5_2 | {5000} | startend_tbs4 startend_pt | | startend_tbs1 (12 rows) -- Import data and check the data volume in the partition. openGauss=# INSERT INTO tpcds.startend_pt VALUES (GENERATE_SERIES(0, 4999), GENERATE_SERIES(0, 4999)); openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION FOR (0); count ------- 1 (1 row) openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION (p3); count ------- 500 (1 row) -- Add partitions [5000, 5300), [5300, 5600), [5600, 5900), and [5900, 6000). openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p6 START(5000) END(6000) EVERY(300) TABLESPACE startend_tbs4; -- Add the partition p7, specified by **MAXVALUE**. openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p7 END(MAXVALUE); -- Rename the partition p7 to p8. openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION p7 TO p8; -- Delete the partition p8. openGauss=# ALTER TABLE tpcds.startend_pt DROP PARTITION p8; -- Rename the partition where 5950 is located to p71. openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION FOR(5950) TO p71; -- Split the partition [4000, 5000) where 4500 is located. openGauss=# ALTER TABLE tpcds.startend_pt SPLIT PARTITION FOR(4500) INTO(PARTITION q1 START(4000) END(5000) EVERY(250) TABLESPACE startend_tbs3); -- Change the tablespace of the partition p2 to startend_tbs4. openGauss=# ALTER TABLE tpcds.startend_pt MOVE PARTITION p2 TABLESPACE startend_tbs4; -- View the partition status. openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs4 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p6_1 | {5300} | startend_tbs4 p6_2 | {5600} | startend_tbs4 p6_3 | {5900} | startend_tbs4 p71 | {6000} | startend_tbs4 q1_1 | {4250} | startend_tbs3 q1_2 | {4500} | startend_tbs3 q1_3 | {4750} | startend_tbs3 q1_4 | {5000} | startend_tbs3 startend_pt | | startend_tbs1 (19 rows) -- Delete tables and tablespaces: openGauss=# DROP SCHEMA tpcds CASCADE; openGauss=# DROP TABLESPACE startend_tbs1; openGauss=# DROP TABLESPACE startend_tbs2; openGauss=# DROP TABLESPACE startend_tbs3; openGauss=# DROP TABLESPACE startend_tbs4; ``` * Example 4: Create interval partitioned table **sales**. The table initially contains two partitions and the partition key is of the DATE type. Ranges of the two partitions are as follows: **time\_id** < '2019-02-01 00:00:00' and '2019-02-01 00:00:00' ≤ **time\_id** < '2019-02-02 00:00:00', respectively. ``` --Create table sales. openGauss=# CREATE TABLE sales (prod_id NUMBER(6), cust_id NUMBER, time_id DATE, channel_id CHAR(1), promo_id NUMBER(6), quantity_sold NUMBER(3), amount_sold NUMBER(10,2) ) PARTITION BY RANGE (time_id) INTERVAL('1 day') ( PARTITION p1 VALUES LESS THAN ('2019-02-01 00:00:00'), PARTITION p2 VALUES LESS THAN ('2019-02-02 00:00:00') ); -- Insert data into partition p1. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-01-10 00:00:00', 'a', 1, 1, 1); -- Insert data into partition p2. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-01 00:00:00', 'a', 1, 1, 1); -- View partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (2 rows) -- If the data to be inserted does not match any partition, create a partition and insert the data into the new partition. -- The range of the new partition is '2019-02-05 00:00:00' ≤ time_id < '2019-02-06 00:00:00'. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-05 00:00:00', 'a', 1, 1, 1); -- If the data to be inserted does not match any partition, create a partition and insert the data into the new partition. -- The range of the new partition is '2019-02-03 00:00:00' ≤ time_id < '2019-02-04 00:00:00'. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-03 00:00:00', 'a', 1, 1, 1); -- View partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- sys_p1 | i | {"2019-02-06 00:00:00"} sys_p2 | i | {"2019-02-04 00:00:00"} p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (4 rows) ``` * Example 5: Create list partitioned table **test\_list**. The table initially contains four partitions and the partition key is of the INT type. The ranges of the four partitions are 2000, 3000, 4000, and 5000 respectively. ``` --Create the test_list table. openGauss=# create table test_list (col1 int, col2 int) partition by list(col1) ( partition p1 values (2000), partition p2 values (3000), partition p3 values (4000), partition p4 values (5000) ); -- Insert data. openGauss=# INSERT INTO test_list VALUES(2000, 2000); INSERT 0 1 openGauss=# INSERT INTO test_list VALUES(3000, 3000); INSERT 0 1 -- View partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} p4 | l | {5000} (4 rows) -- The inserted data does not match the partition, and an error is reported. openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- Add a partition. openGauss=# alter table test_list add partition p5 values (6000); ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p5 | l | {6000} p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (5 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); INSERT 0 1 -- Exchange data between the partitioned table and ordinary table. openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ 2000 | 2000 (1 row) openGauss=# alter table test_list exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 2000 | 2000 (1 row) -- Truncate the partition. openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ 3000 | 3000 (1 row) openGauss=# alter table test_list truncate partition p2; ALTER TABLE openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ (0 rows) -- Delete a partition. openGauss=# alter table test_list drop partition p5; ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (4 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- Delete a partitioned table. openGauss=# drop table test_list; ``` * Example 6: Create a hash partitioned table **test\_hash**. The table initially contains two partitions and the partition key is of the INT type. ``` --Create the test_hash table. openGauss=# create table test_hash (col1 int, col2 int) partition by hash(col1) ( partition p1, partition p2 ); -- Insert data. openGauss=# INSERT INTO test_hash VALUES(1, 1); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(2, 2); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(3, 3); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(4, 4); INSERT 0 1 -- View partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_hash' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | h | {0} p2 | h | {1} (2 rows) -- View data. openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ 1 | 1 2 | 2 (2 rows) -- Exchange data between the partitioned table and ordinary table. openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# alter table test_hash exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) -- Truncate the partition. openGauss=# alter table test_hash truncate partition p2; ALTER TABLE openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ (0 rows) -- Delete a partitioned table. openGauss=# drop table test_hash; --Examples of B-compatible REBUILD, REMOVE, CHECK, REPAIR, and OPTIMIZE syntax --Create a partitioned table test_part. CREATE TABLE IF NOT EXISTS test_part ( a int primary key not null default 5, b int, c int, d int ) PARTITION BY RANGE(a) ( PARTITION p0 VALUES LESS THAN (100000), PARTITION p1 VALUES LESS THAN (200000), PARTITION p2 VALUES LESS THAN (300000) ); create unique index idx_c on test_part (c); create index idx_b on test_part using btree(b) local; alter table test_part add constraint uidx_d unique(d); alter table test_part add constraint uidx_c unique using index idx_c; --Insert data to a partitioned table. insert into test_part (with RECURSIVE t_r(i,j,k,m) as(values(0,1,2,3) union all select i+1,j+2,k+3,m+4 from t_r where i < 250000) select * from t_r); --Check partitioned table system information. select relname from pg_partition where (parentid in (select oid from pg_class where relname = 'test_part')) and parttype = 'p' and oid != relfilenode order by relname; --Select data from a partitioned table by index. explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < d and d < 100000) or (219990 < d and d < 220000)); select * from test_part where ((99990 < b and b < 100000) or (219990 < b and b < 220000)); --Check the REBUILD syntax. ALTER TABLE test_part REBUILD PARTITION p0, p1; --Check the system information and actual data of the partitioned table. select relname from pg_partition where (parentid in (select oid from pg_class where relname = 'test_part')) and parttype = 'p' and oid != relfilenode order by relname; explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < d and d < 100000) or (219990 < d and d < 220000)); select * from test_part where ((99990 < b and b < 100000) or (219990 < b and b < 220000)); --Check the REBUILD PARTITION ALL syntax. ALTER TABLE test_part REBUILD PARTITION all; --Check the system information and actual data of the partitioned table. select relname from pg_partition where (parentid in (select oid from pg_class where relname = 'test_part')) and parttype = 'p' and oid != relfilenode order by relname; explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < d and d < 100000) or (219990 < d and d < 220000)); select * from test_part where ((99990 < b and b < 100000) or (219990 < b and b < 220000)); --Check the REPAIR CHECK OPTIMIZE syntax. ALTER TABLE test_part repair PARTITION p0,p1; ALTER TABLE test_part check PARTITION p0,p1; ALTER TABLE test_part optimize PARTITION p0,p1; ALTER TABLE test_part repair PARTITION all; ALTER TABLE test_part check PARTITION all; ALTER TABLE test_part optimize PARTITION all; --Check the REMOVE PARTITIONING syntax. select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part') order by relname; select parttype,relname from pg_class where relname = 'test_part' and relfilenode != oid; ALTER TABLE test_part remove PARTITIONING; --Check the system information and actual data after partition information is removed from the partitioned table. explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part') order by relname; select parttype,relname from pg_class where relname = 'test_part' and relfilenode != oid; --Examples of B-compatible TRUNCATE, ANALYZE, and EXCHANGE syntax CREATE TABLE IF NOT EXISTS test_part1 ( a int, b int ) PARTITION BY RANGE(a) ( PARTITION p0 VALUES LESS THAN (100), PARTITION p1 VALUES LESS THAN (200), PARTITION p2 VALUES LESS THAN (300) ); create table test_no_part1(a int, b int); insert into test_part1 values(99,1),(199,1),(299,1); select * from test_part1; --Check the B-compatible TRUNCATE PARTITION syntax. ALTER TABLE test_part1 truncate PARTITION p0, p1; select * from test_part1; insert into test_part1 (with RECURSIVE t_r(i,j) as(values(0,1) union all select i+1,j+2 from t_r where i < 20) select * from t_r); select * from test_part1; ALTER TABLE test_part1 truncate PARTITION all; select * from test_part1; --Check the openGauss TRUNCATE PARTITION syntax. insert into test_part1 values(99,1),(199,1); select * from test_part1; ALTER TABLE test_part1 truncate PARTITION p0, truncate PARTITION p1; select * from test_part1; --Check the B-compatible EXCHANGE PARTITION syntax. insert into test_part1 values(99,1),(199,1),(299,1); alter table test_part1 exchange partition p2 with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; alter table test_part1 exchange partition p2 with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; --Check the openGauss EXCHANGE PARTITION syntax. alter table test_part1 exchange partition (p2) with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; alter table test_part1 exchange partition (p2) with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; --Check the B-compatible ANALYZE PARTITION syntax. alter table test_part1 analyze partition p0,p1; alter table test_part1 analyze partition all; --Check the openGauss ANALYZE PARTITION syntax. analyze test_part1 partition (p1); --Examples of B-compatible ADD and DROP syntax CREATE TABLE IF NOT EXISTS test_part2 ( a int, b int ) PARTITION BY RANGE(a) ( PARTITION p0 VALUES LESS THAN (100), PARTITION p1 VALUES LESS THAN (200), PARTITION p2 VALUES LESS THAN (300), PARTITION p3 VALUES LESS THAN (400) ); CREATE TABLE IF NOT EXISTS test_subpart2 ( a int, b int ) PARTITION BY RANGE(a) SUBPARTITION BY RANGE(b) ( PARTITION p0 VALUES LESS THAN (100) ( SUBPARTITION p0_0 VALUES LESS THAN (100), SUBPARTITION p0_1 VALUES LESS THAN (200), SUBPARTITION p0_2 VALUES LESS THAN (300) ), PARTITION p1 VALUES LESS THAN (200) ( SUBPARTITION p1_0 VALUES LESS THAN (100), SUBPARTITION p1_1 VALUES LESS THAN (200), SUBPARTITION p1_2 VALUES LESS THAN (300) ), PARTITION p2 VALUES LESS THAN (300) ( SUBPARTITION p2_0 VALUES LESS THAN (100), SUBPARTITION p2_1 VALUES LESS THAN (200), SUBPARTITION p2_2 VALUES LESS THAN (300) ), PARTITION p3 VALUES LESS THAN (400) ( SUBPARTITION p3_0 VALUES LESS THAN (100), SUBPARTITION p3_1 VALUES LESS THAN (200), SUBPARTITION p3_2 VALUES LESS THAN (300) ) ); --test b_compatibility drop and add partition syntax select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 DROP PARTITION p3; select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 add PARTITION (PARTITION p3 VALUES LESS THAN (400),PARTITION p4 VALUES LESS THAN (500),PARTITION p5 VALUES LESS THAN (600)); select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 add PARTITION (PARTITION p6 VALUES LESS THAN (700),PARTITION p7 VALUES LESS THAN (800)); ALTER TABLE test_part2 DROP PARTITION p4,p5,p6; select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 add PARTITION (PARTITION p4 VALUES LESS THAN (500)); select relname, boundaries from pg_partition where parentid in (select oid from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_subpart2')); ALTER TABLE test_subpart2 DROP SUBPARTITION p0_0; ALTER TABLE test_subpart2 DROP SUBPARTITION p0_2, p1_0, p1_2; select relname, boundaries from pg_partition where parentid in (select oid from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_subpart2')); --Examples of B-compatible REORGANIZE syntax CREATE TABLE test_range_subpart ( a INT4 PRIMARY KEY, b INT4 ) PARTITION BY RANGE (a) SUBPARTITION BY HASH (b) ( PARTITION p1 VALUES LESS THAN (200) ( SUBPARTITION s11, SUBPARTITION s12, SUBPARTITION s13, SUBPARTITION s14 ), PARTITION p2 VALUES LESS THAN (500) ( SUBPARTITION s21, SUBPARTITION s22 ), PARTITION p3 VALUES LESS THAN (800), PARTITION p4 VALUES LESS THAN (1200) ( SUBPARTITION s41 ) ); insert into test_range_subpart values(199,1),(499,1),(799,1),(1199,1); --test test_range_subpart alter table test_range_subpart reorganize partition p1,p2 into (partition m1 values less than(100),partition m2 values less than(500)(subpartition m21,subpartition m22)); select pg_get_tabledef('test_range_subpart'); select * from test_range_subpart subpartition(m22); select * from test_range_subpart subpartition(m21); select * from test_range_subpart partition(m1); explain select /*+ indexscan(test_range_subpart test_range_subpart_pkey) */ * from test_range_subpart where a > 0; select * from test_range_subpart; -- Create an index for a partitioned table. The default value of index in CREATE TABLE is local. Global/local cannot be specified. CREATE TABLE test_partition_btree ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_btree_idx using btree(f1) ) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); -- Create a composite index for partitioned tables. CREATE TABLE test_partition_index ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_btree_idx2 using btree(f1 desc, f2 asc) ) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); -- Create indexes for a column-store partitioned table. CREATE TABLE test_partition_column ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_column(f1) ) with (ORIENTATION = COLUMN) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); -- Create an expression index for a partitioned table. CREATE TABLE test_partition_expr ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_expr_idx using btree((abs(f1)+1)) ) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); ``` ## Helpful Links [ALTER TABLE PARTITION](https://docs.opengauss.org/en/docs/latest/sql_reference/alter_table_partition.html), [DROP TABLE](https://docs.opengauss.org/en/docs/latest/sql_reference/drop_table.html) --- --- url: /en/docs/latest/sql_reference/create_table_partition.md --- # CREATE TABLE PARTITION ## Function **CREATE TABLE PARTITION** creates a partitioned table. Partitioning refers to splitting what is logically one large table into smaller physical pieces based on specific schemes. The table based on the logic is called a partitioned table, and each physical piece is called a partition. Data is stored on these physical partitions, instead of the logical partitioned table. The common forms of partitioning include range partitioning, interval partitioning, hash partitioning, list partitioning, and value partitioning. Currently, row-store tables support range partitioning, interval partitioning, hash partitioning, and list partitioning. Column-store tables support only range partitioning. In range partitioning, a table is partitioned based on ranges defined by 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. The partitioning policy for range partitioning refers to how data is inserted into partitions. Currently, range partitioning only allows the use of the range partitioning policy. In range partitioning, a 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. Interval partitioning is a special type of range partitioning. Compared with range partitioning, interval value definition is added. When no matching partition can be found for an inserted record, a partition can be automatically created based on the interval value. Interval partitioning supports only table-based partitioning of a list where the data type can be TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE] and DATE. Interval partitioning policy: A record is mapped to a created partition based on the partition key value. If the record can be mapped to a created partition, the record is inserted into the corresponding partition. Otherwise, a partition is automatically created based on the partition key value and table definition information, and then the record is inserted into the new partition. The data range of the new partition is equal to the interval value. In hash partitioning, a modulus and a remainder are specified for each partition based on a column in the table, and records to be inserted into the table are allocated to the corresponding partition, the rows in each partition must meet the following condition: The value of the partition key divided by the specified modulus generates the remainder specified for the partition key. In hash 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. List partitioning is to allocate the records to be inserted into a table to the corresponding partition based on the key values in each partition. The key values do not overlap in different partitions. Create a partition for each group of key values to store corresponding data. In list 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. Partitioning can provide several benefits: * Query performance can be improved drastically in certain situations, particularly when most of the heavily accessed rows of the table are in a single partition or a small number of partitions. Partitioning narrows the range of data search and improves data access efficiency. * In the case of an insert or update operation on most portions of a single partition, performance can be improved by taking advantage of continuous scan of that partition instead of partitions scattered across the whole table. * Frequent loading or deletion operations on records in a separate partition can be accomplished by reading or removing that partition. It also entirely avoids the **VACUUM** overload caused by bulk **DELETE** operations (Hash partitions cannot be deleted.). ## Precautions * If the constraint key of the unique constraint and primary key constraint contains all partition keys, a local index is created for the constraints. Otherwise, a global index is created. * Currently, hash partitioning and list partitioning support only single-column partitioning, and do not support multi-column partitioning. * When you have the **INSERT** permission on an interval partitioned table, partitions can be automatically created when you run **INSERT** to write data to the table. * In the **PARTITION FOR (values)** syntax for partitioned tables, values can only be constants. * In the **PARTITION FOR (values)** syntax for partitioned tables, if data type conversion is required for values, you are advised to use forcible type conversion to prevent the implicit type conversion result from being inconsistent with the expected result. * The maximum number of partitions is 1048575. Generally, it is impossible to create so many partitions, because too many partitions may cause insufficient memory. Create partitions based on the value of **local\_syscache\_threshold**. The memory used by the partitioned tables is about (number of partitions x 3/1024) MB. Theoretically, the memory occupied by the partitions cannot be greater than the value of **local\_syscache\_threshold**. In addition, some space must be reserved for other functions. * Currently, the statement specifying a partition cannot perform global index scan. ## Syntax ``` CREATE TABLE [ IF NOT EXISTS ] partition_table_name ( [ { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] }[, ... ] ] ) [ AUTO_INCREMENT [ = ] value ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMMENT {=| } 'text' ] PARTITION BY { {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_less_than_item [, ... ] )} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_start_end_item [, ... ] )} | {LIST (partition_key) ( PARTITION partition_name VALUES (list_values) [TABLESPACE tablespace_name][, ... ])} | {HASH (partition_key) ( PARTITION partition_name [TABLESPACE tablespace_name][, ... ])} {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_less_than_item [COMMENT {=| } 'text'][...][, ... ] )} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_start_end_item [COMMENT {=| } 'text'][...][, ... ] )} | {LIST | HASH (partition_key) (PARTITION partition_name [VALUES (list_values_clause)] opt_table_space [COMMENT {=| } 'text'][...])} } [ { ENABLE | DISABLE } ROW MOVEMENT ]; ``` * **column\_constraint** is as follows: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_e xpr | GENERATED ALWAYS AS ( generation_expr ) STORED | AUTO_INCREMENT | UNIQUE index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * **table\_constraint** is as follows: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * **like\_option** is as follows: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS| ALL } ``` * **index\_parameters** is as follows: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * partition\_less\_than\_item: ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } ) [TABLESPACE tablespace_name] ``` * partition\_start\_end\_item: ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE tablespace_name] ``` * COMMENT {=| } 'text': In the partition of a partitioned table, this column is meaningless and is used only for syntax compatibility. An alarm is displayed when the syntax is used in the database. ## Parameter Description * **IF NOT EXISTS** Sends a notice, but does not throw an error, if a table with the same name exists. * **partition\_table\_name** Specifies the name of a partitioned table. Value range: a string. It must comply with the identifier naming convention. * **column\_name** Specifies the name of a column to be created in the new table. Value range: a string. It must comply with the identifier naming convention. * **data\_type** Specifies the data type of the column. * **COLLATE collation** Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the **select \* from pg\_collation;** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **CONSTRAINT constraint\_name** Specifies the name of a column or table constraint. The optional constraint clauses specify constraints that new or updated rows must satisfy for an insert or update operation to succeed. There are two ways to define constraints: * A column constraint is defined as part of a column definition, and it is bound to a particular column. * A table constraint is not bound to a particular column but can apply to more than one column. constraint\_name is optional in B-compatible mode (**sql\_compatibility = 'B'**). For other modes, constraint\_name must be added. * **index\_name** Specifies an index name. > \[!TIP]NOTICE > > * index\_name is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * For foreign key constraints, if constraint\_name and index\_name are specified at the same time, constraint\_name is used as the index name. > * For a unique key constraint, if both constraint\_name and index\_name are specified, index\_name is used as the index name. * **USING method** Specifies the name of the index method to be used. For details about the value range, see [USING method](create_index.md). > \[!TIP]NOTICE > > * The USING method is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * In B-compatible mode, if USING method is not specified, the default index method is btree for ASTORE or ubtree for USTORE. * **ASC | DESC** **ASC** specifies an ascending (default) sort order. **DESC** specifies a descending sort order. > \[!TIP]NOTICE > ASC|DESC is supported only in B-compatible databases (sql\_compatibility = 'B'). * **LIKE source\_table \[ like\_option ... ]** Specifies a table from which the new table automatically copies all column names, their data types, and their not-null constraints. Unlike **INHERITS**, the new table and original table are decoupled after creation is complete. Changes to the original table will not be applied to the new table, and it is not possible to include data of the new table in scans of the original table. * Default expressions for the copied column definitions will be copied only if **INCLUDING DEFAULTS** is specified. The default behavior is to exclude default expressions, resulting in the copied columns in the new table having default values **NULL**. * If **INCLUDING GENERATED** is specified, the generated expression of the source table column is copied to the new table. By default, the generated expression is not copied. * Not-null constraints are always copied to the new table. **CHECK** constraints will only be copied if **INCLUDING CONSTRAINTS** is specified; other types of constraints will never be copied. These rules also apply to column constraints and table constraints. * Unlike those of **INHERITS**, columns and constraints copied by **LIKE** are not merged with similarly named columns and constraints. If the same name is specified explicitly or in another **LIKE** clause, an error is reported. * Any indexes on the original table will not be created on the new table, unless the **INCLUDING INDEXES** clause is specified. * **STORAGE** settings for the copied column definitions are copied only if **INCLUDING STORAGE** is specified. The default behavior is to exclude **STORAGE** settings. * If **INCLUDING COMMENTS** is specified, comments for the copied columns, constraints, and indexes are copied. The default behavior is to exclude comments. * If **INCLUDING RELOPTIONS** is specified, the new table will copy the storage parameter (that is, **WITH** clause) of the source table. The default behavior is to exclude partition definition of the storage parameter of the source table. * **INCLUDING ALL** contains the meaning of **INCLUDING DEFAULTS**, **INCLUDING CONSTRAINTS**, **INCLUDING INDEXES**, **INCLUDING STORAGE**, **INCLUDING COMMENTS**, **INCLUDING PARTITION**, and **INCLUDING RELOPTIONS**. * **AUTO\_INCREMENT \[ = ] value** This clause specifies an initial value for an auto-increment column. The value must be a positive integer and cannot exceed 2127-1. > \[!TIP]NOTICE > This clause takes effect only when **sql\_compatibility** is set to **B**. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. Optional parameters are as follows: * FILLFACTOR The fill factor of a table is a percentage from 10 to 100. **100** (complete filling) is the default value. When a smaller fill factor is specified, **INSERT** operations pack table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives **UPDATE** a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter has no meaning for column-store tables. Value range: 10–100 * ORIENTATION Determines the storage mode of the data in the table. Value range: * **COLUMN**: The data will be stored in columns. * **ROW** (default value): The data will be stored in rows. > \[!TIP]NOTICE > **orientation** cannot be modified. * COMPRESSTYPE Specifies the row-store table compression algorithm. The value **1** indicates the PGLZ algorithm, the value **2** indicates the ZSTD algorithm, the value **3** indicates the PGZSTD algorithm (currently not supported), and the value **4** indicates the ZLIB algorithm. By default, indexes are not compressed. (Only common tables in the Astore engine are supported.) Value range: 0 to 4. The default value is **0**. * COMPRESS\_LEVEL Specifies the row-store table compression algorithm level. This parameter is valid only when **COMPRESSTYPE** is set to **2** or **4**. A higher compression level indicates a better table compression effect and a slower table access speed. (Only common tables in the Astore engine are supported.) Value range: –31 to 31. The default value is **0**. * COMPRESS\_CHUNK\_SIZE Specifies the size of a row-store table compression chunk. A smaller chunk size indicates a better compression effect, and a larger data dispersion degree indicates a slower table access speed. (Only common tables in the Astore engine are supported.) Value range: subject to the page size. When the page size is 8 KB, the value can be **512**, **1024**, **2048**, or **4096**. Default value: **4096** * COMPRESS\_PREALLOC\_CHUNKS Specifies the number of pre-allocated row-store table compression chunks. A larger number of pre-allocated chunks indicates a lower table compression ratio, and a smaller data dispersion degree indicates a better access performance. (Only common tables in the Astore engine are supported.) Value range: 0 to 7. The default value is **0**. * The maximum value of this parameter is **7** when **COMPRESS\_CHUNK\_SIZE** is set to **512** or **1024**. * The maximum value of this parameter is **3** when **COMPRESS\_CHUNK\_SIZE** is set to **2048**. * The maximum value of this parameter is **1** when **COMPRESS\_CHUNK\_SIZE** is set to **4096**. * COMPRESS\_BYTE\_CONVERT Sets the preprocessing of row-store table compression byte conversion. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * COMPRESS\_DIFF\_CONVERT Sets the preprocessing of row-store table compression differentiation. This parameter can be used together only with **COMPRESS\_BYTE\_CONVERT**. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * STORAGE\_TYPE Specifies the storage engine type. This parameter cannot be modified once it is set. Value range: * **USTORE** indicates that tables support the inplace-update storage engine. Note that the **track\_counts** and **track\_activities** parameters must be enabled when the Ustore table is used. Otherwise, space expansion may occur. * **ASTORE** indicates that tables support the append-only storage engine. Default value: If no table is specified, data is stored in append-only mode by default. * COMPRESSION * Valid values for column-store tables are **LOW**, **MIDDLE**, **HIGH**, **YES**, and **NO**, and the compression level increases accordingly. The default is **LOW**. * Row-store tables do not support compression. * MAX\_BATCHROW Specifies the maximum number of rows in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000. The default value is **60000**. * PARTIAL\_CLUSTER\_ROWS Specifies the number of records to be partially clustered for storage during data loading. The parameter is only valid for column-store tables. Value range: greater than or equal to **MAX\_BATCHROW**. You are advised to set this parameter to an integer multiple of **MAX\_BATCHROW**. * DELTAROW\_THRESHOLD A reserved parameter. The parameter is only valid for column-store tables. Value range: 0 to 9999 * segment The data is stored in segment-page mode. This parameter supports only row-store tables. Column-store tables, temporary tables, and unlogged tables are not supported. The Ustore storage engine is not supported. Value range: **on** and **off** Default value: **off** * **COMPRESS / NOCOMPRESS** Specifies keyword **COMPRESS** during the creation of a table, so that the compression feature is triggered in case of bulk **INSERT** operations. If this feature is enabled, a scan is performed for all tuple data within the page to generate a dictionary and then the tuple data is compressed and stored. If **NOCOMPRESS** is specified, the table is not compressed. Row-store tables do not support compression. Default value: **NOCOMPRESS**, that is, tuple data is not compressed before storage. * **TABLESPACE tablespace\_name** Specifies that the new table will be created in the **tablespace\_name** tablespace. If not specified, the default tablespace is used. * **PARTITION BY RANGE(partition\_key)** Creates a range partition. **partition\_key** is the name of the partition key. (1) Assume that the **VALUES LESS THAN** syntax is used. > \[!TIP]NOTICE > In this case, a maximum of four partition keys are supported. Data types supported by the partition keys are as follows: SMALLINT, INTEGER, BIGINT, DECIMAL, NUMERIC, REAL, DOUBLE PRECISION, CHARACTER VARYING(\*n\_), VARCHAR(\*n\_), CHARACTER(\*n\_), CHAR(\*n\_), CHARACTER, CHAR, TEXT, NVARCHAR, NVARCHAR2, NAME, TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE], and DATE. (2) Assume that the **START END** syntax is used. > \[!TIP]NOTICE > In this case, only one partition key is supported. Data types supported by the partition key are as follows: **SMALLINT**, **INTEGER**, **BIGINT**, **DECIMAL**, **NUMERIC**, **REAL**, **DOUBLE PRECISION**, **TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]**, **TIMESTAMP\[(p)] \[WITH TIME ZONE]**, and **DATE**. (3) Assume that the **INTERVAL** syntax is used. > \[!TIP]NOTICE > In this case, only one partition key is supported. In this case, the data types supported by the partition key are TIMESTAMP\[(p)] \[WITHOUT TIME ZONE], TIMESTAMP\[(p)] \[WITH TIME ZONE] and DATE. * **PARTITION partition\_name VALUES LESS THAN ( { partition\_value | MAXVALUE } )** Specifies the information of partitions. **partition\_name** is the name of a range partition. **partition\_value** is the upper limit of a range partition, and the value depends on the type of **partition\_key**. *MAXVALUE* usually specifies the upper limit of the last range partition. > \[!TIP]NOTICE > > * Each partition requires an upper limit. > * The data type of the upper limit must be the same as that of the partition key. > * In a partition list, partitions are arranged in ascending order of upper limits. A partition with a smaller upper limit value is placed before another partition with a larger one. * **PARTITION partition\_name {START (partition\_value) END (partition\_value) EVERY (interval\_value)} |**{START (partition\_value) END (partition\_value|MAXVALUE)} | {START(partition\_value)} | **{END (partition\_value | MAXVALUE)**} Specifies the information of partitions. * **partition\_name**: name or name prefix of a range partition. It is the name prefix only in the following cases (assuming that **partition\_name** is **p1**): * If **START**+**END**+**EVERY** is used, the names of partitions will be defined as **p1\_1**, **p1\_2**, and the like. For example, if **PARTITION p1 START(1) END(4) EVERY(1)** is defined, the generated partitions are \[1, 2), \[2, 3), and \[3, 4), and their names are **p1\_1**, **p1\_2**, and **p1\_3**. In this case, **p1** is a name prefix. * If the defined statement is in the first place and has **START** specified, the range (*MINVALUE*, **START**) will be automatically used as the first actual partition, and its name will be **p1\_0**. The other partitions are then named **p1\_1**, **p1\_2**, and the like. For example, if **PARTITION p1 START(1), PARTITION p2 START(2)** is defined, generated partitions are (*MINVALUE*, 1), \[1, 2), and \[2, *MAXVALUE*), and their names will be **p1\_0**, **p1\_1**, and **p2**. In this case, **p1** is a name prefix and **p2** is a partition name. **MINVALUE** means the minimum value. * **partition\_value**: start value or end value of a range partition. The value depends on **partition\_key** and cannot be *MAXVALUE*. * **interval\_value**: width of each partition for dividing the \[**START**, **END**) range. It cannot be *MAXVALUE*. If the value of (**END** – **START**) divided by **EVERY** has a remainder, the width of only the last partition is less than the value of **EVERY**. * *MAXVALUE* usually specifies the upper limit of the last range partition. > \[!TIP]NOTICE > > 1. If the defined statement is in the first place and has **START** specified, the range (*MINVALUE*, **START**) will be automatically used as the first actual partition. > 2. The **START END** syntax must comply with the following rules: > * The value of **START** (if any, same for the following situations) in each **partition\_start\_end\_item** must be smaller than that of **END**. > > * In two adjacent **partition\_start\_end\_item** statements, the value of the first **END** must be equal to that of the second **START**. > * The value of **EVERY** in each **partition\_start\_end\_item** must be a positive number (in ascending order) and must be smaller than **END** minus **START**. > * Each partition includes the start value (unless it is *MINVALUE*) and excludes the end value. The format is as follows: \[**START**, **END**). > * Partitions created by the same **partition\_start\_end\_item** belong to the same tablespace. > * If **partition\_name** is a name prefix of a partition, the length must not exceed 57 bytes. If there are more than 57 bytes, the prefix will be automatically truncated. > * When creating or modifying a partitioned table, ensure that the total number of partitions in the table does not exceed the maximum value **1048575**. > > 3. In statements for creating partitioned tables, **START END** and **LESS THAN** cannot be used together. > 4. The **START END** syntax in a partitioned table creation SQL statement will be replaced by the **VALUES LESS THAN** syntax when **gs\_dump** is executed. * **INTERVAL ('interval\_expr') \[ STORE IN (tablespace\_name \[, ... ] ) ]** Defines interval partitioning. * **interval\_expr**: interval for automatically creating partitions, for example, 1 day or 1 month. * **STORE IN (tablespace\_name \[, ... ] )**: Specifies the list of tablespaces for storing automatically created partitions. If this parameter is specified, the automatically created partitions are cyclically selected from the tablespace list. Otherwise, the default tablespace of the partition table is used. > \[!TIP]NOTICE > Column-store tables do not support interval partitioning. * **PARTITION BY LIST(partition\_key)** Create a list partition. **partition\_key** is the name of the partition key. * For **partition\_key**, the list partitioning policy supports only one column of partition keys. * If the clause is **VALUES (list\_values\_clause)**, **list\_values\_clause** contains the key values of the corresponding partition. It is recommended that the number of key values of each partition be less than or equal to 64. Partition keys support the following data types: INT1, INT2, INT4, INT8, NUMERIC, VARCHAR(\*n\_), CHAR, BPCHAR, NVARCHAR, NVARCHAR2, TIMESTAMP\[(\*p\_)] \[WITHOUT TIME ZONE], TIMESTAMP\[(*p*)] \[WITH TIME ZONE], and DATE. The number of partitions cannot exceed 64. In version 2.0.0, when a list partition is created, the partition key cannot be DEFAULT; otherwise, the message "Un-support feature" is displayed. * **PARTITION BY HASH(partition\_key)** Create a hash partition. **partition\_key** is the name of the partition key. For **partition\_key**, the hash partitioning policy supports only one column of partition keys. Partition keys support the following data types: INT1, INT2, INT4, INT8, NUMERIC, VARCHAR(\*n\_), CHAR, BPCHAR, TEXT, NVARCHAR, NVARCHAR2, TIMESTAMP\[(\*p\_)] \[WITHOUT TIME ZONE], TIMESTAMP\[(*p*)] \[WITH TIME ZONE], and DATE. The number of partitions cannot exceed 1048575. * **{ ENABLE | DISABLE } ROW MOVEMENT** Sets row movement. If the tuple value is updated on the partition key during the **UPDATE** action, the partition where the tuple is located is altered. Setting this parameter enables error messages to be reported or movement of the tuple between partitions. Value range: * **ENABLE** (default value): Row movement is enabled. * **DISABLE**: Row movement is disabled. * **NOT NULL** The column is not allowed to contain null values. **ENABLE** can be omitted. * **NULL** Specifies that the column is allowed to contain null values. This is the default setting. This clause is only provided for compatibility with non-standard SQL databases. It is not recommended. * **CHECK (condition) \[ NO INHERIT ]** Specifies an expression producing a Boolean result where the insert or update operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A check constraint specified as a column constraint should reference only the column's values, while an expression appearing in a table constraint can reference multiple columns. A constraint marked with **NO INHERIT** will not propagate to child tables. **ENABLE** can be omitted. * **DEFAULT default\_expr** Assigns a default data value for a column. The value can be any variable-free expressions. (Subqueries and cross-references to other columns in the current table are not allowed.) The data type of the default expression must match the data type of the column. The default expression will be used in any insert operation that does not specify a value for the column. If there is no default value for a column, then the default value is null. * GENERATED ALWAYS AS ( generation\_expr ) STORED This clause creates a column as a generated column. The value of the generated column is calculated by **generation\_expr** when data is written (inserted or updated). **STORED** indicates that the value of the generated column is stored as a common column. > \[!NOTE]NOTE > > * The generation expression cannot refer to data other than the current row in any way. The generation expression cannot reference other generation columns or system columns. The generation expression cannot return a result set. No subquery, aggregate function, or window function can be used. The function called by the generation expression can only be an immutable function. > * Default values cannot be specified for generated columns. > * The generated column cannot be used as a part of the partition key. > * Do not specify the generated column and the CASCADE, SET NULL, and SET DEFAULT actions of the ON UPDATE constraint at the same time. Do not specify the generated column and the SET NULL, and SET DEFAULT actions of the ON DELETE constraint at the same time. > * The method of modifying and deleting generated columns is the same as that of common columns. Delete the common column that the generated column depends on. The generated column is automatically deleted. The type of the column on which the generated column depends cannot be changed. > * The generated column cannot be directly written. In the INSERT or UPDATE statement, values cannot be specified for generated columns, but the keyword DEFAULT can be specified. > * The permission control for generated columns is the same as that for common columns. > * Columns cannot be generated for column-store tables and MOTs. In foreign tables, only **postgres\_fdw** supports generated columns. * **AUTO\_INCREMENT** Specifies an auto-increment column. For details, see [AUTO\_INCREMENT](create_table.md). * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** Specifies that a group of one or more columns of a table can contain only unique values. For the purpose of a unique constraint, null is not considered equal. * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** Specifies that a column or columns of a table can contain only unique (non-duplicate) and non-null values. Only one primary key can be specified for a table. * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(default): Enable constraints, create indexes, and enforce constraints on both existing data and newly added data. * ENABLE NOVALIDATE: Enable constraints and create indexes. For CHECK constraints, the constraints are only enforced for newly added data, regardless of the existing data in the table. For UNIQUE and PRIMARY KEY, indexes need to be established, so the constraints will be enforced for the existing data. * DISABLE( NOVALIDATE)(default): Disable constraints, delete indexes, and operations such as modifying the data of the constraint columns can be performed. * DISABLE VALIDATE: Disable constraints and delete indexes. Insertion, update and deletion operations on the table cannot be performed. * **DEFERRABLE | NOT DEFERRABLE** Controls whether the constraint can be deferred. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable can be postponed until the end of the transaction using the **SET CONSTRAINTS** command. **NOT DEFERRABLE** is the default value. Currently, only UNIQUE constraints, primary key constraints, and foreign key constraints accept this clause. All the other constraints are not deferrable. * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** If a constraint is deferrable, this clause specifies the default time to check the constraint. * If the constraint is **INITIALLY IMMEDIATE** (default value), it is checked after each statement. * If the constraint is **INITIALLY DEFERRED**, it is checked only at the end of the transaction. The constraint check time can be altered using the **SET CONSTRAINTS** statement. * **USING INDEX TABLESPACE tablespace\_name** Allows selection of the tablespace in which the index associated with a **UNIQUE** or **PRIMARY KEY** constraint will be created. If not specified, **default\_tablespace** is consulted, or the default tablespace in the database if **default\_tablespace** is empty. ## Examples * Example 1: Create a range-partitioned table **tpcds.web\_returns\_p1**. The table has eight partitions and their partition keys are of the integer type. The ranges of the partitions are: wr\_returned\_date\_sk < 2450815, 2450815 ≤ wr\_returned\_date\_sk < 2451179, 2451179 ≤ wr\_returned\_date\_sk < 2451544, 2451544 ≤ wr\_returned\_date\_sk < 2451910, 2451910 ≤ wr\_returned\_date\_sk < 2452275, 2452275 ≤ wr\_returned\_date\_sk < 2452640, 2452640 ≤ wr\_returned\_date\_sk < 2453005, and wr\_returned\_date\_sk ≥ 2453005. ``` -- Create the tpcds.web_returns table. openGauss=# CREATE TABLE tpcds.web_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); -- Create a range-partitioned table tpcds.web_returns_p1. openGauss=# CREATE TABLE tpcds.web_returns_p1 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) ); -- Import data from the example data table. openGauss=# INSERT INTO tpcds.web_returns_p1 SELECT * FROM tpcds.web_returns; -- Delete the P8 partition. openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION P8; -- Add a partition WR_RETURNED_DATE_SK with values ranging from 2453005 to 2453105. openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P8 VALUES LESS THAN (2453105); -- Add a partition WR_RETURNED_DATE_SK with values ranging from 2453105 to MAXVALUE. openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P9 VALUES LESS THAN (MAXVALUE); -- Delete the P8 partition. openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION FOR (2453005); -- Rename the P7 partition to P10. openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION P7 TO P10; -- Rename the P6 partition to P11. openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION FOR (2452639) TO P11; -- Query the number of rows in the P10 partition. openGauss=# SELECT count(*) FROM tpcds.web_returns_p1 PARTITION (P10); count -------- 0 (1 row) -- Query the number of rows in the P1 partition. openGauss=# SELECT COUNT(*) FROM tpcds.web_returns_p1 PARTITION FOR (2450815); count -------- 0 (1 row) ``` * Example 2: Create a range-partitioned table **tpcds.web\_returns\_p2**. The table has eight partitions and their partition keys are of the integer type. The upper limit of the eighth partition is *MAXVALUE*. The ranges of the partitions are: wr\_returned\_date\_sk < 2450815, 2450815 ≤ wr\_returned\_date\_sk < 2451179, 2451179 ≤ wr\_returned\_date\_sk < 2451544, 2451544 ≤ wr\_returned\_date\_sk < 2451910, 2451910 ≤ wr\_returned\_date\_sk < 2452275, 2452275 ≤ wr\_returned\_date\_sk < 2452640, 2452640 ≤ wr\_returned\_date\_sk < 2453005, and wr\_returned\_date\_sk ≥ 2453005. The tablespace of the **tpcds.web\_returns\_p2** partitioned table is **example1**. Partitions **P1** to **P7** have no specified tablespaces, and use the **example1** tablespace of the **tpcds.web\_returns\_p2** partitioned table. The tablespace of the **P8** partitioned table is **example2**. Assume that the following data directories of the database nodes are empty directories for which user **dwsadmin** has the read and write permissions: **/pg\_location/mount1/path1**, **/pg\_location/mount2/path2**, **/pg\_location/mount3/path3**, and **/pg\_location/mount4/path4**. ``` openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; openGauss=# CREATE TABLE tpcds.web_returns_p2 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) TABLESPACE example1 PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; -- Create a partitioned table using LIKE. openGauss=# CREATE TABLE tpcds.web_returns_p3 (LIKE tpcds.web_returns_p2 INCLUDING PARTITION); -- Change the tablespace of the P1 partition to example2. openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P1 TABLESPACE example2; -- Change the tablespace of the P2 partition to example3. openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P2 TABLESPACE example3; -- Split the P8 partition at 2453010. openGauss=# ALTER TABLE tpcds.web_returns_p2 SPLIT PARTITION P8 AT (2453010) INTO ( PARTITION P9, PARTITION P10 ); -- Merge the P6 and P7 partitions into one. openGauss=# ALTER TABLE tpcds.web_returns_p2 MERGE PARTITIONS P6, P7 INTO PARTITION P8; -- Modify the migration attribute of the partitioned table. openGauss=# ALTER TABLE tpcds.web_returns_p2 DISABLE ROW MOVEMENT; -- Delete tables and tablespaces. openGauss=# DROP TABLE tpcds.web_returns_p1; openGauss=# DROP TABLE tpcds.web_returns_p2; openGauss=# DROP TABLE tpcds.web_returns_p3; openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; ``` * Example 3: Use **START END** to create and modify a range-partitioned table. Assume that **/home/omm/startend\_tbs1**, **/home/omm/startend\_tbs2**, **/home/omm/startend\_tbs3**, and **/home/omm/startend\_tbs4** are empty directories for which user omm has the read and write permissions. ``` -- Create tablespaces. openGauss=# CREATE TABLESPACE startend_tbs1 LOCATION '/home/omm/startend_tbs1'; openGauss=# CREATE TABLESPACE startend_tbs2 LOCATION '/home/omm/startend_tbs2'; openGauss=# CREATE TABLESPACE startend_tbs3 LOCATION '/home/omm/startend_tbs3'; openGauss=# CREATE TABLESPACE startend_tbs4 LOCATION '/home/omm/startend_tbs4'; -- Create a temporary schema. openGauss=# CREATE SCHEMA tpcds; openGauss=# SET CURRENT_SCHEMA TO tpcds; -- Create a partitioned table with the partition key of the integer type. openGauss=# CREATE TABLE tpcds.startend_pt (c1 INT, c2 INT) TABLESPACE startend_tbs1 PARTITION BY RANGE (c2) ( PARTITION p1 START(1) END(1000) EVERY(200) TABLESPACE startend_tbs2, PARTITION p2 END(2000), PARTITION p3 START(2000) END(2500) TABLESPACE startend_tbs3, PARTITION p4 START(2500), PARTITION p5 START(3000) END(5000) EVERY(1000) TABLESPACE startend_tbs4 ) ENABLE ROW MOVEMENT; -- View the information of the partitioned table. openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs1 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p5_2 | {5000} | startend_tbs4 startend_pt | | startend_tbs1 (12 rows) -- Import data and check the data volume in a partition. openGauss=# INSERT INTO tpcds.startend_pt VALUES (GENERATE_SERIES(0, 4999), GENERATE_SERIES(0, 4999)); openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION FOR (0); count ------- 1 (1 row) openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION (p3); count ------- 500 (1 row) -- Add partitions [5000, 5300), [5300, 5600), [5600, 5900), and [5900, 6000). openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p6 START(5000) END(6000) EVERY(300) TABLESPACE startend_tbs4; -- Add the partition p7, specified by MAXVALUE. openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p7 END(MAXVALUE); -- Rename the partition p7 to p8. openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION p7 TO p8; -- Delete the partition p8. openGauss=# ALTER TABLE tpcds.startend_pt DROP PARTITION p8; -- Rename the partition where 5950 is located to p71. openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION FOR(5950) TO p71; -- Split the partition [4000, 5000) where 4500 is located. openGauss=# ALTER TABLE tpcds.startend_pt SPLIT PARTITION FOR(4500) INTO(PARTITION q1 START(4000) END(5000) EVERY(250) TABLESPACE startend_tbs3); -- Change the tablespace of the partition p2 to startend_tbs4. openGauss=# ALTER TABLE tpcds.startend_pt MOVE PARTITION p2 TABLESPACE startend_tbs4; -- View the partition status. openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs4 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p6_1 | {5300} | startend_tbs4 p6_2 | {5600} | startend_tbs4 p6_3 | {5900} | startend_tbs4 p71 | {6000} | startend_tbs4 q1_1 | {4250} | startend_tbs3 q1_2 | {4500} | startend_tbs3 q1_3 | {4750} | startend_tbs3 q1_4 | {5000} | startend_tbs3 startend_pt | | startend_tbs1 (19 rows) -- Delete tables and tablespaces. openGauss=# DROP SCHEMA tpcds CASCADE; openGauss=# DROP TABLESPACE startend_tbs1; openGauss=# DROP TABLESPACE startend_tbs2; openGauss=# DROP TABLESPACE startend_tbs3; openGauss=# DROP TABLESPACE startend_tbs4; ``` * Example 4: Create interval partitioned table **sales**. The table initially contains two partitions and the partition key is of the DATE type. Ranges of the two partitions are as follows: **time\_id** < '2019-02-01 00:00:00' and '2019-02-01 00:00:00' ≤ **time\_id** < '2019-02-02 00:00:00', respectively. ``` -- Create table sales. openGauss=# CREATE TABLE sales (prod_id NUMBER(6), cust_id NUMBER, time_id DATE, channel_id CHAR(1), promo_id NUMBER(6), quantity_sold NUMBER(3), amount_sold NUMBER(10,2) ) PARTITION BY RANGE (time_id) INTERVAL('1 day') ( PARTITION p1 VALUES LESS THAN ('2019-02-01 00:00:00'), PARTITION p2 VALUES LESS THAN ('2019-02-02 00:00:00') ); -- Insert data into partition p1. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-01-10 00:00:00', 'a', 1, 1, 1); -- Insert data into partition p2. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-01 00:00:00', 'a', 1, 1, 1); -- View the partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (2 rows) -- If the data to be inserted does not match any partition, create a partition and insert the data into the new partition. -- The range of the new partition is '2019-02-05 00:00:00' ≤ time_id < '2019-02-06 00:00:00'. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-05 00:00:00', 'a', 1, 1, 1); -- If the data to be inserted does not match any partition, create a partition and insert the data into the new partition. -- The range of the new partition is '2019-02-03 00:00:00' ≤ time_id < '2019-02-04 00:00:00'. openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-03 00:00:00', 'a', 1, 1, 1); -- View the partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- sys_p1 | i | {"2019-02-06 00:00:00"} sys_p2 | i | {"2019-02-04 00:00:00"} p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (4 rows) ``` * Example 5: Create list partitioned table **test\_list**. The table initially contains four partitions and the partition key is of the INT type. The ranges of the four partitions are 2000, 3000, 4000, and 5000 respectively. ``` -- Create the test_list table. openGauss=# create table test_list (col1 int, col2 int) partition by list(col1) ( partition p1 values (2000), partition p2 values (3000), partition p3 values (4000), partition p4 values (5000) ); -- Insert data. openGauss=# INSERT INTO test_list VALUES(2000, 2000); INSERT 0 1 openGauss=# INSERT INTO test_list VALUES(3000, 3000); INSERT 0 1 -- View the partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} p4 | l | {5000} (4 rows) -- The inserted data does not match the partition, and an error is reported. openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- Add a partition. openGauss=# alter table test_list add partition p5 values (6000); ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p5 | l | {6000} p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (5 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); INSERT 0 1 -- Exchange data between the partitioned table and ordinary table. openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ 2000 | 2000 (1 row) openGauss=# alter table test_list exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 2000 | 2000 (1 row) -- Truncate the partition. openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ 3000 | 3000 (1 row) openGauss=# alter table test_list truncate partition p2; ALTER TABLE openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ (0 rows) -- Delete the partition. openGauss=# alter table test_list drop partition p5; ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (4 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- Delete the partitioned table. openGauss=# drop table test_list; ``` * Example 6: Create a hash partitioned table **test\_hash**. The table initially contains two partitions and the partition key is of the INT type. ``` -- Create the test_hash table. openGauss=# create table test_hash (col1 int, col2 int) partition by hash(col1) ( partition p1, partition p2 ); -- Insert data. openGauss=# INSERT INTO test_hash VALUES(1, 1); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(2, 2); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(3, 3); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(4, 4); INSERT 0 1 -- View the partition information. openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_hash' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | h | {0} p2 | h | {1} (2 rows) -- View the data. openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ 1 | 1 2 | 2 (2 rows) -- Exchange data between the partitioned table and ordinary table. openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# alter table test_hash exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) -- Truncate the partition. openGauss=# alter table test_hash truncate partition p2; ALTER TABLE openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ (0 rows) -- Delete the partitioned table. openGauss=# drop table test_hash; ``` ## Helpful Links [ALTER TABLE PARTITION](alter_table_partition.md) and [DROP TABLE](drop_table.md) --- --- url: >- /zh/docs/latest-lite/extension_reference/extension_reference/plugin/dolphin-CREATE-TABLE-PARTITION.md --- # CREATE TABLE PARTITION ## 功能描述 创建分区表。分区表是把逻辑上的一张表根据某种方案分成几张物理块进行存储,这张逻辑上的表称之为分区表,物理块称之为分区。分区表是一张逻辑表,不存储数据,数据实际是存储在分区上的。 常见的分区方案有范围分区(Range Partitioning)、间隔分区(Interval Partitioning)、哈希分区(Hash Partitioning)、列表分区(List Partitioning)、数值分区(Value Partition)等。目前行存表支持范围分区、间隔分区、哈希分区、列表分区,列存表仅支持范围分区。 范围分区是根据表的一列或者多列,将要插入表的记录分为若干个范围,这些范围在不同的分区里没有重叠。为每个范围创建一个分区,用来存储相应的数据。 范围分区的分区策略是指记录插入分区的方式。目前范围分区仅支持范围分区策略。 范围分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。这是最常用的分区策略。 间隔分区是一种特殊的范围分区,相比范围分区,新增间隔值定义,当插入记录找不到匹配的分区时,可以根据间隔值自动创建分区。 间隔分区只支持基于表的一列分区,并且该列只支持TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE数据类型。 间隔分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则根据分区键值和表定义信息自动创建一个分区,然后将记录插入新分区中,新创建的分区数据范围等于间隔值。 哈希分区是根据表的一列,为每个分区指定模数和余数,将要插入表的记录划分到对应的分区中,每个分区所持有的行都需要满足条件:分区键的值除以为其指定的模数将产生为其指定的余数。 哈希分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则返回报错和提示信息。 列表分区是根据表的一列,将要插入表的记录通过每一个分区中出现的键值划分到对应的分区中,这些键值在不同的分区里没有重叠。为每组键值创建一个分区,用来存储相应的数据。 列表分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。 分区可以提供若干好处: * 某些类型的查询性能可以得到极大提升。特别是表中访问率较高的行位于一个单独分区或少数几个分区上的情况下。分区可以减少数据的搜索空间,提高数据访问效率。 * 当查询或更新一个分区的大部分记录时,连续扫描那个分区而不是访问整个表可以获得巨大的性能提升。 * 如果需要大量加载或者删除的记录位于单独的分区上,则可以通过直接读取或删除那个分区以获得巨大的性能提升,同时还可以避免由于大量DELETE导致的VACUUM超载(仅范围分区)。 相比于内核语法,dolphin的rebuild,remove,check,repair,optimize,truncate,analyze,exchange,reorganize都做了B兼容模式下的特色修改。 ## 注意事项 * 唯一约束和主键约束的约束键包含所有分区键将为约束创建LOCAL索引,否则创建GLOBAL索引。 * 目前哈希分区和列表分区仅支持单列构建分区键,暂不支持多列构建分区键。 * 只需要有间隔分区表的INSERT权限,往该表INSERT数据时就可以自动创建分区。 * 对于分区表PARTITION FOR (values)语法,values只能是常量。 * 对于分区表PARTITION FOR (values)语法,values在需要数据类型转换时,建议使用强制类型转换,以防隐式类型转换结果与预期不符。 * 分区数最大值为1048575个,一般情况下业务不可能创建这么多分区,这样会导致内存不足。应参照参数local\_syscache\_threshold的值合理创建分区,分区表使用内存大致为(分区数 \* 3 / 1024)MB。理论上分区占用内存不允许大于local\_syscache\_threshold的值,同时还需要预留部分空间以供其他功能使用。 * 使用table\_indexclause创建分区表上的索引为LOCAL索引,不支持选择GLOBAL索引。 * 支持使用表达式当作分区键,允许分区键使用算术运算符 "+"、"-"、"\*"。 * 只支持部分函数允许在分区键中使用,支持的函数为: ABS()、CEILING()、DATEDIFF()、DAY()、DAYOFMONTH()、DAYOFWEEK()、DAYOFYEAR()、EXTRACT() 、FLOOR()、HOUR()、MICROSECOND()、MINUTE()、MOD()、MONTH()、QUARTER()、SECOND()、TIME\_TO\_SEC()、TO\_DAYS()、TO\_SECONDS()、UNIX\_TIMESTAMP()、WEEKDAY()、YEAR()、YEARWEEK()。 * 表达式用作分区键时,只支持设置一个partition key,且分区为range、hash和list分区,另外暂不支持列存表。 ## 语法格式 ``` CREATE TABLE [ IF NOT EXISTS ] partition_table_name ( [ { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | table_indexclause | LIKE source_table [ like_option [...] ] }[, ... ] ] ) [create_option] PARTITION BY { {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_less_than_item [, ... ] )} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_start_end_item [, ... ] )} | {LIST (partition_key) [ PARTITIONS opt_partitions_num ] (PARTITION partition_name [VALUES [IN] (list_values_clause) ] opt_table_space )} | {HASH (partition_key) [ PARTITIONS opt_partitions_num ] [ (PARTITION partition_name opt_table_space) ]} | {KEY (opt_partition_key) [ PARTITIONS opt_partitions_num ] [ (PARTITION partition_name opt_table_space) ]} } [ { ENABLE | DISABLE } ROW MOVEMENT ]; [create_option] 其中create_option为: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMPRESSION [=] compression_arg ] [ ENGINE [=] engine_name ] 除了WITH选项外允许输入多次同一种create_option,以最后一次的输入为准。 ``` 其中参数part\_option为: ``` part_option:{ COMMENT [=] 'string' | [STORAGE] ENGINE [=] engine_name } ``` * 列约束column\_constraint: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_e xpr | GENERATED ALWAYS AS ( generation_expr ) STORED | UNIQUE index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 表约束table\_constraint: ``` [ CONSTRAINT constraint_name ] { CHECK ( expression ) | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters | FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 创建表上索引table\_indexclause: ``` {INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option]... ``` * 其中参数index\_type为: ``` USING {BTREE | HASH | GIN | GIST | PSORT | UBTREE} ``` * 其中参数key\_part为: ``` {col_name [ ( length ) ] | (expr)} [ASC | DESC] ``` * 其中`col_name ( length )`为前缀键,column\_name为前缀键的字段名,length为前缀长度。前缀键将取指定字段数据的前缀作为索引键值,可以减少索引占用的存储空间。含有前缀键字段的过滤条件和连接条件可以使用索引。 > \[!NOTE]说明 > > * 前缀键支持的索引方法:Btree、UBtree。 > * 前缀键的字段的数据类型必须是二进制类型或字符类型(不包括特殊字符类型)。 > * 前缀长度必须是不超过2676的正整数,并且不能超过字段的最大长度。对于二进制类型,前缀长度以字节数为单位。对于非二进制字符类型,前缀长度以字符数为单位。键值的实际长度受内部页面限制,若字段中含有多字节字符、或者一个索引上有多个键,索引行长度可能会超限,导致报错,设定较长的前缀长度时请考虑此情况。 * 其中参数index\_option为: ``` index_option:{ COMMENT 'string' | index_type } ``` COMMENT、index\_type 的顺序和数量任意,但相同字段仅最后一个值生效。 * like选项like\_option: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS| ALL } ``` * 索引存储参数index\_parameters: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * partition\_less\_than\_item: ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } ) | MAXVALUE [TABLESPACE tablespace_name] [part_option [ ...]] ``` * partition\_start\_end\_item: ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE}) | MAXVALUE} | {START(partition_value)} | {END ({partition_value | MAXVALUE}) | MAXVALUE} } [TABLESPACE tablespace_name] [part_option [ ...]] ``` ## 参数说明 * **IF NOT EXISTS** 如果已经存在相同名称的表,不会抛出一个错误,而会发出一个通知,告知表关系已存在。 * **partition\_table\_name** 分区表的名称。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新表中要创建的字段名。 取值范围:字符串,要符合标识符的命名规范。 * **data\_type** 字段的数据类型。 * **COLLATE collation** COLLATE子句指定列的排序规则(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 * **CONSTRAINT constraint\_name** 列约束或表约束的名称。可选的约束子句用于声明约束,新行或者更新的行必须满足这些约束才能成功插入或更新。 定义约束有两种方法: * 列约束:作为一个列定义的一部分,仅影响该列。 * 表约束:不和某个列绑在一起,可以作用于多个列。 * **LIKE source\_table \[ like\_option ... ]** LIKE子句声明一个表,新表自动从这个表里面继承所有字段名及其数据类型和非空约束。 和INHERITS不同,新表与原来的表之间在创建动作完毕之后是完全无关的。在源表做的任何修改都不会传播到新表中,并且也不可能在扫描源表的时候包含新表的数据。 * 字段缺省表达式只有在声明了INCLUDING DEFAULTS之后才会包含进来。缺省是不包含缺省表达式的,即新表中所有字段的缺省值都是NULL。 * 如果指定了INCLUDING GENERATED,则源表列的生成表达式会复制到新表中。默认不复制生成表达式。 * 非空约束将总是复制到新表中,CHECK约束则仅在指定了INCLUDING CONSTRAINTS的时候才复制,而其他类型的约束则永远也不会被复制。此规则同时适用于表约束和列约束。 * 和INHERITS不同,被复制的列和约束并不使用相同的名称进行融合。如果明确的指定了相同的名称或者在另外一个LIKE子句中,将会报错。 * 如果指定了INCLUDING INDEXES,则源表上的索引也将在新表上创建,默认不建立索引。 * 如果指定了INCLUDING STORAGE,则拷贝列的STORAGE设置也将被拷贝,默认情况下不包含STORAGE设置。 * 如果指定了INCLUDING COMMENTS,则源表列、约束和索引的注释也会被拷贝过来。默认情况下,不拷贝源表的注释。 * 如果指定了INCLUDING RELOPTIONS,则源表的存储参数(即源表的WITH子句)也将拷贝至新表。默认情况下,不拷贝源表的存储参数。 * INCLUDING ALL包含了INCLUDING DEFAULTS、INCLUDING CONSTRAINTS、INCLUDING INDEXES、INCLUDING STORAGE、INCLUDING COMMENTS、INCLUDING PARTITION和INCLUDING RELOPTIONS的内容。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。参数的详细描述如下所示: * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数对于列存表没有意义。 取值范围:10~100 * ORIENTATION 决定了表的数据的存储方式。 取值范围: * COLUMN:表的数据将以列式存储。 * ROW(缺省值):表的数据将以行式存储。 > \[!TIP]须知 > orientation不支持修改。 * STORAGE\_TYPE 指定存储引擎类型,该参数设置成功后就不再支持修改。 取值范围: * USTORE,表示表支持Inplace-Update存储引擎。 * ASTORE,表示表支持Append-Only存储引擎。 * 默认值,不指定表时,默认是Append-Only存储。 * COMPRESSION * 列存表的有效值为LOW/MIDDLE/HIGH/YES/NO,压缩级别依次升高,默认值为LOW。 * 行存表不支持压缩。 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000,默认60000。 * PARTIAL\_CLUSTER\_ROWS 指定了在数据加载过程中进行将局部聚簇存储的记录数目。该参数只对列存表有效。 取值范围:大于等于MAX\_BATCHROW,建议取值为MAX\_BATCHROW的整数倍数。 * DELTAROW\_THRESHOLD 预留参数。该参数只对列存表有效。 取值范围:0~9999 * segment 使用段页式的方式存储。本参数仅支持行存表。不支持列存表、临时表、unlog表。不支持Ustore存储引擎。 取值范围:on/off 默认值:off * **COMPRESS / NOCOMPRESS** 创建一个新表时,需要在创建表语句中指定关键字COMPRESS,这样,当对该表进行批量插入时就会触发压缩特性。该特性会在页范围内扫描所有元组数据,生成字典、压缩元组数据并进行存储。指定关键字NOCOMPRESS则不对表进行压缩。行存表不支持压缩。该参数已废弃,列存表请使用COMPRESSION修改压缩等级。 缺省值为NOCOMPRESS,即不对元组数据进行压缩。 * **TABLESPACE tablespace\_name** 指定新表将要在tablespace\_name表空间内创建。如果没有声明,将使用默认表空间。 * **PARTITION BY RANGE(partition\_key)** 创建范围分区。partition\_key为分区键的名称。 (1)对于从句是VALUES LESS THAN的语法格式: > \[!TIP]须知 > 对于从句是VALUE LESS THAN的语法格式,范围分区策略的分区键最多支持4列。 该情形下,分区键支持的数据类型为:TINYINT\[UNSIGNED]、SMALLINT\[UNSIGNED]、INTEGER\[UNSIGNED]、BIGINT\[UNSIGNED]、DECIMAL、NUMERIC、REAL、DOUBLE PRECISION、CHARACTER VARYING(n)、VARCHAR(n)、CHARACTER(n)、CHAR(n)、CHARACTER、CHAR、TEXT、NVARCHAR、NVARCHAR2、NAME、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 (2)对于从句是START END的语法格式: > \[!TIP]须知 > 对于从句是START END的语法格式,范围分区策略的分区键仅支持1列。 该情形下,分区键支持的数据类型为:TINYINT\[UNSIGNED]、SMALLINT\[UNSIGNED]、INTEGER\[UNSIGNED]、BIGINT\[UNSIGNED]、DECIMAL、NUMERIC、REAL、DOUBLE PRECISION、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 (3)对于指定了INTERVAL子句的语法格式: > \[!TIP]须知 > 对于指定了INTERVAL子句的语法格式,范围分区策略的分区键仅支持1列。 该情形下,分区键支持的数据类型为:TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 * **PARTITION partition\_name VALUES LESS THAN ( { partition\_value | MAXVALUE } ) | MAXVALUE** 指定各分区的信息。partition\_name为范围分区的名称。partition\_value为范围分区的上边界,取值依赖于partition\_key的类型。MAXVALUE表示分区的上边界,它通常用于设置最后一个范围分区的上边界。 > \[!TIP]须知 > > * 每个分区都需要指定一个上边界。 > * 在加载dolphin插件的B兼容库下,分区键为有符号整型时,分区上边界的类型为int8;分区键为无符号整型时,分区上边界的类型为uint8,因此允许设置上边界的值超过分区键的最大值。 > * 分区列表是按照分区上边界升序排列的,值较小的分区位于值较大的分区之前。 * **PARTITION partition\_name {START (partition\_value) END (partition\_value) EVERY (interval\_value)}** | **{START (partition\_value) END (partition\_value|MAXVALUE) | MAXVALUE**} | {START(partition\_value)\*\*} | **{END (partition\_value | MAXVALUE) | MAXVALUE**} 指定各分区的信息,各参数意义如下: * partition\_name:范围分区的名称或名称前缀,除以下情形外(假定其中的partition\_name是p1),均为分区的名称。 * 若该定义是START+END+EVERY从句,则语义上定义的分区的名称依次为p1\_1, p1\_2, ...。例如对于定义“PARTITION p1 START(1) END(4) EVERY(1)”,则生成的分区是:\[1, 2), \[2, 3) 和 \[3, 4),名称依次为p1\_1, p1\_2和p1\_3,即此处的p1是名称前缀。 * 若该定义是第一个分区定义,且该定义有START值,则范围(MINVALUE, START)将自动作为第一个实际分区,其名称为p1\_0,然后该定义语义描述的分区名称依次为p1\_1, p1\_2, ...。例如对于完整定义“PARTITION p1 START(1), PARTITION p2 START(2)”,则生成的分区是:(MINVALUE, 1), \[1, 2) 和 \[2, MAXVALUE),其名称依次为p1\_0, p1\_1和p2,即此处p1是名称前缀,p2是分区名称。这里MINVALUE表示最小值。 * partition\_value:范围分区的端点值(起始或终点),取值依赖于partition\_key的类型,不可是MAXVALUE。 * interval\_value:对\[START,END) 表示的范围进行切分,interval\_value是指定切分后每个分区的宽度,不可是MAXVALUE;如果(END-START)值不能整除以EVERY值,则仅最后一个分区的宽度小于EVERY值。 * MAXVALUE:表示最大值,它通常用于设置最后一个范围分区的上边界。 > \[!TIP]须知 > > 1. 在创建分区表若第一个分区定义含START值,则范围(MINVALUE,START)将自动作为实际的第一个分区。 > 2. START END语法需要遵循以下限制: > * 每个partition\_start\_end\_item中的START值(如果有的话,下同)必须小于其END值。 > * 相邻的两个partition\_start\_end\_item,第一个的END值必须等于第二个的START值; > * 每个partition\_start\_end\_item中的EVERY值必须是正向递增的,且必须小于(END-START)值; > * 每个分区包含起始值,不包含终点值,即形如:\[起始值,终点值),起始值是MINVALUE时则不包含; > * 一个partition\_start\_end\_item创建的每个分区所属的TABLESPACE一样; > * partition\_name作为分区名称前缀时,其长度不要超过57字节,超过时自动截断; > * 在创建、修改分区表时请注意分区表的分区总数不可超过最大限制(1048575); > 3. 在创建分区表时START END与LESS THAN语法不可混合使用。 > 4. 即使创建分区表时使用START END语法,备份(gs\_dump)出的SQL语句也是VALUES LESS THAN语法格式。 * **INTERVAL ('interval\_expr') \[ STORE IN (tablespace\_name \[, ... ] ) ]** 间隔分区定义信息。 * interval\_expr:自动创建分区的间隔,例如:1 day、1 month。 * STORE IN (tablespace\_name \[, ... ] ):指定存放自动创建分区的表空间列表,如果有指定,则自动创建的分区从表空间列表中循环选择使用,否则使用分区表默认的表空间。 > \[!TIP]须知 > 列存表不支持间隔分区。 * **PARTITION BY LIST(partition\_key)** 创建列表分区。partition\_key为分区键的名称。 * 对于partition\_key,列表分区策略的分区键最大支持16列。 * 对于从句是VALUES (list\_values\_clause)的语法格式,list\_values\_clause中包含了对应分区存在的键值,推荐每个分区的键值数量不超过64个。 分区键支持的数据类型为:INT1\[UNSIGNED]、INT2\[UNSIGNED]、INT4\[UNSIGNED]、INT8\[UNSIGNED]、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过 1048575 个。 * **PARTITION BY HASH(partition\_key)** 创建哈希分区。partition\_key为分区键的名称。 对于partition\_key,哈希分区策略的分区键仅支持1列。 分区键支持的数据类型为:INT1\[UNSIGNED]、INT2\[UNSIGNED]、INT4\[UNSIGNED]、INT8\[UNSIGNED]、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、TEXT、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过1048575 个。 * **PARTITION BY KEY(opt\_partition\_key)** 创建键分区。opt\_partition\_key是可选的,其表示分区键的名称。 对于opt\_partition\_key,当用户明确提供了分区键时,键分区策略的分区键仅支持1列。当用户没有提供分区键时,将使用表的主键为分区键。目前组合键是不支持的。 分区键支持的数据类型为:INT1\[UNSIGNED]、INT2\[UNSIGNED]、INT4\[UNSIGNED]、INT8\[UNSIGNED]、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、TEXT、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过1048575 个。 * **{ ENABLE | DISABLE } ROW MOVEMENT** 行迁移开关。 如果进行UPDATE操作时,更新了元组在分区键上的值,造成了该元组所在分区发生变化,就会根据该开关给出报错信息,或者进行元组在分区间的转移。 取值范围: * ENABLE(缺省值):行迁移开关打开。 * DISABLE:行迁移开关关闭。 > \[!TIP]须知 > 列表/哈希分区表暂不支持ROW MOVEMENT。 * **NOT NULL** 字段值不允许为NULL。ENABLE用于语法兼容,可省略。 * **NULL** 字段值允许NULL ,这是缺省。 这个子句只是为和非标准SQL数据库兼容。不建议使用。 * **CHECK (condition) \[ NO INHERIT ]** CHECK约束声明一个布尔表达式,每次要插入的新行或者要更新的行的新值必须使表达式结果为真或未知才能成功,否则会抛出一个异常并且不会修改数据库。 声明为字段约束的检查约束应该只引用该字段的数值,而在表约束里出现的表达式可以引用多个字段。 用NO INHERIT标记的约束将不会传递到子表中去。 ENABLE用于语法兼容,可省略。 * **DEFAULT default\_expr** DEFAULT子句给字段指定缺省值。该数值可以是任何不含变量的表达式(不允许使用子查询和对本表中的其他字段的交叉引用)。缺省表达式的数据类型必须和字段类型匹配。 缺省表达式将被用于任何未声明该字段数值的插入操作。如果没有指定缺省值则缺省值为NULL 。 * GENERATED ALWAYS AS ( generation\_expr ) STORED 该子句将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,STORED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > > * 生成表达式不能以任何方式引用当前行以外的其他数据。生成表达式不能引用其他生成列,不能引用系统列。生成表达式不能返回结果集,不能使用子查询,不能使用聚集函数,不能使用窗口函数。生成表达式调用的函数只能是不可变(IMMUTABLE)函数。 > > * 不能为生成列指定默认值。 > > * 生成列不能作为分区键的一部分。 > > * 生成列不能和ON UPDATE约束字句的CASCADE,SET NULL,SET DEFAULT动作同时指定。生成列不能和ON DELETE约束字句的SET NULL、SET DEFAULT动作同时指定。 > > * 修改和删除生成列的方法和普通列相同。删除生成列依赖的普通列,生成列被自动删除。不能改变生成列所依赖的列的类型。 > > * 生成列不能被直接写入。在INSERT或UPDATE命令中, 不能为生成列指定值, 但是可以指定关键字DEFAULT。 > > * 生成列的权限控制和普通列一样。 > > * 列存表、内存表MOT不支持生成列。外表中仅postgres\_fdw支持生成列。 * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** UNIQUE约束表示表里的一个字段或多个字段的组合必须在全表范围内唯一。 对于唯一约束,NULL被认为是互不相等的。 * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** 主键约束声明表中的一个或者多个字段只能包含唯一的非NULL值。 一个表只能声明一个主键。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 * **DEFERRABLE | NOT DEFERRABLE** 这两个关键字设置该约束是否可推迟。一个不可推迟的约束将在每条命令之后马上检查。可推迟约束可以推迟到事务结尾使用SET CONSTRAINTS命令检查。缺省是NOT DEFERRABLE。目前,UNIQUE约束、主键约束、外键约束可以接受这个子句。所有其他约束类型都是不可推迟的。 * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** 如果约束是可推迟的,则这个子句声明检查约束的缺省时间。 * 如果约束是INITIALLY IMMEDIATE(缺省),则在每条语句执行之后就立即检查它; * 如果约束是INITIALLY DEFERRED ,则只有在事务结尾才检查它。 约束检查的时间可以用SET CONSTRAINTS命令修改。 * **USING INDEX TABLESPACE tablespace\_name** 为UNIQUE或PRIMARY KEY约束相关的索引声明一个表空间。如果没有提供这个子句,这个索引将在default\_tablespace中创建,如果default\_tablespace为空,将使用数据库的缺省表空间。 ## 示例 * 示例1:创建范围分区表tpcds.web\_returns\_p1,含有8个分区,分区键为integer类型。 分区的范围分别为:wr\_returned\_date\_sk< 2450815、2450815<= wr\_returned\_date\_sk< 2451179、2451179<=wr\_returned\_date\_sk< 2451544、2451544 <= wr\_returned\_date\_sk< 2451910、2451910 <= wr\_returned\_date\_sk< 2452275、2452275 <= wr\_returned\_date\_sk< 2452640、2452640 <= wr\_returned\_date\_sk< 2453005、wr\_returned\_date\_sk>=2453005。 ``` --创建表tpcds.web_returns。 openGauss=# CREATE TABLE tpcds.web_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建分区表tpcds.web_returns_p1。 openGauss=# CREATE TABLE tpcds.web_returns_p1 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) ); --从示例数据表导入数据。 openGauss=# INSERT INTO tpcds.web_returns_p1 SELECT * FROM tpcds.web_returns; --删除分区P8。 openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION P8; --增加分区WR_RETURNED_DATE_SK介于2453005和2453105之间。 openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P8 VALUES LESS THAN (2453105); --增加分区WR_RETURNED_DATE_SK介于2453105和MAXVALUE之间。 openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P9 VALUES LESS THAN (MAXVALUE); --删除分区P8。 openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION FOR (2453005); --分区P7重命名为P10。 openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION P7 TO P10; --分区P6重命名为P11。 openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION FOR (2452639) TO P11; --查询分区P10的行数。 openGauss=# SELECT count(*) FROM tpcds.web_returns_p1 PARTITION (P10); count -------- 0 (1 row) --查询分区P1的行数。 openGauss=# SELECT COUNT(*) FROM tpcds.web_returns_p1 PARTITION FOR (2450815); count -------- 0 (1 row) ``` * 示例2:创建范围分区表tpcds.web\_returns\_p2,含有8个分区,分区键类型为integer类型,其中第8个分区上边界为MAXVALUE。 八个分区的范围分别为: wr\_returned\_date\_sk< 2450815、2450815<= wr\_returned\_date\_sk< 2451179、2451179<=wr\_returned\_date\_sk< 2451544、2451544 <= wr\_returned\_date\_sk< 2451910、2451910 <= wr\_returned\_date\_sk< 2452275、2452275 <= wr\_returned\_date\_sk< 2452640、2452640 <= wr\_returned\_date\_sk< 2453005、wr\_returned\_date\_sk>=2453005。 分区表tpcds.web\_returns\_p2的表空间为example1;分区P1到P7没有声明表空间,使用采用分区表tpcds.web\_returns\_p2的表空间example1;指定分区P8的表空间为example2。 假定数据库节点的数据目录/pg\_location/mount1/path1,数据库节点的数据目录/pg\_location/mount2/path2,数据库节点的数据目录/pg\_location/mount3/path3,数据库节点的数据目录/pg\_location/mount4/path4是dwsadmin用户拥有读写权限的空目录。 ``` openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; openGauss=# CREATE TABLE tpcds.web_returns_p2 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) TABLESPACE example1 PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --以like方式创建一个分区表。 openGauss=# CREATE TABLE tpcds.web_returns_p3 (LIKE tpcds.web_returns_p2 INCLUDING PARTITION); --修改分区P1的表空间为example2。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P1 TABLESPACE example2; --修改分区P2的表空间为example3。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P2 TABLESPACE example3; --以2453010为分割点切分P8。 openGauss=# ALTER TABLE tpcds.web_returns_p2 SPLIT PARTITION P8 AT (2453010) INTO ( PARTITION P9, PARTITION P10 ); --将P6,P7合并为一个分区。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MERGE PARTITIONS P6, P7 INTO PARTITION P8; --修改分区表迁移属性。 openGauss=# ALTER TABLE tpcds.web_returns_p2 DISABLE ROW MOVEMENT; --删除表和表空间。 openGauss=# DROP TABLE tpcds.web_returns_p1; openGauss=# DROP TABLE tpcds.web_returns_p2; openGauss=# DROP TABLE tpcds.web_returns_p3; openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; ``` * 示例3:START END语法创建、修改Range分区表。 假定/home/omm/startend\_tbs1、/home/omm/startend\_tbs2、/home/omm/startend\_tbs3、/home/omm/startend\_tbs4是omm用户拥有读写权限的空目录。 ``` -- 创建表空间 openGauss=# CREATE TABLESPACE startend_tbs1 LOCATION '/home/omm/startend_tbs1'; openGauss=# CREATE TABLESPACE startend_tbs2 LOCATION '/home/omm/startend_tbs2'; openGauss=# CREATE TABLESPACE startend_tbs3 LOCATION '/home/omm/startend_tbs3'; openGauss=# CREATE TABLESPACE startend_tbs4 LOCATION '/home/omm/startend_tbs4'; -- 创建临时schema openGauss=# CREATE SCHEMA tpcds; openGauss=# SET CURRENT_SCHEMA TO tpcds; -- 创建分区表,分区键是integer类型 openGauss=# CREATE TABLE tpcds.startend_pt (c1 INT, c2 INT) TABLESPACE startend_tbs1 PARTITION BY RANGE (c2) ( PARTITION p1 START(1) END(1000) EVERY(200) TABLESPACE startend_tbs2, PARTITION p2 END(2000), PARTITION p3 START(2000) END(2500) TABLESPACE startend_tbs3, PARTITION p4 START(2500), PARTITION p5 START(3000) END(5000) EVERY(1000) TABLESPACE startend_tbs4 ) ENABLE ROW MOVEMENT; -- 查看分区表信息 openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs1 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p5_2 | {5000} | startend_tbs4 startend_pt | | startend_tbs1 (12 rows) -- 导入数据,查看分区数据量 openGauss=# INSERT INTO tpcds.startend_pt VALUES (GENERATE_SERIES(0, 4999), GENERATE_SERIES(0, 4999)); openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION FOR (0); count ------- 1 (1 row) openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION (p3); count ------- 500 (1 row) -- 增加分区: [5000, 5300), [5300, 5600), [5600, 5900), [5900, 6000) openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p6 START(5000) END(6000) EVERY(300) TABLESPACE startend_tbs4; -- 增加MAXVALUE分区: p7 openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p7 END(MAXVALUE); -- 重命名分区p7为p8 openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION p7 TO p8; -- 删除分区p8 openGauss=# ALTER TABLE tpcds.startend_pt DROP PARTITION p8; -- 重命名5950所在的分区为:p71 openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION FOR(5950) TO p71; -- 分裂4500所在的分区[4000, 5000) openGauss=# ALTER TABLE tpcds.startend_pt SPLIT PARTITION FOR(4500) INTO(PARTITION q1 START(4000) END(5000) EVERY(250) TABLESPACE startend_tbs3); -- 修改分区p2的表空间为startend_tbs4 openGauss=# ALTER TABLE tpcds.startend_pt MOVE PARTITION p2 TABLESPACE startend_tbs4; -- 查看分区情形 openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs4 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p6_1 | {5300} | startend_tbs4 p6_2 | {5600} | startend_tbs4 p6_3 | {5900} | startend_tbs4 p71 | {6000} | startend_tbs4 q1_1 | {4250} | startend_tbs3 q1_2 | {4500} | startend_tbs3 q1_3 | {4750} | startend_tbs3 q1_4 | {5000} | startend_tbs3 startend_pt | | startend_tbs1 (19 rows) -- 删除表和表空间 openGauss=# DROP SCHEMA tpcds CASCADE; openGauss=# DROP TABLESPACE startend_tbs1; openGauss=# DROP TABLESPACE startend_tbs2; openGauss=# DROP TABLESPACE startend_tbs3; openGauss=# DROP TABLESPACE startend_tbs4; ``` * 示例4:创建间隔分区表sales,初始包含2个分区,分区键为DATE类型。 分区的范围分别为:time\_id < '2019-02-01 00:00:00'、 '2019-02-01 00:00:00' <= time\_id < '2019-02-02 00:00:00' 。 ``` --创建表sales openGauss=# CREATE TABLE sales (prod_id NUMBER(6), cust_id NUMBER, time_id DATE, channel_id CHAR(1), promo_id NUMBER(6), quantity_sold NUMBER(3), amount_sold NUMBER(10,2) ) PARTITION BY RANGE (time_id) INTERVAL('1 day') ( PARTITION p1 VALUES LESS THAN ('2019-02-01 00:00:00'), PARTITION p2 VALUES LESS THAN ('2019-02-02 00:00:00') ); -- 数据插入分区p1 openGauss=# INSERT INTO sales VALUES(1, 12, '2019-01-10 00:00:00', 'a', 1, 1, 1); -- 数据插入分区p2 openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-01 00:00:00', 'a', 1, 1, 1); -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (2 rows) -- 插入数据没有匹配的分区,新创建一个分区,并将数据插入该分区 -- 新分区的范围为 '2019-02-05 00:00:00' <= time_id < '2019-02-06 00:00:00' openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-05 00:00:00', 'a', 1, 1, 1); -- 插入数据没有匹配的分区,新创建一个分区,并将数据插入该分区 -- 新分区的范围为 '2019-02-03 00:00:00' <= time_id < '2019-02-04 00:00:00' openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-03 00:00:00', 'a', 1, 1, 1); -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- sys_p1 | i | {"2019-02-06 00:00:00"} sys_p2 | i | {"2019-02-04 00:00:00"} p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (4 rows) ``` * 示例5:创建LIST分区表test\_list,初始包含4个分区,分区键为INT类型。4个分区的范围分别为:2000、3000、4000、5000。 ``` --创建表test_list openGauss=# create table test_list (col1 int, col2 int) partition by list(col1) ( partition p1 values (2000), partition p2 values (3000), partition p3 values (4000), partition p4 values (5000) ); -- 数据插入 openGauss=# INSERT INTO test_list VALUES(2000, 2000); INSERT 0 1 openGauss=# INSERT INTO test_list VALUES(3000, 3000); INSERT 0 1 -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} p4 | l | {5000} (4 rows) -- 插入数据没有匹配到分区,报错处理 openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- 添加分区 openGauss=# alter table test_list add partition p5 values (6000); ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p5 | l | {6000} p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (5 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); INSERT 0 1 -- 分区表和普通表交换数据 openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ 2000 | 2000 (1 row) openGauss=# alter table test_list exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 2000 | 2000 (1 row) -- truncate分区 openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ 3000 | 3000 (1 row) openGauss=# alter table test_list truncate partition p2; ALTER TABLE openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ (0 rows) -- 删除分区 openGauss=# alter table test_list drop partition p5; ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (4 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- 删除分区表 openGauss=# drop table test_list; ``` * 示例6:创建HASH分区表test\_hash,初始包含2个分区,分区键为INT类型。 ``` --创建表test_hash openGauss=# create table test_hash (col1 int, col2 int) partition by hash(col1) ( partition p1, partition p2 ); -- 数据插入 openGauss=# INSERT INTO test_hash VALUES(1, 1); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(2, 2); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(3, 3); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(4, 4); INSERT 0 1 -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_hash' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | h | {0} p2 | h | {1} (2 rows) -- 查看数据 openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ 1 | 1 2 | 2 (2 rows) -- 分区表和普通表交换数据 openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# alter table test_hash exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) -- truncate分区 openGauss=# alter table test_hash truncate partition p2; ALTER TABLE openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ (0 rows) -- 删除分区表 openGauss=# drop table test_hash; --rebuild,remove,check,repair,optimize语法示例 --创建分区表test_part CREATE TABLE IF NOT EXISTS test_part ( a int primary key not null default 5, b int, c int, d int ) PARTITION BY RANGE(a) ( PARTITION p0 VALUES LESS THAN (100000), PARTITION p1 VALUES LESS THAN (200000), PARTITION p2 VALUES LESS THAN (300000) ); create unique index idx_c on test_part (c); create index idx_b on test_part using btree(b) local; alter table test_part add constraint uidx_d unique(d); alter table test_part add constraint uidx_c unique using index idx_c; --向分区表插入数据 insert into test_part (with RECURSIVE t_r(i,j,k,m) as(values(0,1,2,3) union all select i+1,j+2,k+3,m+4 from t_r where i < 250000) select * from t_r); --检查分区表系统信息 select relname from pg_partition where (parentid in (select oid from pg_class where relname = 'test_part')) and parttype = 'p' and oid != relfilenode order by relname; --通过索引从分区表select数据 explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < d and d < 100000) or (219990 < d and d < 220000)); select * from test_part where ((99990 < b and b < 100000) or (219990 < b and b < 220000)); --测试rebuild分区表语法 ALTER TABLE test_part REBUILD PARTITION p0, p1; --检查分区表系统信息和真实数据 select relname from pg_partition where (parentid in (select oid from pg_class where relname = 'test_part')) and parttype = 'p' and oid != relfilenode order by relname; explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < d and d < 100000) or (219990 < d and d < 220000)); select * from test_part where ((99990 < b and b < 100000) or (219990 < b and b < 220000)); --测试rebuild partition all分区表语法 ALTER TABLE test_part REBUILD PARTITION all; --检查分区表系统信息和真实数据 select relname from pg_partition where (parentid in (select oid from pg_class where relname = 'test_part')) and parttype = 'p' and oid != relfilenode order by relname; explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < d and d < 100000) or (219990 < d and d < 220000)); select * from test_part where ((99990 < b and b < 100000) or (219990 < b and b < 220000)); --测试 repair check optimize 分区表语法 ALTER TABLE test_part repair PARTITION p0,p1; ALTER TABLE test_part check PARTITION p0,p1; ALTER TABLE test_part optimize PARTITION p0,p1; ALTER TABLE test_part repair PARTITION all; ALTER TABLE test_part check PARTITION all; ALTER TABLE test_part optimize PARTITION all; --测试 remove partitioning 语法 select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part') order by relname; select parttype,relname from pg_class where relname = 'test_part' and relfilenode != oid; ALTER TABLE test_part remove PARTITIONING; --检查分区表移除分区信息后的系统信息和真实数据 explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part') order by relname; select parttype,relname from pg_class where relname = 'test_part' and relfilenode != oid; --truncate,analyze,exchange语法示例 CREATE TABLE IF NOT EXISTS test_part1 ( a int, b int ) PARTITION BY RANGE(a) ( PARTITION p0 VALUES LESS THAN (100), PARTITION p1 VALUES LESS THAN (200), PARTITION p2 VALUES LESS THAN (300) ); create table test_no_part1(a int, b int); insert into test_part1 values(99,1),(199,1),(299,1); select * from test_part1; --truncate partition语法 ALTER TABLE test_part1 truncate PARTITION p0, p1; select * from test_part1; insert into test_part1 (with RECURSIVE t_r(i,j) as(values(0,1) union all select i+1,j+2 from t_r where i < 20) select * from t_r); select * from test_part1; ALTER TABLE test_part1 truncate PARTITION all; select * from test_part1; --测试opengauss truncate partition语法 insert into test_part1 values(99,1),(199,1); select * from test_part1; ALTER TABLE test_part1 truncate PARTITION p0, truncate PARTITION p1; select * from test_part1; --exchange partition语法 insert into test_part1 values(99,1),(199,1),(299,1); alter table test_part1 exchange partition p2 with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; alter table test_part1 exchange partition p2 with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; --测试opengauss exchange partition语法 alter table test_part1 exchange partition (p2) with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; alter table test_part1 exchange partition (p2) with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; --analyze partition语法 alter table test_part1 analyze partition p0,p1; alter table test_part1 analyze partition all; --测试opengauss analyze partition语法 analyze test_part1 partition (p1); --add, drop语法示例 CREATE TABLE IF NOT EXISTS test_part2 ( a int, b int ) PARTITION BY RANGE(a) ( PARTITION p0 VALUES LESS THAN (100), PARTITION p1 VALUES LESS THAN (200), PARTITION p2 VALUES LESS THAN (300), PARTITION p3 VALUES LESS THAN (400) ); CREATE TABLE IF NOT EXISTS test_subpart2 ( a int, b int ) PARTITION BY RANGE(a) SUBPARTITION BY RANGE(b) ( PARTITION p0 VALUES LESS THAN (100) ( SUBPARTITION p0_0 VALUES LESS THAN (100), SUBPARTITION p0_1 VALUES LESS THAN (200), SUBPARTITION p0_2 VALUES LESS THAN (300) ), PARTITION p1 VALUES LESS THAN (200) ( SUBPARTITION p1_0 VALUES LESS THAN (100), SUBPARTITION p1_1 VALUES LESS THAN (200), SUBPARTITION p1_2 VALUES LESS THAN (300) ), PARTITION p2 VALUES LESS THAN (300) ( SUBPARTITION p2_0 VALUES LESS THAN (100), SUBPARTITION p2_1 VALUES LESS THAN (200), SUBPARTITION p2_2 VALUES LESS THAN (300) ), PARTITION p3 VALUES LESS THAN (400) ( SUBPARTITION p3_0 VALUES LESS THAN (100), SUBPARTITION p3_1 VALUES LESS THAN (200), SUBPARTITION p3_2 VALUES LESS THAN (300) ) ); --test b_compatibility drop and add partition syntax select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 DROP PARTITION p3; select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 add PARTITION (PARTITION p3 VALUES LESS THAN (400),PARTITION p4 VALUES LESS THAN (500),PARTITION p5 VALUES LESS THAN (600)); select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 add PARTITION (PARTITION p6 VALUES LESS THAN (700),PARTITION p7 VALUES LESS THAN (800)); ALTER TABLE test_part2 DROP PARTITION p4,p5,p6; select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 add PARTITION (PARTITION p4 VALUES LESS THAN (500)); select relname, boundaries from pg_partition where parentid in (select oid from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_subpart2')); ALTER TABLE test_subpart2 DROP SUBPARTITION p0_0; ALTER TABLE test_subpart2 DROP SUBPARTITION p0_2, p1_0, p1_2; select relname, boundaries from pg_partition where parentid in (select oid from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_subpart2')); --reorganize分区语法示例 CREATE TABLE test_range_subpart ( a INT4 PRIMARY KEY, b INT4 ) PARTITION BY RANGE (a) SUBPARTITION BY HASH (b) ( PARTITION p1 VALUES LESS THAN (200) ( SUBPARTITION s11, SUBPARTITION s12, SUBPARTITION s13, SUBPARTITION s14 ), PARTITION p2 VALUES LESS THAN (500) ( SUBPARTITION s21, SUBPARTITION s22 ), PARTITION p3 VALUES LESS THAN (800), PARTITION p4 VALUES LESS THAN (1200) ( SUBPARTITION s41 ) ); insert into test_range_subpart values(199,1),(499,1),(799,1),(1199,1); --test test_range_subpart alter table test_range_subpart reorganize partition p1,p2 into (partition m1 values less than(100),partition m2 values less than(500)(subpartition m21,subpartition m22)); select pg_get_tabledef('test_range_subpart'); select * from test_range_subpart subpartition(m22); select * from test_range_subpart subpartition(m21); select * from test_range_subpart partition(m1); explain select /*+ indexscan(test_range_subpart test_range_subpart_pkey) */ * from test_range_subpart where a > 0; select * from test_range_subpart; -- 分区表建索引,在create table 中index默认为local,不支持指定global/local CREATE TABLE test_partition_btree ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_btree_idx using btree(f1) ) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); -- 分区表建组合索引 CREATE TABLE test_partition_index ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_btree_idx2 using btree(f1 desc, f2 asc) ) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); -- 分区表列存创建索引 CREATE TABLE test_partition_column ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_column(f1) ) with (ORIENTATION = COLUMN) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); -- 分区表创建表达式索引 CREATE TABLE test_partition_expr ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_expr_idx using btree((abs(f1)+1)) ) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); ``` * 示例7:创建分区键为表达式分区的分区表。 ``` openGauss=# create table testrangepart(a int, b int) partition by range(abs(a*2)) ( partition p0 values less than(100), partition p1 values less than(200) ); CREATE TABLE openGauss=# select partkeyexpr from pg_partition where (parttype = 'r') and (parentid in (select oid from pg_class where relname = 'testrangepart')); partkeyexpr --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- {FUNCEXPR :funcid 1397 :funcresulttype 23 :funcresulttype_orig -1 :funcretset false :funcformat 0 :funccollid 0 :inputcollid 0 :args ({OPEXPR :opno 514 :opfuncid 141 :opresulttype 23 :opretset false :opcollid 0 :inputcollid 0 :args ({VAR :varno 1 :varattno 1 :vartype 23 :vartypmod -1 :varcollid 0 :varlevelsup 0 :varnoold 1 :varoattno 1 :location 64} {CONST :consttype 23 :consttypmod -1 :constcollid 0 :constlen 4 :constbyval true :constisnull false :ismaxvalue false :location 66 :constvalue 4 [ 2 0 0 0 0 0 0 0 ] :cursor_data :row_count 0 :cur_dno -1 :is_open false :found false :not_found false :null_open false :null_fetch false}) :location 65}) :location 60 :refSynOid 0} (1 row) openGauss=# insert into testrangepart values(-51,1),(49,2); INSERT 0 2 openGauss=# insert into testrangepart values(-101,1); ERROR: inserted partition key does not map to any table partition openGauss=# select * from testrangepart partition(p0); a | b ----+--- 49 | 2 (1 row) openGauss=# select * from testrangepart partition(p1); a | b -----+--- -51 | 1 (1 row) openGauss=# select * from testrangepart where a = -51; a | b -----+--- -51 | 1 (1 row) ``` ## 相关链接 [ALTER TABLE PARTITION](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/alter_table_partition.html),[DROP TABLE](https://docs.opengauss.org/zh/docs/latest-lite/sql_reference/drop_table.html) --- --- url: /zh/docs/latest-lite/sql_reference/create_table_partition.md --- # CREATE TABLE PARTITION ## 功能描述 创建分区表。分区表是把逻辑上的一张表根据某种方案分成几张物理块进行存储,这张逻辑上的表称之为分区表,物理块称之为分区。分区表是一张逻辑表,不存储数据,数据实际是存储在分区上的。 常见的分区方案有范围分区(Range Partitioning)、间隔分区(Interval Partitioning)、哈希分区(Hash Partitioning)、列表分区(List Partitioning)、数值分区(Value Partition)等。目前行存表支持范围分区、间隔分区、哈希分区、列表分区,列存表仅支持范围分区。 范围分区是根据表的一列或者多列,将要插入表的记录分为若干个范围,这些范围在不同的分区里没有重叠。为每个范围创建一个分区,用来存储相应的数据。 范围分区的分区策略是指记录插入分区的方式。目前范围分区仅支持范围分区策略。 范围分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。这是最常用的分区策略。 间隔分区是一种特殊的范围分区,相比范围分区,新增间隔值定义,当插入记录找不到匹配的分区时,可以根据间隔值自动创建分区。 间隔分区只支持基于表的一列分区,并且该列只支持TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE数据类型。 间隔分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则根据分区键值和表定义信息自动创建一个分区,然后将记录插入新分区中,新创建的分区数据范围等于间隔值。 哈希分区是根据表的一列,为每个分区指定模数和余数,将要插入表的记录划分到对应的分区中,每个分区所持有的行都需要满足条件:分区键的值除以为其指定的模数将产生为其指定的余数。 哈希分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则返回报错和提示信息。 列表分区是根据表的一列,将要插入表的记录通过每一个分区中出现的键值划分到对应的分区中,这些键值在不同的分区里没有重叠。为每组键值创建一个分区,用来存储相应的数据。 列表分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。 分区可以提供若干好处: * 某些类型的查询性能可以得到极大提升。特别是表中访问率较高的行位于一个单独分区或少数几个分区上的情况下。分区可以减少数据的搜索空间,提高数据访问效率。 * 当查询或更新一个分区的大部分记录时,连续扫描那个分区而不是访问整个表可以获得巨大的性能提升。 * 如果需要大量加载或者删除的记录位于单独的分区上,则可以通过直接读取或删除那个分区以获得巨大的性能提升,同时还可以避免由于大量DELETE导致的VACUUM超载(仅范围分区)。 ## 注意事项 * 唯一约束和主键约束的约束键包含所有分区键将为约束创建LOCAL索引,否则创建GLOBAL索引。 * 目前哈希分区和列表分区仅支持单列构建分区键,暂不支持多列构建分区键。 * 只需要有间隔分区表的INSERT权限,往该表INSERT数据时就可以自动创建分区。 * 对于分区表PARTITION FOR (values)语法,values只能是常量。 * 对于分区表PARTITION FOR (values)语法,values在需要数据类型转换时,建议使用强制类型转换,以防隐式类型转换结果与预期不符。 * 分区数最大值为1048575个,一般情况下业务不可能创建这么多分区,这样会导致内存不足。应参照参数local\_syscache\_threshold的值合理创建分区,分区表使用内存大致为(分区数 \* 3 / 1024)MB。理论上分区占用内存不允许大于local\_syscache\_threshold的值,同时还需要预留部分空间以供其他功能使用。 * 指定分区语句目前不能走全局索引扫描。 * 当分区数太多导致内存不足时,会间接导致性能急剧下降。 * 支持使用表达式当作分区键,允许分区键使用算术运算符 "+"、"-"、"\*"。 * 只支持部分函数允许在分区键中使用,支持的函数为: ABS()、CEILING()。 * 表达式用作分区键时,只支持设置一个partition key,且分区为range、hash和list分区,另外暂不支持列存表。 ## 语法格式 ``` CREATE TABLE [ IF NOT EXISTS ] partition_table_name ( [ { column_name data_type [ CHARACTER SET | CHARSET charset ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ] ] ) [ AUTO_INCREMENT [ = ] value ] [ [ DEFAULT ] CHARACTER SET | CHARSET [ = ] default_charset ][ [ DEFAULT ] COLLATE [ = ] default_collation ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ DISTRIBUTE BY { REPLICATION | { [ HASH ] ( column_name ) } } ] NOTICE: DISTRIBUTE BY is only avaliable in DISTRIBUTED mode! [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] PARTITION BY { {VALUES (partition_key)} | {RANGE [ COLUMNS ] (partition_key) [ INTERVAL ('interval_expr') [ STORE IN ( tablespace_name [, ...] ) ] ] [ PARTITIONS integer ] ( partition_less_than_item [, ... ] )} | {RANGE [ COLUMNS ] (partition_key) [ INTERVAL ('interval_expr') [ STORE IN ( tablespace_name [, ...] ) ] ] [ PARTITIONS integer ] ( partition_start_end_item [, ... ] )} | {{{LIST [ COLUMNS ]} | HASH | KEY} (partition_key) [ PARTITIONS integer ] (PARTITION partition_name [ VALUES [ IN ] (list_values_clause) ] opt_table_space ) } } [ { ENABLE | DISABLE } ROW MOVEMENT ]; ``` * 列约束column\_constraint: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_e xpr | GENERATED ALWAYS AS ( generation_expr ) [STORED] | AUTO_INCREMENT | UNIQUE [KEY] index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 表约束table\_constraint: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * like选项like\_option: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS| ALL } ``` * 索引存储参数index\_parameters: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * partition\_less\_than\_item: ``` PARTITION partition_name VALUES LESS THAN {( { partition_value | MAXVALUE } [,...] ) | MAXVALUE } [TABLESPACE [=] tablespace_name] ``` * partition\_start\_end\_item: ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE [=] tablespace_name] ``` * COMMENT {=| } 'text': 分区表的分区中,该字段无实际意义,仅作语法兼容。在数据库中使用该语法时会有告警提示。 ## 参数说明 * **IF NOT EXISTS** 如果已经存在相同名称的表,不会抛出一个错误,而会发出一个通知,告知表关系已存在。 * **partition\_table\_name** 分区表的名称。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新表中要创建的字段名。 取值范围:字符串,要符合标识符的命名规范。 * **data\_type** 字段的数据类型。 * **COLLATE collation** COLLATE子句指定列的排序规则(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 * **CONSTRAINT constraint\_name** 列约束或表约束的名称。可选的约束子句用于声明约束,新行或者更新的行必须满足这些约束才能成功插入或更新。 定义约束有两种方法: * 列约束:作为一个列定义的一部分,仅影响该列。 * 表约束:不和某个列绑在一起,可以作用于多个列。 > \[!TIP]须知 > > 在B模式数据库下(即sql\_compatibility = 'B')constraint\_name为可选项,在其他模式数据库下,必须加上constraint\_name。 * **index\_name** 索引名。 > \[!TIP]须知 > > * index\_name仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 对于外键约束,constraint\_name和index\_name同时指定时,索引名为constraint\_name。 > * 对于唯一键约束,constraint\_name和index\_name同时指定时,索引名以index\_name。 * **USING method** 指定创建索引的方法。 取值范围参考[参数说明](create_index_1.md#zh-cn_topic_0283136578_zh-cn_topic_0237122106_zh-cn_topic_0059777455_s82e47e35c54c477094dcafdc90e5d85a)中的USING method。 > \[!TIP]须知 > > * USING method仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 在B模式下,未指定USING method时,对于Astore的存储方式,默认索引方法为btree;对于Ustore的存储方式,默认索引方法为ubtree。 * **ASC | DESC** ASC表示指定按升序排序(默认)。DESC指定按降序排序。 > \[!TIP]须知 > > ASC|DESC只在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库不支持。 * **LIKE source\_table \[ like\_option ... ]** LIKE子句声明一个表,新表自动从这个表里面继承所有字段名及其数据类型和非空约束。 和INHERITS不同,新表与原来的表之间在创建动作完毕之后是完全无关的。在源表做的任何修改都不会传播到新表中,并且也不可能在扫描源表的时候包含新表的数据。 * 字段缺省表达式只有在声明了INCLUDING DEFAULTS之后才会包含进来。缺省是不包含缺省表达式的,即新表中所有字段的缺省值都是NULL。 * 如果指定了INCLUDING GENERATED,则源表列的生成表达式会复制到新表中。默认不复制生成表达式。 * 非空约束将总是复制到新表中,CHECK约束则仅在指定了INCLUDING CONSTRAINTS的时候才复制,而其他类型的约束则永远也不会被复制。此规则同时适用于表约束和列约束。 * 和INHERITS不同,被复制的列和约束并不使用相同的名称进行融合。如果明确的指定了相同的名称或者在另外一个LIKE子句中,将会报错。 * 如果指定了INCLUDING INDEXES,则源表上的索引也将在新表上创建,默认不建立索引。 * 如果指定了INCLUDING STORAGE,则源表列的STORAGE设置也将被拷贝,默认情况下不包含STORAGE设置。 * 如果指定了INCLUDING COMMENTS,则源表列、约束和索引的注释也会被拷贝过来。默认情况下,不拷贝源表的注释。 * 如果指定了INCLUDING RELOPTIONS,则源表的存储参数(即源表的WITH子句)也将拷贝至新表。默认情况下,不拷贝源表的存储参数。 * INCLUDING ALL包含了INCLUDING DEFAULTS、INCLUDING CONSTRAINTS、INCLUDING INDEXES、INCLUDING STORAGE、INCLUDING COMMENTS、INCLUDING PARTITION和INCLUDING RELOPTIONS的内容。 * **AUTO\_INCREMENT \[ = ] value** 这个子句为自动增长列指定一个初始值,value必须为正整数,不得超过2127-1。 > \[!TIP]须知 > > 该子句仅在参数sql\_compatibility=B时有效。 * **\[ DEFAULT ] CHARACTER SET | CHARSET \[ = ] default\_charset ]** 指定模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **\[ \[ DEFAULT ] COLLATE \[ = ] default\_collation** 指定模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。参数的详细描述如下所示: * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数对于列存表没有意义。 取值范围:10~100 * ORIENTATION 决定了表的数据的存储方式。 取值范围: * COLUMN:表的数据将以列式存储。 * ROW(缺省值):表的数据将以行式存储。 > \[!TIP]须知 > > orientation不支持修改。 * COMPRESSTYPE 行存表参数,设置行存表压缩算法。1代表pglz算法(不推荐使用),2代表zstd算法,3代表pgzstd算法(目前暂不支持),4代表zlib算法,默认不压缩。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。(仅支持Astore和Ustore下的普通表和分区表) 取值范围:0~4,默认值为0。 * COMPRESS\_LEVEL 行存表参数,设置行存表压缩算法等级,仅当COMPRESSTYPE为2或4时生效。压缩等级越高,表的压缩效果越好,表的访问速度越慢。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:-31~31,默认值为0。 * COMPRESS\_CHUNK\_SIZE 行存表参数,设置行存表压缩chunk块大小,仅当COMPRESSTYPE不为0时生效。chunk数据块越小,预期能达到的压缩效果越好,同时数据越离散,影响表的访问速度。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:与页面大小有关。在页面大小为8k场景,取值范围为:512、1024、2048、4096。 默认值:4096 * COMPRESS\_PREALLOC\_CHUNKS 行存表参数,设置行存表压缩chunk块预分配数量。预分配数量越大,表的压缩率相对越差,离散度越小,访问性能越好。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:0~7,默认值为0。 * 当COMPRESS\_CHUNK\_SIZE为512和1024时,支持预分配设置最大为7。 * 当COMPRESS\_CHUNK\_SIZE为2048时,支持预分配设置最大为3。 * 当COMPRESS\_CHUNK\_SIZE为4096时,支持预分配设置最大为1。 * COMPRESS\_BYTE\_CONVERT 行存表参数,设置行存表压缩字节转换预处理,仅当COMPRESSTYPE不为0时生效。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:布尔值,默认关闭。 * COMPRESS\_DIFF\_CONVERT 行存表参数,设置行存表压缩字节差分预处理。只能与compress\_byte\_convert一起使用。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:布尔值,默认关闭。 * STORAGE\_TYPE 指定存储引擎类型,该参数设置成功后就不再支持修改。 取值范围: * USTORE,表示表支持Inplace-Update存储引擎。 * ASTORE,表示表支持Append-Only存储引擎。 默认值: 不指定表时,默认是Append-Only存储。 * COMPRESSION * 列存表的有效值为LOW/MIDDLE/HIGH/YES/NO,压缩级别依次升高,默认值为LOW。 * 行存表不支持压缩。 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000,默认60000。 * PARTIAL\_CLUSTER\_ROWS 指定了在数据加载过程中进行将局部聚簇存储的记录数目。该参数只对列存表有效。 取值范围:大于等于MAX\_BATCHROW,建议取值为MAX\_BATCHROW的整数倍数。 * DELTAROW\_THRESHOLD 预留参数。该参数只对列存表有效。 取值范围:0~9999 * segment 使用段页式的方式存储。本参数仅支持行存表。不支持列存表、临时表、unlog表。不支持Ustore存储引擎。 取值范围:on/off 默认值:off * **COMPRESS / NOCOMPRESS** 创建一个新表时,需要在创建表语句中指定关键字COMPRESS,这样,当对该表进行批量插入时就会触发压缩特性。该特性会在页范围内扫描所有元组数据,生成字典、压缩元组数据并进行存储。指定关键字NOCOMPRESS则不对表进行压缩。行存表不支持压缩。该参数已废弃,列存表请使用COMPRESSION修改压缩等级。 缺省值为NOCOMPRESS,即不对元组数据进行压缩。 * **TABLESPACE tablespace\_name** 指定新表将要在tablespace\_name表空间内创建。如果没有声明,将使用默认表空间。 * **TO { GROUP groupname | NODE ( nodename \[, … ] ) }** 此语法仅在扩展模式(GUC参数support\_extended\_features为on时)下可用。该模式谨慎打开,主要供内部扩容工具使用,一般用户不应使用该模式。 * **PARTITION BY VALUES (partition\_key)** 创建数值分区。partition\_key为分区键的名称。 * **PARTITION BY RANGE \[COLUMNS]\(partition\_key)** 创建范围分区。partition\_key为分区键的名称。 (1)对于从句是VALUES LESS THAN的语法格式: > \[!TIP]须知 > > 对于从句是VALUE LESS THAN的语法格式,范围分区策略的分区键最多支持4列。 该情形下,分区键支持的数据类型为:SMALLINT、INTEGER、BIGINT、DECIMAL、NUMERIC、REAL、DOUBLE PRECISION、CHARACTER VARYING(n)、VARCHAR(n)、CHARACTER(n)、CHAR(n)、CHARACTER、CHAR、TEXT、NVARCHAR、NVARCHAR2、NAME、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 (2)对于从句是START END的语法格式: > \[!TIP]须知 > > 对于从句是START END的语法格式,范围分区策略的分区键仅支持1列。 该情形下,分区键支持的数据类型为:SMALLINT、INTEGER、BIGINT、DECIMAL、NUMERIC、REAL、DOUBLE PRECISION、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 (3)对于指定了INTERVAL子句的语法格式: > \[!TIP]须知 > > 对于指定了INTERVAL子句的语法格式,范围分区策略的分区键仅支持1列。 该情形下,分区键支持的数据类型为:TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 * **PARTITION partition\_name VALUES LESS THAN ( { partition\_value | MAXVALUE } )** 指定各分区的信息。partition\_name为范围分区的名称。partition\_value为范围分区的上边界,取值依赖于partition\_key的类型。MAXVALUE表示分区的上边界,它通常用于设置最后一个范围分区的上边界。 > \[!TIP]须知 > > * 每个分区都需要指定一个上边界。 > * 分区上边界的类型应当和分区键的类型一致。 > * 分区列表是按照分区上边界升序排列的,值较小的分区位于值较大的分区之前。 * **PARTITION partition\_name {START (partition\_value) END (partition\_value) EVERY (interval\_value)} |**{START (partition\_value) END (partition\_value|MAXVALUE)} | {START(partition\_value)} | **{END (partition\_value | MAXVALUE)**} 指定各分区的信息,各参数意义如下: * partition\_name:范围分区的名称或名称前缀,除以下情形外(假定其中的partition\_name是p1),均为分区的名称。 * 若该定义是START+END+EVERY从句,则语义上定义的分区的名称依次为p1\_1, p1\_2, ...。例如对于定义“PARTITION p1 START(1) END(4) EVERY(1)”,则生成的分区是:\[1, 2), \[2, 3) 和 \[3, 4),名称依次为p1\_1, p1\_2和p1\_3,即此处的p1是名称前缀。 * 若该定义是第一个分区定义,且该定义有START值,则范围(MINVALUE, START)将自动作为第一个实际分区,其名称为p1\_0,然后该定义语义描述的分区名称依次为p1\_1, p1\_2, ...。例如对于完整定义“PARTITION p1 START(1), PARTITION p2 START(2)”,则生成的分区是:(MINVALUE, 1), \[1, 2) 和 \[2, MAXVALUE),其名称依次为p1\_0, p1\_1和p2,即此处p1是名称前缀,p2是分区名称。这里MINVALUE表示最小值。 * partition\_value:范围分区的端点值(起始或终点),取值依赖于partition\_key的类型,不可是MAXVALUE。 * interval\_value:对\[START,END) 表示的范围进行切分,interval\_value是指定切分后每个分区的宽度,不可是MAXVALUE;如果(END-START)值不能整除以EVERY值,则仅最后一个分区的宽度小于EVERY值。 * MAXVALUE:表示最大值,它通常用于设置最后一个范围分区的上边界。 > \[!TIP]须知 > > 1. 在创建分区表若第一个分区定义含START值,则范围(MINVALUE,START)将自动作为实际的第一个分区。 > 2. START END语法需要遵循以下限制: > * 每个partition\_start\_end\_item中的START值(如果有的话,下同)必须小于其END值; > * 相邻的两个partition\_start\_end\_item,第一个的END值必须等于第二个的START值; > * 每个partition\_start\_end\_item中的EVERY值必须是正向递增的,且必须小于(END-START)值; > * 每个分区包含起始值,不包含终点值,即形如:\[起始值,终点值),起始值是MINVALUE时则不包含; > * 一个partition\_start\_end\_item创建的每个分区所属的TABLESPACE一样; > * partition\_name作为分区名称前缀时,其长度不要超过57字节,超过时自动截断; > * 在创建、修改分区表时请注意分区表的分区总数不可超过最大限制(1048575); > 3. 在创建分区表时START END与LESS THAN语法不可混合使用。 > 4. 即使创建分区表时使用START END语法,备份(gs\_dump)出的SQL语句也是VALUES LESS THAN语法格式。 * **INTERVAL ('interval\_expr') \[ STORE IN (tablespace\_name \[, ... ] ) ]** 间隔分区定义信息。 * interval\_expr:自动创建分区的间隔,例如:1 day、1 month。 * STORE IN (tablespace\_name \[, ... ] ):指定存放自动创建分区的表空间列表,如果有指定,则自动创建的分区从表空间列表中循环选择使用,否则使用分区表默认的表空间。 > \[!TIP]须知 > > 列存表不支持间隔分区。 * **PARTITION BY LIST(partition\_key)** 创建列表分区。partition\_key为分区键的名称。 * 对于partition\_key,列表分区策略的分区键最大支持16列。 * 对于从句是VALUES (list\_values\_clause)的语法格式,list\_values\_clause中包含了对应分区存在的键值,推荐每个分区的键值数量不超过64个。 分区键支持的数据类型为:INT1、INT2、INT4、INT8、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过1048575个。 * **PARTITION BY HASH(partition\_key)** 创建哈希分区。partition\_key为分区键的名称。 对于partition\_key,哈希分区策略的分区键仅支持1列。 分区键支持的数据类型为:INT1、INT2、INT4、INT8、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、TEXT、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过1048575个。 * **{ ENABLE | DISABLE } ROW MOVEMENT** 行迁移开关。 如果进行UPDATE操作时,更新了元组在分区键上的值,造成了该元组所在分区发生变化,就会根据该开关给出报错信息,或者进行元组在分区间的转移。 取值范围: * ENABLE(缺省值):行迁移开关打开。 * DISABLE:行迁移开关关闭。 > \[!TIP]须知 > > 列表/哈希分区表暂不支持ROW MOVEMENT。 * **NOT NULL** 字段值不允许为NULL。ENABLE用于语法兼容,可省略。 * **NULL** 字段值允许NULL ,这是缺省。 这个子句只是为和非标准SQL数据库兼容。不建议使用。 * **CHECK (condition) \[ NO INHERIT ]** CHECK约束声明一个布尔表达式,每次要插入的新行或者要更新的行的新值必须使表达式结果为真或未知才能成功,否则会抛出一个异常并且不会修改数据库。 声明为字段约束的检查约束应该只引用该字段的数值,而在表约束里出现的表达式可以引用多个字段。 用NO INHERIT标记的约束将不会传递到子表中去。 ENABLE用于语法兼容,可省略。 * **DEFAULT default\_expr** DEFAULT子句给字段指定缺省值。该数值可以是任何不含变量的表达式(不允许使用子查询和对本表中的其他字段的交叉引用)。缺省表达式的数据类型必须和字段类型匹配。 缺省表达式将被用于任何未声明该字段数值的插入操作。如果没有指定缺省值则缺省值为NULL 。 * **GENERATED ALWAYS AS ( generation\_expr ) \[STORED]** 该子句将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,STORED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > > * STORED关键字可省略,与不省略STORED语义相同。 > * 生成表达式不能以任何方式引用当前行以外的其他数据。生成表达式不能引用其他生成列,不能引用系统列。生成表达式不能返回结果集,不能使用子查询,不能使用聚集函数,不能使用窗口函数。生成表达式调用的函数只能是不可变(IMMUTABLE)函数。 > * 不能为生成列指定默认值。 > * 生成列不能作为分区键的一部分。 > * 生成列不能和ON UPDATE约束字句的CASCADE,SET NULL,SET DEFAULT动作同时指定。生成列不能和ON DELETE约束字句的SET NULL,SET DEFAULT动作同时指定。 > * 修改和删除生成列的方法和普通列相同。删除生成列依赖的普通列,生成列被自动删除。不能改变生成列所依赖的列的类型。 > * 生成列不能被直接写入。在INSERT或UPDATE命令中, 不能为生成列指定值, 但是可以指定关键字DEFAULT。 > * 生成列的权限控制和普通列一样。 > * 列存表、内存表MOT不支持生成列。外表中仅postgres\_fdw支持生成列。 * **AUTO\_INCREMENT** 指定列为自动增长列。 详见:[AUTO\_INCREMENT](create_table.md)。 * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** UNIQUE约束表示表里的一个字段或多个字段的组合必须在全表范围内唯一。 对于唯一约束,NULL被认为是互不相等的。 * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** 主键约束声明表中的一个或者多个字段只能包含唯一的非NULL值。 一个表只能声明一个主键。 UNIQUE KEY只能在sql\_compatibility='B'时使用,与UNIQUE语义相同。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 * **DEFERRABLE | NOT DEFERRABLE** 这两个关键字设置该约束是否可推迟。一个不可推迟的约束将在每条命令之后马上检查。可推迟约束可以推迟到事务结尾使用SET CONSTRAINTS命令检查。缺省是NOT DEFERRABLE。目前,UNIQUE约束、主键约束、外键约束可以接受这个子句。所有其他约束类型都是不可推迟的。 * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** 如果约束是可推迟的,则这个子句声明检查约束的缺省时间。 * 如果约束是INITIALLY IMMEDIATE(缺省),则在每条语句执行之后就立即检查它; * 如果约束是INITIALLY DEFERRED ,则只有在事务结尾才检查它。 约束检查的时间可以用SET CONSTRAINTS命令修改。 * **USING INDEX TABLESPACE tablespace\_name** 为UNIQUE或PRIMARY KEY约束相关的索引声明一个表空间。如果没有提供这个子句,这个索引将在default\_tablespace中创建,如果default\_tablespace为空,将使用数据库的缺省表空间。 ## 示例 * 示例1:创建范围分区表tpcds.web\_returns\_p1,含有8个分区,分区键为integer类型。 分区的范围分别为:wr\_returned\_date\_sk< 2450815,2450815<= wr\_returned\_date\_sk< 2451179,2451179<=wr\_returned\_date\_sk< 2451544,2451544 <= wr\_returned\_date\_sk< 2451910,2451910 <= wr\_returned\_date\_sk< 2452275,2452275 <= wr\_returned\_date\_sk< 2452640,2452640 <= wr\_returned\_date\_sk< 2453005,wr\_returned\_date\_sk>=2453005。 ``` --创建表tpcds.web_returns。 openGauss=# CREATE TABLE tpcds.web_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建分区表tpcds.web_returns_p1。 openGauss=# CREATE TABLE tpcds.web_returns_p1 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) ); --从示例数据表导入数据。 openGauss=# INSERT INTO tpcds.web_returns_p1 SELECT * FROM tpcds.web_returns; --删除分区P8。 openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION P8; --增加分区WR_RETURNED_DATE_SK介于2453005和2453105之间。 openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P8 VALUES LESS THAN (2453105); --增加分区WR_RETURNED_DATE_SK介于2453105和MAXVALUE之间。 openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P9 VALUES LESS THAN (MAXVALUE); --删除分区P8。 openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION FOR (2453005); --分区P7重命名为P10。 openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION P7 TO P10; --分区P6重命名为P11。 openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION FOR (2452639) TO P11; --查询分区P10的行数。 openGauss=# SELECT count(*) FROM tpcds.web_returns_p1 PARTITION (P10); count -------- 0 (1 row) --查询分区P1的行数。 openGauss=# SELECT COUNT(*) FROM tpcds.web_returns_p1 PARTITION FOR (2450815); count -------- 0 (1 row) ``` * 示例2:创建范围分区表tpcds.web\_returns\_p2,含有8个分区,分区键类型为integer类型,其中第8个分区上边界为MAXVALUE。 八个分区的范围分别为: wr\_returned\_date\_sk< 2450815,2450815<= wr\_returned\_date\_sk< 2451179,2451179<=wr\_returned\_date\_sk< 2451544,2451544 <= wr\_returned\_date\_sk< 2451910,2451910 <= wr\_returned\_date\_sk< 2452275,2452275 <= wr\_returned\_date\_sk< 2452640,2452640 <= wr\_returned\_date\_sk< 2453005,wr\_returned\_date\_sk>=2453005。 分区表tpcds.web\_returns\_p2的表空间为example1;分区P1到P7没有声明表空间,使用采用分区表tpcds.web\_returns\_p2的表空间example1;指定分区P8的表空间为example2。 假定数据库节点的数据目录/pg\_location/mount1/path1,数据库节点的数据目录/pg\_location/mount2/path2,数据库节点的数据目录/pg\_location/mount3/path3,数据库节点的数据目录/pg\_location/mount4/path4是dwsadmin用户拥有读写权限的空目录。 ``` openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; openGauss=# CREATE TABLE tpcds.web_returns_p2 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) TABLESPACE example1 PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --以like方式创建一个分区表。 openGauss=# CREATE TABLE tpcds.web_returns_p3 (LIKE tpcds.web_returns_p2 INCLUDING PARTITION); --修改分区P1的表空间为example2。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P1 TABLESPACE example2; --修改分区P2的表空间为example3。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P2 TABLESPACE example3; --以2453010为分割点切分P8。 openGauss=# ALTER TABLE tpcds.web_returns_p2 SPLIT PARTITION P8 AT (2453010) INTO ( PARTITION P9, PARTITION P10 ); --将P6,P7合并为一个分区。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MERGE PARTITIONS P6, P7 INTO PARTITION P8; --修改分区表迁移属性。 openGauss=# ALTER TABLE tpcds.web_returns_p2 DISABLE ROW MOVEMENT; --删除表和表空间。 openGauss=# DROP TABLE tpcds.web_returns_p1; openGauss=# DROP TABLE tpcds.web_returns_p2; openGauss=# DROP TABLE tpcds.web_returns_p3; openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; ``` * 示例3:START END语法创建、修改Range分区表。 假定/home/omm/startend\_tbs1,/home/omm/startend\_tbs2,/home/omm/startend\_tbs3,/home/omm/startend\_tbs4是omm用户拥有读写权限的空目录。 ``` -- 创建表空间 openGauss=# CREATE TABLESPACE startend_tbs1 LOCATION '/home/omm/startend_tbs1'; openGauss=# CREATE TABLESPACE startend_tbs2 LOCATION '/home/omm/startend_tbs2'; openGauss=# CREATE TABLESPACE startend_tbs3 LOCATION '/home/omm/startend_tbs3'; openGauss=# CREATE TABLESPACE startend_tbs4 LOCATION '/home/omm/startend_tbs4'; -- 创建临时schema openGauss=# CREATE SCHEMA tpcds; openGauss=# SET CURRENT_SCHEMA TO tpcds; -- 创建分区表,分区键是integer类型 openGauss=# CREATE TABLE tpcds.startend_pt (c1 INT, c2 INT) TABLESPACE startend_tbs1 PARTITION BY RANGE (c2) ( PARTITION p1 START(1) END(1000) EVERY(200) TABLESPACE startend_tbs2, PARTITION p2 END(2000), PARTITION p3 START(2000) END(2500) TABLESPACE startend_tbs3, PARTITION p4 START(2500), PARTITION p5 START(3000) END(5000) EVERY(1000) TABLESPACE startend_tbs4 ) ENABLE ROW MOVEMENT; -- 查看分区表信息 openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs1 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p5_2 | {5000} | startend_tbs4 startend_pt | | startend_tbs1 (12 rows) -- 导入数据,查看分区数据量 openGauss=# INSERT INTO tpcds.startend_pt VALUES (GENERATE_SERIES(0, 4999), GENERATE_SERIES(0, 4999)); openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION FOR (0); count ------- 1 (1 row) openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION (p3); count ------- 500 (1 row) -- 增加分区: [5000, 5300), [5300, 5600), [5600, 5900), [5900, 6000) openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p6 START(5000) END(6000) EVERY(300) TABLESPACE startend_tbs4; -- 增加MAXVALUE分区: p7 openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p7 END(MAXVALUE); -- 重命名分区p7为p8 openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION p7 TO p8; -- 删除分区p8 openGauss=# ALTER TABLE tpcds.startend_pt DROP PARTITION p8; -- 重命名5950所在的分区为:p71 openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION FOR(5950) TO p71; -- 分裂4500所在的分区[4000, 5000) openGauss=# ALTER TABLE tpcds.startend_pt SPLIT PARTITION FOR(4500) INTO(PARTITION q1 START(4000) END(5000) EVERY(250) TABLESPACE startend_tbs3); -- 修改分区p2的表空间为startend_tbs4 openGauss=# ALTER TABLE tpcds.startend_pt MOVE PARTITION p2 TABLESPACE startend_tbs4; -- 查看分区情形 openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs4 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p6_1 | {5300} | startend_tbs4 p6_2 | {5600} | startend_tbs4 p6_3 | {5900} | startend_tbs4 p71 | {6000} | startend_tbs4 q1_1 | {4250} | startend_tbs3 q1_2 | {4500} | startend_tbs3 q1_3 | {4750} | startend_tbs3 q1_4 | {5000} | startend_tbs3 startend_pt | | startend_tbs1 (19 rows) -- 删除表和表空间 openGauss=# DROP SCHEMA tpcds CASCADE; openGauss=# DROP TABLESPACE startend_tbs1; openGauss=# DROP TABLESPACE startend_tbs2; openGauss=# DROP TABLESPACE startend_tbs3; openGauss=# DROP TABLESPACE startend_tbs4; ``` * 示例4:创建间隔分区表sales,初始包含2个分区,分区键为DATE类型。 分区的范围分别为:time\_id < '2019-02-01 00:00:00', '2019-02-01 00:00:00' <= time\_id < '2019-02-02 00:00:00' 。 ``` --创建表sales openGauss=# CREATE TABLE sales (prod_id NUMBER(6), cust_id NUMBER, time_id DATE, channel_id CHAR(1), promo_id NUMBER(6), quantity_sold NUMBER(3), amount_sold NUMBER(10,2) ) PARTITION BY RANGE (time_id) INTERVAL('1 day') ( PARTITION p1 VALUES LESS THAN ('2019-02-01 00:00:00'), PARTITION p2 VALUES LESS THAN ('2019-02-02 00:00:00') ); -- 数据插入分区p1 openGauss=# INSERT INTO sales VALUES(1, 12, '2019-01-10 00:00:00', 'a', 1, 1, 1); -- 数据插入分区p2 openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-01 00:00:00', 'a', 1, 1, 1); -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (2 rows) -- 插入数据没有匹配的分区,新创建一个分区,并将数据插入该分区 -- 新分区的范围为 '2019-02-05 00:00:00' <= time_id < '2019-02-06 00:00:00' openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-05 00:00:00', 'a', 1, 1, 1); -- 插入数据没有匹配的分区,新创建一个分区,并将数据插入该分区 -- 新分区的范围为 '2019-02-03 00:00:00' <= time_id < '2019-02-04 00:00:00' openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-03 00:00:00', 'a', 1, 1, 1); -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- sys_p1 | i | {"2019-02-06 00:00:00"} sys_p2 | i | {"2019-02-04 00:00:00"} p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (4 rows) ``` * 示例5:创建LIST分区表test\_list,初始包含4个分区,分区键为INT类型。4个分区的范围分别为:2000,3000,4000,5000。 ``` --创建表test_list openGauss=# create table test_list (col1 int, col2 int) partition by list(col1) ( partition p1 values (2000), partition p2 values (3000), partition p3 values (4000), partition p4 values (5000) ); -- 数据插入 openGauss=# INSERT INTO test_list VALUES(2000, 2000); INSERT 0 1 openGauss=# INSERT INTO test_list VALUES(3000, 3000); INSERT 0 1 -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} p4 | l | {5000} (4 rows) -- 插入数据没有匹配到分区,报错处理 openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- 添加分区 openGauss=# alter table test_list add partition p5 values (6000); ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p5 | l | {6000} p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (5 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); INSERT 0 1 -- 分区表和普通表交换数据 openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ 2000 | 2000 (1 row) openGauss=# alter table test_list exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 2000 | 2000 (1 row) -- truncate分区 openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ 3000 | 3000 (1 row) openGauss=# alter table test_list truncate partition p2; ALTER TABLE openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ (0 rows) -- 删除分区 openGauss=# alter table test_list drop partition p5; ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (4 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- 删除分区表 openGauss=# drop table test_list; ``` * 示例6:创建HASH分区表test\_hash,初始包含2个分区,分区键为INT类型。 ``` --创建表test_hash openGauss=# create table test_hash (col1 int, col2 int) partition by hash(col1) ( partition p1, partition p2 ); -- 数据插入 openGauss=# INSERT INTO test_hash VALUES(1, 1); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(2, 2); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(3, 3); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(4, 4); INSERT 0 1 -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_hash' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | h | {0} p2 | h | {1} (2 rows) -- 查看数据 openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ 1 | 1 2 | 2 (2 rows) -- 分区表和普通表交换数据 openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# alter table test_hash exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) -- truncate分区 openGauss=# alter table test_hash truncate partition p2; ALTER TABLE openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ (0 rows) -- 删除分区表 openGauss=# drop table test_hash; ``` - 示例7:创建LIST分区表t\_multi\_keys\_list,初始包含5个分区,两个分区键分别为INT类型和VARCHAR类型。 ``` -- 创建表t_multi_keys_list openGauss=# CREATE TABLE t_multi_keys_list (a int, b varchar(4), c int) PARTITION BY LIST (a,b) ( PARTITION p1 VALUES ( (0,NULL) ), PARTITION p2 VALUES ( (0,'1'), (0,'2'), (0,'3'), (1,'1'), (1,'2') ), PARTITION p3 VALUES ( (NULL,'0'), (2,'1') ), PARTITION p4 VALUES ( (3,'2'), (NULL,NULL) ), PARTITION pd VALUES ( DEFAULT ) ); ``` ## 相关链接 [ALTER TABLE PARTITION](alter_table_partition.md),[DROP TABLE](drop_table.md) --- --- url: >- /zh/docs/latest/extension_reference/extension_reference/plugin/dolphin-CREATE-TABLE-PARTITION.md --- # CREATE TABLE PARTITION ## 功能描述 创建分区表。分区表是把逻辑上的一张表根据某种方案分成几张物理块进行存储,这张逻辑上的表称之为分区表,物理块称之为分区。分区表是一张逻辑表,不存储数据,数据实际是存储在分区上的。 常见的分区方案有范围分区(Range Partitioning)、间隔分区(Interval Partitioning)、哈希分区(Hash Partitioning)、列表分区(List Partitioning)、数值分区(Value Partition)等。目前行存表支持范围分区、间隔分区、哈希分区、列表分区,列存表仅支持范围分区。 范围分区是根据表的一列或者多列,将要插入表的记录分为若干个范围,这些范围在不同的分区里没有重叠。为每个范围创建一个分区,用来存储相应的数据。 范围分区的分区策略是指记录插入分区的方式。目前范围分区仅支持范围分区策略。 范围分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。这是最常用的分区策略。 间隔分区是一种特殊的范围分区,相比范围分区,新增间隔值定义,当插入记录找不到匹配的分区时,可以根据间隔值自动创建分区。 间隔分区只支持基于表的一列分区,并且该列只支持TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE数据类型。 间隔分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则根据分区键值和表定义信息自动创建一个分区,然后将记录插入新分区中,新创建的分区数据范围等于间隔值。 哈希分区是根据表的一列,为每个分区指定模数和余数,将要插入表的记录划分到对应的分区中,每个分区所持有的行都需要满足条件:分区键的值除以为其指定的模数将产生为其指定的余数。 哈希分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则返回报错和提示信息。 列表分区是根据表的一列,将要插入表的记录通过每一个分区中出现的键值划分到对应的分区中,这些键值在不同的分区里没有重叠。为每组键值创建一个分区,用来存储相应的数据。 列表分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。 分区可以提供若干好处: * 某些类型的查询性能可以得到极大提升。特别是表中访问率较高的行位于一个单独分区或少数几个分区上的情况下。分区可以减少数据的搜索空间,提高数据访问效率。 * 当查询或更新一个分区的大部分记录时,连续扫描那个分区而不是访问整个表可以获得巨大的性能提升。 * 如果需要大量加载或者删除的记录位于单独的分区上,则可以通过直接读取或删除那个分区以获得巨大的性能提升,同时还可以避免由于大量DELETE导致的VACUUM超载(仅范围分区)。 相比于内核语法,dolphin的rebuild,remove,check,repair,optimize,truncate,analyze,exchange,reorganize都做了B兼容模式下的特色修改。 ## 注意事项 * 唯一约束和主键约束的约束键包含所有分区键将为约束创建LOCAL索引,否则创建GLOBAL索引。 * 目前哈希分区和列表分区仅支持单列构建分区键,暂不支持多列构建分区键。 * 只需要有间隔分区表的INSERT权限,往该表INSERT数据时就可以自动创建分区。 * 对于分区表PARTITION FOR (values)语法,values只能是常量。 * 对于分区表PARTITION FOR (values)语法,values在需要数据类型转换时,建议使用强制类型转换,以防隐式类型转换结果与预期不符。 * 分区数最大值为1048575个,一般情况下业务不可能创建这么多分区,这样会导致内存不足。应参照参数local\_syscache\_threshold的值合理创建分区,分区表使用内存大致为(分区数 \* 3 / 1024)MB。理论上分区占用内存不允许大于local\_syscache\_threshold的值,同时还需要预留部分空间以供其他功能使用。 * 使用table\_indexclause创建分区表上的索引为LOCAL索引,不支持选择GLOBAL索引。 * 支持使用表达式当作分区键,允许分区键使用算术运算符 "+"、"-"、"\*"。 * 只支持部分函数允许在分区键中使用,支持的函数为: ABS()、CEILING()、DATEDIFF()、DAY()、DAYOFMONTH()、DAYOFWEEK()、DAYOFYEAR()、EXTRACT() 、FLOOR()、HOUR()、MICROSECOND()、MINUTE()、MOD()、MONTH()、QUARTER()、SECOND()、TIME\_TO\_SEC()、TO\_DAYS()、TO\_SECONDS()、UNIX\_TIMESTAMP()、WEEKDAY()、YEAR()、YEARWEEK()。 * 表达式用作分区键时,只支持设置一个partition key,且分区为range、hash和list分区,另外暂不支持列存表。 ## 语法格式 ``` CREATE TABLE [ IF NOT EXISTS ] partition_table_name ( [ { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | table_indexclause | LIKE source_table [ like_option [...] ] }[, ... ] ] ) [create_option] PARTITION BY { {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_less_than_item [, ... ] )} | {RANGE (partition_key) [ INTERVAL ('interval_expr') [ STORE IN (tablespace_name [, ... ] ) ] ] ( partition_start_end_item [, ... ] )} | {LIST (partition_key) [ PARTITIONS opt_partitions_num ] (PARTITION partition_name [VALUES [IN] (list_values_clause) ] opt_table_space )} | {HASH (partition_key) [ PARTITIONS opt_partitions_num ] [ (PARTITION partition_name opt_table_space) ]} | {KEY (opt_partition_key) [ PARTITIONS opt_partitions_num ] [ (PARTITION partition_name opt_table_space) ]} } [ { ENABLE | DISABLE } ROW MOVEMENT ]; [create_option] 其中create_option为: [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ COMPRESSION [=] compression_arg ] [ ENGINE [=] engine_name ] 除了WITH选项外允许输入多次同一种create_option,以最后一次的输入为准。 ``` 其中参数part\_option为: ``` part_option:{ COMMENT [=] 'string' | [STORAGE] ENGINE [=] engine_name } ``` * 列约束column\_constraint: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_e xpr | GENERATED ALWAYS AS ( generation_expr ) STORED | UNIQUE index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 表约束table\_constraint: ``` [ CONSTRAINT constraint_name ] { CHECK ( expression ) | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters | FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] ``` * 创建表上索引table\_indexclause: ``` {INDEX | KEY} [index_name] [index_type] (key_part,...)[index_option]... ``` * 其中参数index\_type为: ``` USING {BTREE | HASH | GIN | GIST | PSORT | UBTREE} ``` * 其中参数key\_part为: ``` {col_name [ ( length ) ] | (expr)} [ASC | DESC] ``` * 其中`col_name ( length )`为前缀键,column\_name为前缀键的字段名,length为前缀长度。前缀键将取指定字段数据的前缀作为索引键值,可以减少索引占用的存储空间。含有前缀键字段的过滤条件和连接条件可以使用索引。 > \[!NOTE]说明 > > * 前缀键支持的索引方法:Btree、UBtree。 > * 前缀键的字段的数据类型必须是二进制类型或字符类型(不包括特殊字符类型)。 > * 前缀长度必须是不超过2676的正整数,并且不能超过字段的最大长度。对于二进制类型,前缀长度以字节数为单位。对于非二进制字符类型,前缀长度以字符数为单位。键值的实际长度受内部页面限制,若字段中含有多字节字符、或者一个索引上有多个键,索引行长度可能会超限,导致报错,设定较长的前缀长度时请考虑此情况。 * 其中参数index\_option为: ``` index_option:{ COMMENT 'string' | index_type } ``` COMMENT、index\_type 的顺序和数量任意,但相同字段仅最后一个值生效。 * like选项like\_option: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS| ALL } ``` * 索引存储参数index\_parameters: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * partition\_less\_than\_item: ``` PARTITION partition_name VALUES LESS THAN ( { partition_value | MAXVALUE } ) | MAXVALUE [TABLESPACE tablespace_name] [part_option [ ...]] ``` * partition\_start\_end\_item: ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE}) | MAXVALUE} | {START(partition_value)} | {END ({partition_value | MAXVALUE}) | MAXVALUE} } [TABLESPACE tablespace_name] [part_option [ ...]] ``` ## 参数说明 * **IF NOT EXISTS** 如果已经存在相同名称的表,不会抛出一个错误,而会发出一个通知,告知表关系已存在。 * **partition\_table\_name** 分区表的名称。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新表中要创建的字段名。 取值范围:字符串,要符合标识符的命名规范。 * **data\_type** 字段的数据类型。 * **COLLATE collation** COLLATE子句指定列的排序规则(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 * **CONSTRAINT constraint\_name** 列约束或表约束的名称。可选的约束子句用于声明约束,新行或者更新的行必须满足这些约束才能成功插入或更新。 定义约束有两种方法: * 列约束:作为一个列定义的一部分,仅影响该列。 * 表约束:不和某个列绑在一起,可以作用于多个列。 * **LIKE source\_table \[ like\_option ... ]** LIKE子句声明一个表,新表自动从这个表里面继承所有字段名及其数据类型和非空约束。 和INHERITS不同,新表与原来的表之间在创建动作完毕之后是完全无关的。在源表做的任何修改都不会传播到新表中,并且也不可能在扫描源表的时候包含新表的数据。 * 字段缺省表达式只有在声明了INCLUDING DEFAULTS之后才会包含进来。缺省是不包含缺省表达式的,即新表中所有字段的缺省值都是NULL。 * 如果指定了INCLUDING GENERATED,则源表列的生成表达式会复制到新表中。默认不复制生成表达式。 * 非空约束将总是复制到新表中,CHECK约束则仅在指定了INCLUDING CONSTRAINTS的时候才复制,而其他类型的约束则永远也不会被复制。此规则同时适用于表约束和列约束。 * 和INHERITS不同,被复制的列和约束并不使用相同的名称进行融合。如果明确的指定了相同的名称或者在另外一个LIKE子句中,将会报错。 * 如果指定了INCLUDING INDEXES,则源表上的索引也将在新表上创建,默认不建立索引。 * 如果指定了INCLUDING STORAGE,则拷贝列的STORAGE设置也将被拷贝,默认情况下不包含STORAGE设置。 * 如果指定了INCLUDING COMMENTS,则源表列、约束和索引的注释也会被拷贝过来。默认情况下,不拷贝源表的注释。 * 如果指定了INCLUDING RELOPTIONS,则源表的存储参数(即源表的WITH子句)也将拷贝至新表。默认情况下,不拷贝源表的存储参数。 * INCLUDING ALL包含了INCLUDING DEFAULTS、INCLUDING CONSTRAINTS、INCLUDING INDEXES、INCLUDING STORAGE、INCLUDING COMMENTS、INCLUDING PARTITION和INCLUDING RELOPTIONS的内容。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。参数的详细描述如下所示: * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数对于列存表没有意义。 取值范围:10~100 * ORIENTATION 决定了表的数据的存储方式。 取值范围: * COLUMN:表的数据将以列式存储。 * ROW(缺省值):表的数据将以行式存储。 > \[!TIP]须知 > orientation不支持修改。 * STORAGE\_TYPE 指定存储引擎类型,该参数设置成功后就不再支持修改。 取值范围: * USTORE,表示表支持Inplace-Update存储引擎。特别需要注意,使用USTORE表,必须要开启track\_counts和track\_activities参数,否则会引起空间膨胀。 * ASTORE,表示表支持Append-Only存储引擎。 * 默认值,不指定表时,默认是Append-Only存储。 * COMPRESSION * 列存表的有效值为LOW/MIDDLE/HIGH/YES/NO,压缩级别依次升高,默认值为LOW。 * 行存表不支持压缩。 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000,默认60000。 * PARTIAL\_CLUSTER\_ROWS 指定了在数据加载过程中进行将局部聚簇存储的记录数目。该参数只对列存表有效。 取值范围:大于等于MAX\_BATCHROW,建议取值为MAX\_BATCHROW的整数倍数。 * DELTAROW\_THRESHOLD 预留参数。该参数只对列存表有效。 取值范围:0~9999 * segment 使用段页式的方式存储。本参数仅支持行存表。不支持列存表、临时表、unlog表。不支持Ustore存储引擎。 取值范围:on/off 默认值:off * **COMPRESS / NOCOMPRESS** 创建一个新表时,需要在创建表语句中指定关键字COMPRESS,这样,当对该表进行批量插入时就会触发压缩特性。该特性会在页范围内扫描所有元组数据,生成字典、压缩元组数据并进行存储。指定关键字NOCOMPRESS则不对表进行压缩。行存表不支持压缩。该参数已废弃,列存表请使用COMPRESSION修改压缩等级。 缺省值为NOCOMPRESS,即不对元组数据进行压缩。 * **TABLESPACE tablespace\_name** 指定新表将要在tablespace\_name表空间内创建。如果没有声明,将使用默认表空间。 * **PARTITION BY RANGE(partition\_key)** 创建范围分区。partition\_key为分区键的名称。 (1)对于从句是VALUES LESS THAN的语法格式: > \[!TIP]须知 > 对于从句是VALUE LESS THAN的语法格式,范围分区策略的分区键最多支持4列。 该情形下,分区键支持的数据类型为:TINYINT\[UNSIGNED]、SMALLINT\[UNSIGNED]、INTEGER\[UNSIGNED]、BIGINT\[UNSIGNED]、DECIMAL、NUMERIC、REAL、DOUBLE PRECISION、CHARACTER VARYING(n)、VARCHAR(n)、CHARACTER(n)、CHAR(n)、CHARACTER、CHAR、TEXT、NVARCHAR、NVARCHAR2、NAME、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 (2)对于从句是START END的语法格式: > \[!TIP]须知 > 对于从句是START END的语法格式,范围分区策略的分区键仅支持1列。 该情形下,分区键支持的数据类型为:TINYINT\[UNSIGNED]、SMALLINT\[UNSIGNED]、INTEGER\[UNSIGNED]、BIGINT\[UNSIGNED]、DECIMAL、NUMERIC、REAL、DOUBLE PRECISION、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 (3)对于指定了INTERVAL子句的语法格式: > \[!TIP]须知 > 对于指定了INTERVAL子句的语法格式,范围分区策略的分区键仅支持1列。 该情形下,分区键支持的数据类型为:TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 * **PARTITION partition\_name VALUES LESS THAN ( { partition\_value | MAXVALUE } ) | MAXVALUE** 指定各分区的信息。partition\_name为范围分区的名称。partition\_value为范围分区的上边界,取值依赖于partition\_key的类型。MAXVALUE表示分区的上边界,它通常用于设置最后一个范围分区的上边界。 > \[!TIP]须知 > > * 每个分区都需要指定一个上边界。 > * 在加载dolphin插件的B兼容库下,分区键为有符号整型时,分区上边界的类型为int8;分区键为无符号整型时,分区上边界的类型为uint8,因此允许设置上边界的值超过分区键的最大值。 > * 分区列表是按照分区上边界升序排列的,值较小的分区位于值较大的分区之前。 * **PARTITION partition\_name {START (partition\_value) END (partition\_value) EVERY (interval\_value)}** | **{START (partition\_value) END (partition\_value|MAXVALUE) | MAXVALUE**} | {START(partition\_value)\*\*} | **{END (partition\_value | MAXVALUE) | MAXVALUE**} 指定各分区的信息,各参数意义如下: * partition\_name:范围分区的名称或名称前缀,除以下情形外(假定其中的partition\_name是p1),均为分区的名称。 * 若该定义是START+END+EVERY从句,则语义上定义的分区的名称依次为p1\_1, p1\_2, ...。例如对于定义“PARTITION p1 START(1) END(4) EVERY(1)”,则生成的分区是:\[1, 2), \[2, 3) 和 \[3, 4),名称依次为p1\_1, p1\_2和p1\_3,即此处的p1是名称前缀。 * 若该定义是第一个分区定义,且该定义有START值,则范围(MINVALUE, START)将自动作为第一个实际分区,其名称为p1\_0,然后该定义语义描述的分区名称依次为p1\_1, p1\_2, ...。例如对于完整定义“PARTITION p1 START(1), PARTITION p2 START(2)”,则生成的分区是:(MINVALUE, 1), \[1, 2) 和 \[2, MAXVALUE),其名称依次为p1\_0, p1\_1和p2,即此处p1是名称前缀,p2是分区名称。这里MINVALUE表示最小值。 * partition\_value:范围分区的端点值(起始或终点),取值依赖于partition\_key的类型,不可是MAXVALUE。 * interval\_value:对\[START,END) 表示的范围进行切分,interval\_value是指定切分后每个分区的宽度,不可是MAXVALUE;如果(END-START)值不能整除以EVERY值,则仅最后一个分区的宽度小于EVERY值。 * MAXVALUE:表示最大值,它通常用于设置最后一个范围分区的上边界。 > \[!TIP]须知 > > 1. 在创建分区表若第一个分区定义含START值,则范围(MINVALUE,START)将自动作为实际的第一个分区。 > 2. START END语法需要遵循以下限制: > * 每个partition\_start\_end\_item中的START值(如果有的话,下同)必须小于其END值。 > * 相邻的两个partition\_start\_end\_item,第一个的END值必须等于第二个的START值; > * 每个partition\_start\_end\_item中的EVERY值必须是正向递增的,且必须小于(END-START)值; > * 每个分区包含起始值,不包含终点值,即形如:\[起始值,终点值),起始值是MINVALUE时则不包含; > * 一个partition\_start\_end\_item创建的每个分区所属的TABLESPACE一样; > * partition\_name作为分区名称前缀时,其长度不要超过57字节,超过时自动截断; > * 在创建、修改分区表时请注意分区表的分区总数不可超过最大限制(1048575); > 3. 在创建分区表时START END与LESS THAN语法不可混合使用。 > 4. 即使创建分区表时使用START END语法,备份(gs\_dump)出的SQL语句也是VALUES LESS THAN语法格式。 * **INTERVAL ('interval\_expr') \[ STORE IN (tablespace\_name \[, ... ] ) ]** 间隔分区定义信息。 * interval\_expr:自动创建分区的间隔,例如:1 day、1 month。 * STORE IN (tablespace\_name \[, ... ] ):指定存放自动创建分区的表空间列表,如果有指定,则自动创建的分区从表空间列表中循环选择使用,否则使用分区表默认的表空间。 > \[!TIP]须知 > 列存表不支持间隔分区。 * **PARTITION BY LIST(partition\_key)** 创建列表分区。partition\_key为分区键的名称。 * 对于partition\_key,列表分区策略的分区键最大支持16列。 * 对于从句是VALUES (list\_values\_clause)的语法格式,list\_values\_clause中包含了对应分区存在的键值,推荐每个分区的键值数量不超过64个。 分区键支持的数据类型为:INT1\[UNSIGNED]、INT2\[UNSIGNED]、INT4\[UNSIGNED]、INT8\[UNSIGNED]、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过 1048575 个。 * **PARTITION BY HASH(partition\_key)** 创建哈希分区。partition\_key为分区键的名称。 对于partition\_key,哈希分区策略的分区键仅支持1列。 分区键支持的数据类型为:INT1\[UNSIGNED]、INT2\[UNSIGNED]、INT4\[UNSIGNED]、INT8\[UNSIGNED]、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、TEXT、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过1048575 个。 * **PARTITION BY KEY(opt\_partition\_key)** 创建键分区。opt\_partition\_key是可选的,其表示分区键的名称。 对于opt\_partition\_key,当用户明确提供了分区键时,键分区策略的分区键仅支持1列。当用户没有提供分区键时,将使用表的主键为分区键。目前组合键是不支持的。 分区键支持的数据类型为:INT1\[UNSIGNED]、INT2\[UNSIGNED]、INT4\[UNSIGNED]、INT8\[UNSIGNED]、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、TEXT、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过1048575 个。 * **{ ENABLE | DISABLE } ROW MOVEMENT** 行迁移开关。 如果进行UPDATE操作时,更新了元组在分区键上的值,造成了该元组所在分区发生变化,就会根据该开关给出报错信息,或者进行元组在分区间的转移。 取值范围: * ENABLE(缺省值):行迁移开关打开。 * DISABLE:行迁移开关关闭。 > \[!TIP]须知 > 列表/哈希分区表暂不支持ROW MOVEMENT。 * **NOT NULL** 字段值不允许为NULL。ENABLE用于语法兼容,可省略。 * **NULL** 字段值允许NULL ,这是缺省。 这个子句只是为和非标准SQL数据库兼容。不建议使用。 * **CHECK (condition) \[ NO INHERIT ]** CHECK约束声明一个布尔表达式,每次要插入的新行或者要更新的行的新值必须使表达式结果为真或未知才能成功,否则会抛出一个异常并且不会修改数据库。 声明为字段约束的检查约束应该只引用该字段的数值,而在表约束里出现的表达式可以引用多个字段。 用NO INHERIT标记的约束将不会传递到子表中去。 ENABLE用于语法兼容,可省略。 * **DEFAULT default\_expr** DEFAULT子句给字段指定缺省值。该数值可以是任何不含变量的表达式(不允许使用子查询和对本表中的其他字段的交叉引用)。缺省表达式的数据类型必须和字段类型匹配。 缺省表达式将被用于任何未声明该字段数值的插入操作。如果没有指定缺省值则缺省值为NULL 。 * GENERATED ALWAYS AS ( generation\_expr ) STORED 该子句将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,STORED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > > * 生成表达式不能以任何方式引用当前行以外的其他数据。生成表达式不能引用其他生成列,不能引用系统列。生成表达式不能返回结果集,不能使用子查询,不能使用聚集函数,不能使用窗口函数。生成表达式调用的函数只能是不可变(IMMUTABLE)函数。 > > * 不能为生成列指定默认值。 > > * 生成列不能作为分区键的一部分。 > > * 生成列不能和ON UPDATE约束字句的CASCADE,SET NULL,SET DEFAULT动作同时指定。生成列不能和ON DELETE约束字句的SET NULL、SET DEFAULT动作同时指定。 > > * 修改和删除生成列的方法和普通列相同。删除生成列依赖的普通列,生成列被自动删除。不能改变生成列所依赖的列的类型。 > > * 生成列不能被直接写入。在INSERT或UPDATE命令中, 不能为生成列指定值, 但是可以指定关键字DEFAULT。 > > * 生成列的权限控制和普通列一样。 > > * 列存表、内存表MOT不支持生成列。外表中仅postgres\_fdw支持生成列。 * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** UNIQUE约束表示表里的一个字段或多个字段的组合必须在全表范围内唯一。 对于唯一约束,NULL被认为是互不相等的。 * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** 主键约束声明表中的一个或者多个字段只能包含唯一的非NULL值。 一个表只能声明一个主键。 * **DEFERRABLE | NOT DEFERRABLE** 这两个关键字设置该约束是否可推迟。一个不可推迟的约束将在每条命令之后马上检查。可推迟约束可以推迟到事务结尾使用SET CONSTRAINTS命令检查。缺省是NOT DEFERRABLE。目前,UNIQUE约束、主键约束、外键约束可以接受这个子句。所有其他约束类型都是不可推迟的。 * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** 如果约束是可推迟的,则这个子句声明检查约束的缺省时间。 * 如果约束是INITIALLY IMMEDIATE(缺省),则在每条语句执行之后就立即检查它; * 如果约束是INITIALLY DEFERRED ,则只有在事务结尾才检查它。 约束检查的时间可以用SET CONSTRAINTS命令修改。 * **USING INDEX TABLESPACE tablespace\_name** 为UNIQUE或PRIMARY KEY约束相关的索引声明一个表空间。如果没有提供这个子句,这个索引将在default\_tablespace中创建,如果default\_tablespace为空,将使用数据库的缺省表空间。 ## 示例 * 示例1:创建范围分区表tpcds.web\_returns\_p1,含有8个分区,分区键为integer类型。 分区的范围分别为:wr\_returned\_date\_sk< 2450815、2450815<= wr\_returned\_date\_sk< 2451179、2451179<=wr\_returned\_date\_sk< 2451544、2451544 <= wr\_returned\_date\_sk< 2451910、2451910 <= wr\_returned\_date\_sk< 2452275、2452275 <= wr\_returned\_date\_sk< 2452640、2452640 <= wr\_returned\_date\_sk< 2453005、wr\_returned\_date\_sk>=2453005。 ``` --创建表tpcds.web_returns。 openGauss=# CREATE TABLE tpcds.web_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建分区表tpcds.web_returns_p1。 openGauss=# CREATE TABLE tpcds.web_returns_p1 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) ); --从示例数据表导入数据。 openGauss=# INSERT INTO tpcds.web_returns_p1 SELECT * FROM tpcds.web_returns; --删除分区P8。 openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION P8; --增加分区WR_RETURNED_DATE_SK介于2453005和2453105之间。 openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P8 VALUES LESS THAN (2453105); --增加分区WR_RETURNED_DATE_SK介于2453105和MAXVALUE之间。 openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P9 VALUES LESS THAN (MAXVALUE); --删除分区P8。 openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION FOR (2453005); --分区P7重命名为P10。 openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION P7 TO P10; --分区P6重命名为P11。 openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION FOR (2452639) TO P11; --查询分区P10的行数。 openGauss=# SELECT count(*) FROM tpcds.web_returns_p1 PARTITION (P10); count -------- 0 (1 row) --查询分区P1的行数。 openGauss=# SELECT COUNT(*) FROM tpcds.web_returns_p1 PARTITION FOR (2450815); count -------- 0 (1 row) ``` * 示例2:创建范围分区表tpcds.web\_returns\_p2,含有8个分区,分区键类型为integer类型,其中第8个分区上边界为MAXVALUE。 八个分区的范围分别为: wr\_returned\_date\_sk< 2450815、2450815<= wr\_returned\_date\_sk< 2451179、2451179<=wr\_returned\_date\_sk< 2451544、2451544 <= wr\_returned\_date\_sk< 2451910、2451910 <= wr\_returned\_date\_sk< 2452275、2452275 <= wr\_returned\_date\_sk< 2452640、2452640 <= wr\_returned\_date\_sk< 2453005、wr\_returned\_date\_sk>=2453005。 分区表tpcds.web\_returns\_p2的表空间为example1;分区P1到P7没有声明表空间,使用采用分区表tpcds.web\_returns\_p2的表空间example1;指定分区P8的表空间为example2。 假定数据库节点的数据目录/pg\_location/mount1/path1,数据库节点的数据目录/pg\_location/mount2/path2,数据库节点的数据目录/pg\_location/mount3/path3,数据库节点的数据目录/pg\_location/mount4/path4是dwsadmin用户拥有读写权限的空目录。 ``` openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; openGauss=# CREATE TABLE tpcds.web_returns_p2 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) TABLESPACE example1 PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --以like方式创建一个分区表。 openGauss=# CREATE TABLE tpcds.web_returns_p3 (LIKE tpcds.web_returns_p2 INCLUDING PARTITION); --修改分区P1的表空间为example2。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P1 TABLESPACE example2; --修改分区P2的表空间为example3。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P2 TABLESPACE example3; --以2453010为分割点切分P8。 openGauss=# ALTER TABLE tpcds.web_returns_p2 SPLIT PARTITION P8 AT (2453010) INTO ( PARTITION P9, PARTITION P10 ); --将P6,P7合并为一个分区。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MERGE PARTITIONS P6, P7 INTO PARTITION P8; --修改分区表迁移属性。 openGauss=# ALTER TABLE tpcds.web_returns_p2 DISABLE ROW MOVEMENT; --删除表和表空间。 openGauss=# DROP TABLE tpcds.web_returns_p1; openGauss=# DROP TABLE tpcds.web_returns_p2; openGauss=# DROP TABLE tpcds.web_returns_p3; openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; ``` * 示例3:START END语法创建、修改Range分区表。 假定/home/omm/startend\_tbs1、/home/omm/startend\_tbs2、/home/omm/startend\_tbs3、/home/omm/startend\_tbs4是omm用户拥有读写权限的空目录。 ``` -- 创建表空间 openGauss=# CREATE TABLESPACE startend_tbs1 LOCATION '/home/omm/startend_tbs1'; openGauss=# CREATE TABLESPACE startend_tbs2 LOCATION '/home/omm/startend_tbs2'; openGauss=# CREATE TABLESPACE startend_tbs3 LOCATION '/home/omm/startend_tbs3'; openGauss=# CREATE TABLESPACE startend_tbs4 LOCATION '/home/omm/startend_tbs4'; -- 创建临时schema openGauss=# CREATE SCHEMA tpcds; openGauss=# SET CURRENT_SCHEMA TO tpcds; -- 创建分区表,分区键是integer类型 openGauss=# CREATE TABLE tpcds.startend_pt (c1 INT, c2 INT) TABLESPACE startend_tbs1 PARTITION BY RANGE (c2) ( PARTITION p1 START(1) END(1000) EVERY(200) TABLESPACE startend_tbs2, PARTITION p2 END(2000), PARTITION p3 START(2000) END(2500) TABLESPACE startend_tbs3, PARTITION p4 START(2500), PARTITION p5 START(3000) END(5000) EVERY(1000) TABLESPACE startend_tbs4 ) ENABLE ROW MOVEMENT; -- 查看分区表信息 openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs1 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p5_2 | {5000} | startend_tbs4 startend_pt | | startend_tbs1 (12 rows) -- 导入数据,查看分区数据量 openGauss=# INSERT INTO tpcds.startend_pt VALUES (GENERATE_SERIES(0, 4999), GENERATE_SERIES(0, 4999)); openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION FOR (0); count ------- 1 (1 row) openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION (p3); count ------- 500 (1 row) -- 增加分区: [5000, 5300), [5300, 5600), [5600, 5900), [5900, 6000) openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p6 START(5000) END(6000) EVERY(300) TABLESPACE startend_tbs4; -- 增加MAXVALUE分区: p7 openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p7 END(MAXVALUE); -- 重命名分区p7为p8 openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION p7 TO p8; -- 删除分区p8 openGauss=# ALTER TABLE tpcds.startend_pt DROP PARTITION p8; -- 重命名5950所在的分区为:p71 openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION FOR(5950) TO p71; -- 分裂4500所在的分区[4000, 5000) openGauss=# ALTER TABLE tpcds.startend_pt SPLIT PARTITION FOR(4500) INTO(PARTITION q1 START(4000) END(5000) EVERY(250) TABLESPACE startend_tbs3); -- 修改分区p2的表空间为startend_tbs4 openGauss=# ALTER TABLE tpcds.startend_pt MOVE PARTITION p2 TABLESPACE startend_tbs4; -- 查看分区情形 openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs4 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p6_1 | {5300} | startend_tbs4 p6_2 | {5600} | startend_tbs4 p6_3 | {5900} | startend_tbs4 p71 | {6000} | startend_tbs4 q1_1 | {4250} | startend_tbs3 q1_2 | {4500} | startend_tbs3 q1_3 | {4750} | startend_tbs3 q1_4 | {5000} | startend_tbs3 startend_pt | | startend_tbs1 (19 rows) -- 删除表和表空间 openGauss=# DROP SCHEMA tpcds CASCADE; openGauss=# DROP TABLESPACE startend_tbs1; openGauss=# DROP TABLESPACE startend_tbs2; openGauss=# DROP TABLESPACE startend_tbs3; openGauss=# DROP TABLESPACE startend_tbs4; ``` * 示例4:创建间隔分区表sales,初始包含2个分区,分区键为DATE类型。 分区的范围分别为:time\_id < '2019-02-01 00:00:00'、 '2019-02-01 00:00:00' <= time\_id < '2019-02-02 00:00:00' 。 ``` --创建表sales openGauss=# CREATE TABLE sales (prod_id NUMBER(6), cust_id NUMBER, time_id DATE, channel_id CHAR(1), promo_id NUMBER(6), quantity_sold NUMBER(3), amount_sold NUMBER(10,2) ) PARTITION BY RANGE (time_id) INTERVAL('1 day') ( PARTITION p1 VALUES LESS THAN ('2019-02-01 00:00:00'), PARTITION p2 VALUES LESS THAN ('2019-02-02 00:00:00') ); -- 数据插入分区p1 openGauss=# INSERT INTO sales VALUES(1, 12, '2019-01-10 00:00:00', 'a', 1, 1, 1); -- 数据插入分区p2 openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-01 00:00:00', 'a', 1, 1, 1); -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (2 rows) -- 插入数据没有匹配的分区,新创建一个分区,并将数据插入该分区 -- 新分区的范围为 '2019-02-05 00:00:00' <= time_id < '2019-02-06 00:00:00' openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-05 00:00:00', 'a', 1, 1, 1); -- 插入数据没有匹配的分区,新创建一个分区,并将数据插入该分区 -- 新分区的范围为 '2019-02-03 00:00:00' <= time_id < '2019-02-04 00:00:00' openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-03 00:00:00', 'a', 1, 1, 1); -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- sys_p1 | i | {"2019-02-06 00:00:00"} sys_p2 | i | {"2019-02-04 00:00:00"} p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (4 rows) ``` * 示例5:创建LIST分区表test\_list,初始包含4个分区,分区键为INT类型。4个分区的范围分别为:2000、3000、4000、5000。 ``` --创建表test_list openGauss=# create table test_list (col1 int, col2 int) partition by list(col1) ( partition p1 values (2000), partition p2 values (3000), partition p3 values (4000), partition p4 values (5000) ); -- 数据插入 openGauss=# INSERT INTO test_list VALUES(2000, 2000); INSERT 0 1 openGauss=# INSERT INTO test_list VALUES(3000, 3000); INSERT 0 1 -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} p4 | l | {5000} (4 rows) -- 插入数据没有匹配到分区,报错处理 openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- 添加分区 openGauss=# alter table test_list add partition p5 values (6000); ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p5 | l | {6000} p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (5 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); INSERT 0 1 -- 分区表和普通表交换数据 openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ 2000 | 2000 (1 row) openGauss=# alter table test_list exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 2000 | 2000 (1 row) -- truncate分区 openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ 3000 | 3000 (1 row) openGauss=# alter table test_list truncate partition p2; ALTER TABLE openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ (0 rows) -- 删除分区 openGauss=# alter table test_list drop partition p5; ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (4 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- 删除分区表 openGauss=# drop table test_list; ``` * 示例6:创建HASH分区表test\_hash,初始包含2个分区,分区键为INT类型。 ``` --创建表test_hash openGauss=# create table test_hash (col1 int, col2 int) partition by hash(col1) ( partition p1, partition p2 ); -- 数据插入 openGauss=# INSERT INTO test_hash VALUES(1, 1); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(2, 2); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(3, 3); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(4, 4); INSERT 0 1 -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_hash' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | h | {0} p2 | h | {1} (2 rows) -- 查看数据 openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ 1 | 1 2 | 2 (2 rows) -- 分区表和普通表交换数据 openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# alter table test_hash exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) -- truncate分区 openGauss=# alter table test_hash truncate partition p2; ALTER TABLE openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ (0 rows) -- 删除分区表 openGauss=# drop table test_hash; --rebuild,remove,check,repair,optimize语法示例 --创建分区表test_part CREATE TABLE IF NOT EXISTS test_part ( a int primary key not null default 5, b int, c int, d int ) PARTITION BY RANGE(a) ( PARTITION p0 VALUES LESS THAN (100000), PARTITION p1 VALUES LESS THAN (200000), PARTITION p2 VALUES LESS THAN (300000) ); create unique index idx_c on test_part (c); create index idx_b on test_part using btree(b) local; alter table test_part add constraint uidx_d unique(d); alter table test_part add constraint uidx_c unique using index idx_c; --向分区表插入数据 insert into test_part (with RECURSIVE t_r(i,j,k,m) as(values(0,1,2,3) union all select i+1,j+2,k+3,m+4 from t_r where i < 250000) select * from t_r); --检查分区表系统信息 select relname from pg_partition where (parentid in (select oid from pg_class where relname = 'test_part')) and parttype = 'p' and oid != relfilenode order by relname; --通过索引从分区表select数据 explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < d and d < 100000) or (219990 < d and d < 220000)); select * from test_part where ((99990 < b and b < 100000) or (219990 < b and b < 220000)); --测试rebuild分区表语法 ALTER TABLE test_part REBUILD PARTITION p0, p1; --检查分区表系统信息和真实数据 select relname from pg_partition where (parentid in (select oid from pg_class where relname = 'test_part')) and parttype = 'p' and oid != relfilenode order by relname; explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < d and d < 100000) or (219990 < d and d < 220000)); select * from test_part where ((99990 < b and b < 100000) or (219990 < b and b < 220000)); --测试rebuild partition all分区表语法 ALTER TABLE test_part REBUILD PARTITION all; --检查分区表系统信息和真实数据 select relname from pg_partition where (parentid in (select oid from pg_class where relname = 'test_part')) and parttype = 'p' and oid != relfilenode order by relname; explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < d and d < 100000) or (219990 < d and d < 220000)); select * from test_part where ((99990 < b and b < 100000) or (219990 < b and b < 220000)); --测试 repair check optimize 分区表语法 ALTER TABLE test_part repair PARTITION p0,p1; ALTER TABLE test_part check PARTITION p0,p1; ALTER TABLE test_part optimize PARTITION p0,p1; ALTER TABLE test_part repair PARTITION all; ALTER TABLE test_part check PARTITION all; ALTER TABLE test_part optimize PARTITION all; --测试 remove partitioning 语法 select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part') order by relname; select parttype,relname from pg_class where relname = 'test_part' and relfilenode != oid; ALTER TABLE test_part remove PARTITIONING; --检查分区表移除分区信息后的系统信息和真实数据 explain select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select * from test_part where ((99990 < c and c < 100000) or (219990 < c and c < 220000)); select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part') order by relname; select parttype,relname from pg_class where relname = 'test_part' and relfilenode != oid; --truncate,analyze,exchange语法示例 CREATE TABLE IF NOT EXISTS test_part1 ( a int, b int ) PARTITION BY RANGE(a) ( PARTITION p0 VALUES LESS THAN (100), PARTITION p1 VALUES LESS THAN (200), PARTITION p2 VALUES LESS THAN (300) ); create table test_no_part1(a int, b int); insert into test_part1 values(99,1),(199,1),(299,1); select * from test_part1; --truncate partition语法 ALTER TABLE test_part1 truncate PARTITION p0, p1; select * from test_part1; insert into test_part1 (with RECURSIVE t_r(i,j) as(values(0,1) union all select i+1,j+2 from t_r where i < 20) select * from t_r); select * from test_part1; ALTER TABLE test_part1 truncate PARTITION all; select * from test_part1; --测试opengauss truncate partition语法 insert into test_part1 values(99,1),(199,1); select * from test_part1; ALTER TABLE test_part1 truncate PARTITION p0, truncate PARTITION p1; select * from test_part1; --exchange partition语法 insert into test_part1 values(99,1),(199,1),(299,1); alter table test_part1 exchange partition p2 with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; alter table test_part1 exchange partition p2 with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; --测试opengauss exchange partition语法 alter table test_part1 exchange partition (p2) with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; alter table test_part1 exchange partition (p2) with table test_no_part1 without validation; select * from test_part1; select * from test_no_part1; --analyze partition语法 alter table test_part1 analyze partition p0,p1; alter table test_part1 analyze partition all; --测试opengauss analyze partition语法 analyze test_part1 partition (p1); --add, drop语法示例 CREATE TABLE IF NOT EXISTS test_part2 ( a int, b int ) PARTITION BY RANGE(a) ( PARTITION p0 VALUES LESS THAN (100), PARTITION p1 VALUES LESS THAN (200), PARTITION p2 VALUES LESS THAN (300), PARTITION p3 VALUES LESS THAN (400) ); CREATE TABLE IF NOT EXISTS test_subpart2 ( a int, b int ) PARTITION BY RANGE(a) SUBPARTITION BY RANGE(b) ( PARTITION p0 VALUES LESS THAN (100) ( SUBPARTITION p0_0 VALUES LESS THAN (100), SUBPARTITION p0_1 VALUES LESS THAN (200), SUBPARTITION p0_2 VALUES LESS THAN (300) ), PARTITION p1 VALUES LESS THAN (200) ( SUBPARTITION p1_0 VALUES LESS THAN (100), SUBPARTITION p1_1 VALUES LESS THAN (200), SUBPARTITION p1_2 VALUES LESS THAN (300) ), PARTITION p2 VALUES LESS THAN (300) ( SUBPARTITION p2_0 VALUES LESS THAN (100), SUBPARTITION p2_1 VALUES LESS THAN (200), SUBPARTITION p2_2 VALUES LESS THAN (300) ), PARTITION p3 VALUES LESS THAN (400) ( SUBPARTITION p3_0 VALUES LESS THAN (100), SUBPARTITION p3_1 VALUES LESS THAN (200), SUBPARTITION p3_2 VALUES LESS THAN (300) ) ); --test b_compatibility drop and add partition syntax select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 DROP PARTITION p3; select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 add PARTITION (PARTITION p3 VALUES LESS THAN (400),PARTITION p4 VALUES LESS THAN (500),PARTITION p5 VALUES LESS THAN (600)); select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 add PARTITION (PARTITION p6 VALUES LESS THAN (700),PARTITION p7 VALUES LESS THAN (800)); ALTER TABLE test_part2 DROP PARTITION p4,p5,p6; select relname, boundaries from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_part2'); ALTER TABLE test_part2 add PARTITION (PARTITION p4 VALUES LESS THAN (500)); select relname, boundaries from pg_partition where parentid in (select oid from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_subpart2')); ALTER TABLE test_subpart2 DROP SUBPARTITION p0_0; ALTER TABLE test_subpart2 DROP SUBPARTITION p0_2, p1_0, p1_2; select relname, boundaries from pg_partition where parentid in (select oid from pg_partition where parentid in (select parentid from pg_partition where relname = 'test_subpart2')); --reorganize分区语法示例 CREATE TABLE test_range_subpart ( a INT4 PRIMARY KEY, b INT4 ) PARTITION BY RANGE (a) SUBPARTITION BY HASH (b) ( PARTITION p1 VALUES LESS THAN (200) ( SUBPARTITION s11, SUBPARTITION s12, SUBPARTITION s13, SUBPARTITION s14 ), PARTITION p2 VALUES LESS THAN (500) ( SUBPARTITION s21, SUBPARTITION s22 ), PARTITION p3 VALUES LESS THAN (800), PARTITION p4 VALUES LESS THAN (1200) ( SUBPARTITION s41 ) ); insert into test_range_subpart values(199,1),(499,1),(799,1),(1199,1); --test test_range_subpart alter table test_range_subpart reorganize partition p1,p2 into (partition m1 values less than(100),partition m2 values less than(500)(subpartition m21,subpartition m22)); select pg_get_tabledef('test_range_subpart'); select * from test_range_subpart subpartition(m22); select * from test_range_subpart subpartition(m21); select * from test_range_subpart partition(m1); explain select /*+ indexscan(test_range_subpart test_range_subpart_pkey) */ * from test_range_subpart where a > 0; select * from test_range_subpart; -- 分区表建索引,在create table 中index默认为local,不支持指定global/local CREATE TABLE test_partition_btree ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_btree_idx using btree(f1) ) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); -- 分区表建组合索引 CREATE TABLE test_partition_index ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_btree_idx2 using btree(f1 desc, f2 asc) ) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); -- 分区表列存创建索引 CREATE TABLE test_partition_column ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_column(f1) ) with (ORIENTATION = COLUMN) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); -- 分区表创建表达式索引 CREATE TABLE test_partition_expr ( f1 INTEGER, f2 INTEGER, f3 INTEGER, key part_expr_idx using btree((abs(f1)+1)) ) PARTITION BY RANGE(f1) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(MAXVALUE) ); ``` * 示例7:创建分区键为表达式分区的分区表。 ``` openGauss=# create table testrangepart(a int, b int) partition by range(abs(a*2)) ( partition p0 values less than(100), partition p1 values less than(200) ); CREATE TABLE openGauss=# select partkeyexpr from pg_partition where (parttype = 'r') and (parentid in (select oid from pg_class where relname = 'testrangepart')); partkeyexpr --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- {FUNCEXPR :funcid 1397 :funcresulttype 23 :funcresulttype_orig -1 :funcretset false :funcformat 0 :funccollid 0 :inputcollid 0 :args ({OPEXPR :opno 514 :opfuncid 141 :opresulttype 23 :opretset false :opcollid 0 :inputcollid 0 :args ({VAR :varno 1 :varattno 1 :vartype 23 :vartypmod -1 :varcollid 0 :varlevelsup 0 :varnoold 1 :varoattno 1 :location 64} {CONST :consttype 23 :consttypmod -1 :constcollid 0 :constlen 4 :constbyval true :constisnull false :ismaxvalue false :location 66 :constvalue 4 [ 2 0 0 0 0 0 0 0 ] :cursor_data :row_count 0 :cur_dno -1 :is_open false :found false :not_found false :null_open false :null_fetch false}) :location 65}) :location 60 :refSynOid 0} (1 row) openGauss=# insert into testrangepart values(-51,1),(49,2); INSERT 0 2 openGauss=# insert into testrangepart values(-101,1); ERROR: inserted partition key does not map to any table partition openGauss=# select * from testrangepart partition(p0); a | b ----+--- 49 | 2 (1 row) openGauss=# select * from testrangepart partition(p1); a | b -----+--- -51 | 1 (1 row) openGauss=# select * from testrangepart where a = -51; a | b -----+--- -51 | 1 (1 row) ``` ## 相关链接 [ALTER TABLE PARTITION](https://docs.opengauss.org/zh/docs/latest/sql_reference/alter_table_partition.html),[DROP TABLE](https://docs.opengauss.org/zh/docs/latest/sql_reference/drop_table.html) --- --- url: /zh/docs/latest/ograc/sql_reference/create_table_partition.md --- # CREATE TABLE PARTITION ## 功能描述 创建分区表。 分区表是将一个逻辑上的大表,在物理存储上分割成多个更小、更易管理的部分(称为"分区"或"子表")的技术。每个分区可以独立存储、备份、维护和查询,但对用户和应用来说,它仍然像一张完整的表。oGRAC 支持范围分区,列表分区,哈希分区,间隔分区。 ## 注意事项 分区表和普通表的属性存在一些不兼容。 * 当前支持RANGE、LIST、HASH、INTERVAL四种分区 * 分区键不超过16个字段 * 支持设置为分区键的列类型:UINT32、UINT64、INTEGER、BIGINT、REAL、NUMBER、NUMBER2、NUMBER3、DECIMAL、DATE、TIMESTAMP、INTERVAL\_DS、INTERVAL\_YM、CHAR、VARCHAR、STRING、BINARY、RAW * 最多支持16777216个分区,采用HASH分区时最多支持8388608个分区 ## 语法格式 **stmt:** ```sql CREATE TABLE [IF NOT EXISTS] [schema_name.]table_name ({column_def_clause}[,...] [external_constraint][,...]) ``` 共享语句尾部及各子句的完整定义参见 [CREATE TABLE 共享子句](shared/create_table_common_clauses.md)。 分区表继承普通表的列定义、约束及存储子句。 **using\_index\_clause:** ``` USING INDEX [ INITRANS int | TABLESPACE tablespace_name | LOCAL [({PARTITION partition_name [TABLESPACE tablespace_name | INITRANS int | PCTFREE int | ({SUBPARTITION subpartition_name[TABLESPACE tablespace_name]} [,...] )]}[,...])] ] [ ...] ``` **table\_attr\_clause:** ``` [column_attr_clause] [AUTO_INCREMENT [=] value] [table_partition_clause] ``` **column\_attr\_clause:** ``` [LOB (LOB_item) STORE AS LOB_segname [(LOB_parameters)]] [APPENDONLY {ON|OFF}] ``` **table\_partition\_clause:** ``` range_partition_clause | list_partition_clause | hash_partition_clause | interval_partition_clause ``` **range\_partition\_clause:** ``` PARTITION BY RANGE (partition_key[,...]) [SUBPARTITION BY {RANGE|LIST|HASH} (subpartition_key [,...])] (range_partition_item[,...]) ``` **range\_partition\_item:** ``` PARTITION partition_name VALUES LESS THAN ({value | MAXVALUE}[,...]) [physical_properties_clause] [(subpartition_item[,...])] ``` **subpartition\_item:** ``` SUBPARTITION subpartition_name [{VALUES LESS THAN ({value | MAXVALUE}[,...]) | VALUES ({value | DEFAULT}[,...])}] [TABLESPACE tablespace_name] ``` **list\_partition\_clause:** ``` PARTITION BY LIST (partition_key[,...]) [SUBPARTITION BY {RANGE|LIST|HASH} (subpartition_key [,...])] (list_partition_item[,...]) ``` **list\_partition\_item:** ``` PARTITION partition_name VALUES ([value][,...] [DEFAULT]) [physical_properties_clause] [(subpartition_item[,...])] ``` **hash\_partition\_clause:** ``` PARTITION BY HASH (partition_key[,...]) [SUBPARTITION BY {RANGE|LIST|HASH} (subpartition_key [,...])] ({hash_partition_item1[,...] | hash_partition_item2}) ``` **hash\_partition\_item1:** ``` PARTITION partition_name [physical_properties_clause] [(subpartition_item[,...])] ``` **hash\_partition\_item2:** ``` PARTITIONS partition_count (STORE IN (tablespace_name[,...])) ``` **interval\_partition\_clause:** ``` PARTITION BY RANGE (partition_key) INTERVAL (value) [STORE IN (TABLESPACE tablespace_name[,...])] [SUBPARTITION BY {RANGE|LIST|HASH} (subpartition_key [,...])] (range_partition_item[,...]) ``` **physical\_properties\_clause:** ``` segment_attr_clause | FORMAT row_format_clause ``` ## 参数说明 * [普通表共有的参数](create_table.md#参数说明) * range\_partition\_clause: RANGE分区 * list\_partition\_clause: LIST分区 * hash\_partition\_clause: HASH分区 * interval\_partition\_clause: INTERVAL分区 * partition\_key: 分区键所在列的集合 * VALUES LESS THAN: RANGE分区的分区键最大值 * SUBPARTITION BY {RANGE|LIST|HASH}: 定义二级分区分区方式 * MAXVALUE:分区特殊定义,最大值 * VALUES(value): LIST分区键值 * VALUES(DEFAULT): DEFAULT分区,默认值所在分区 * PARTITIONS partition\_count: HASH分区数,指定后自动创建partition\_count个分区,数据均匀分布 ## 示例 ``` -- 范围分区 CREATE TABLE sales_range ( sale_id NUMBER, sale_date DATE, amount NUMBER, region VARCHAR2(50) ) PARTITION BY RANGE (sale_date) ( PARTITION sales_q1 VALUES LESS THAN (TO_DATE('2024-04-01', 'YYYY-MM-DD')), PARTITION sales_q2 VALUES LESS THAN (TO_DATE('2024-07-01', 'YYYY-MM-DD')), PARTITION sales_q3 VALUES LESS THAN (TO_DATE('2024-10-01', 'YYYY-MM-DD')), PARTITION sales_q4 VALUES LESS THAN (MAXVALUE) ); -- 列表分区 CREATE TABLE employees_list ( emp_id NUMBER, emp_name VARCHAR2(100), department VARCHAR2(50), salary NUMBER ) PARTITION BY LIST (department) ( PARTITION dept_sales VALUES ('SALES', 'MARKETING'), PARTITION dept_tech VALUES ('IT', 'ENGINEERING'), PARTITION dept_hr VALUES ('HR', 'ADMIN'), PARTITION dept_other VALUES (DEFAULT) ); -- 哈希分区方式1:指定分区名称 CREATE TABLE products_hash ( product_id NUMBER, product_name VARCHAR2(200), category VARCHAR2(100) ) PARTITION BY HASH (product_id) ( PARTITION p1, PARTITION p2, PARTITION p3, PARTITION p4 ); -- 哈希分区方式2:指定分区数量 CREATE TABLE orders_hash ( order_id NUMBER, order_date DATE, customer_id NUMBER ) PARTITION BY HASH (order_id) PARTITIONS 8; -- 间隔分区 CREATE TABLE sales_interval ( sale_id NUMBER, sale_date DATE, amount NUMBER, region VARCHAR2(50) ) PARTITION BY RANGE (sale_date) INTERVAL (NUMTOYMINTERVAL(1, 'MONTH')) ( PARTITION sales_historical VALUES LESS THAN (TO_DATE('2024-01-01', 'YYYY-MM-DD')), PARTITION sales_jan_2024 VALUES LESS THAN (TO_DATE('2024-02-01', 'YYYY-MM-DD')) ); -- 二级分区 RANGE + LIST CREATE TABLE sales_subpart ( sale_id NUMBER, sale_date DATE, region VARCHAR2(20), product_type VARCHAR2(30), amount NUMBER ) PARTITION BY RANGE (sale_date) SUBPARTITION BY LIST (region) ( PARTITION sales_2023 VALUES LESS THAN (DATE '2024-01-01') ( SUBPARTITION north VALUES ('NORTH'), SUBPARTITION south VALUES ('SOUTH'), SUBPARTITION east VALUES ('EAST'), SUBPARTITION west VALUES ('WEST'), SUBPARTITION other VALUES (DEFAULT) ), PARTITION sales_2024 VALUES LESS THAN (DATE '2025-01-01'), PARTITION sales_future VALUES LESS THAN (MAXVALUE) ); ``` --- --- url: /zh/docs/latest/sql_reference/create_table_partition.md --- # CREATE TABLE PARTITION ## 功能描述 创建分区表。分区表是把逻辑上的一张表根据某种方案分成几张物理块进行存储,这张逻辑上的表称之为分区表,物理块称之为分区。分区表是一张逻辑表,不存储数据,数据实际是存储在分区上的。 常见的分区方案有范围分区(Range Partitioning)、间隔分区(Interval Partitioning)、哈希分区(Hash Partitioning)、列表分区(List Partitioning)、数值分区(Value Partition)等。目前行存表支持范围分区、间隔分区、哈希分区、列表分区,列存表仅支持范围分区。 范围分区是根据表的一列或者多列,将要插入表的记录分为若干个范围,这些范围在不同的分区里没有重叠。为每个范围创建一个分区,用来存储相应的数据。 范围分区的分区策略是指记录插入分区的方式。目前范围分区仅支持范围分区策略。 范围分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。这是最常用的分区策略。 间隔分区是一种特殊的范围分区,相比范围分区,新增间隔值定义,当插入记录找不到匹配的分区时,可以根据间隔值自动创建分区。 间隔分区只支持基于表的一列分区,并且该列只支持TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE数据类型。 间隔分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则根据分区键值和表定义信息自动创建一个分区,然后将记录插入新分区中,新创建的分区数据范围等于间隔值。 哈希分区是根据表的一列,为每个分区指定模数和余数,将要插入表的记录划分到对应的分区中,每个分区所持有的行都需要满足条件:分区键的值除以为其指定的模数将产生为其指定的余数。 哈希分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则返回报错和提示信息。 列表分区是根据表的一列,将要插入表的记录通过每一个分区中出现的键值划分到对应的分区中,这些键值在不同的分区里没有重叠。为每组键值创建一个分区,用来存储相应的数据。 列表分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。 分区可以提供若干好处: * 某些类型的查询性能可以得到极大提升。特别是表中访问率较高的行位于一个单独分区或少数几个分区上的情况下。分区可以减少数据的搜索空间,提高数据访问效率。 * 当查询或更新一个分区的大部分记录时,连续扫描那个分区而不是访问整个表可以获得巨大的性能提升。 * 如果需要大量加载或者删除的记录位于单独的分区上,则可以通过直接读取或删除那个分区以获得巨大的性能提升,同时还可以避免由于大量DELETE导致的VACUUM超载(哈希分区不支持删除分区)。 ## 注意事项 * 唯一约束和主键约束的约束键包含所有分区键将为约束创建LOCAL索引,否则创建GLOBAL索引。 * 目前哈希分区和列表分区仅支持单列构建分区键,暂不支持多列构建分区键。 * 只需要有间隔分区表的INSERT权限,往该表INSERT数据时就可以自动创建分区。 * 对于分区表PARTITION FOR (values)语法,values只能是常量。 * 对于分区表PARTITION FOR (values)语法,values在需要数据类型转换时,建议使用强制类型转换,以防隐式类型转换结果与预期不符。 * 分区数最大值为1048575个,一般情况下业务不可能创建这么多分区,这样会导致内存不足。应参照参数local\_syscache\_threshold的值合理创建分区,分区表使用内存大致为(分区数 \* 3 / 1024)MB。理论上分区占用内存不允许大于local\_syscache\_threshold的值,同时还需要预留部分空间以供其他功能使用。 * 当分区数太多导致内存不足时,会间接导致性能急剧下降。 * 指定分区语句目前不能走全局索引扫描。 * 目前Hash分区是按倒序排列的,即通过哈希和取余计算后得到的分区下标与创建顺序相反,同样EXPLAIN计划显示的Selected Partitions的序号排序也与创建顺序相反。List分区是按分区数组的第一个元素排序的。 * 支持使用表达式当作分区键,允许分区键使用算术运算符 "+"、"-"、"\*"。 * 只支持部分函数允许在分区键中使用,支持的函数为: ABS()、CEILING()。 * 表达式用作分区键时,只支持设置一个partition key,且分区为range、hash和list分区,另外暂不支持列存表。 ## 语法格式 ``` CREATE TABLE [ IF NOT EXISTS ] partition_table_name ( [ { column_name data_type [ CHARACTER SET | CHARSET charset ] [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] } [, ... ] ] ) [ AUTO_INCREMENT [ = ] value ] [ [ DEFAULT ] CHARACTER SET | CHARSET [ = ] default_charset ][ [ DEFAULT ] COLLATE [ = ] default_collation ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] [ DISTRIBUTE BY { REPLICATION | { [ HASH ] ( column_name ) } } ] NOTICE: DISTRIBUTE BY is only avaliable in DISTRIBUTED mode! [ TO { GROUP groupname | NODE ( nodename [, ... ] ) } ] PARTITION BY { {VALUES (partition_key)} | {RANGE [ COLUMNS ] (partition_key) [ INTERVAL ('interval_expr') [ STORE IN ( tablespace_name [, ...] ) ] ] [ PARTITIONS integer ] ( partition_less_than_item [, ... ] )} | {RANGE [ COLUMNS ] (partition_key) [ INTERVAL ('interval_expr') [ STORE IN ( tablespace_name [, ...] ) ] ] [ PARTITIONS integer ] ( partition_start_end_item [, ... ] )} | {{{LIST [ COLUMNS ]} | HASH | KEY} (partition_key) [ PARTITIONS integer ] (PARTITION partition_name [ VALUES [ IN ] (list_values_clause) ] opt_table_space ) } } [ { ENABLE | DISABLE } ROW MOVEMENT ]; ``` * 列约束column\_constraint: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_e xpr | GENERATED ALWAYS AS ( generation_expr ) [STORED] | AUTO_INCREMENT | UNIQUE [KEY] index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * 表约束table\_constraint: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * like选项like\_option: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS| ALL } ``` * 索引存储参数index\_parameters: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` * partition\_less\_than\_item: ``` PARTITION partition_name VALUES LESS THAN {( { partition_value | MAXVALUE } [,...] ) | MAXVALUE } [TABLESPACE [=] tablespace_name] ``` * partition\_start\_end\_item: ``` PARTITION partition_name { {START(partition_value) END (partition_value) EVERY (interval_value)} | {START(partition_value) END ({partition_value | MAXVALUE})} | {START(partition_value)} | {END({partition_value | MAXVALUE})} } [TABLESPACE [=] tablespace_name] ``` * COMMENT {=| } 'text': 分区表的分区中,该字段无实际意义,仅作语法兼容。在数据库中使用该语法时会有告警提示。 ## 参数说明 * **IF NOT EXISTS** 如果已经存在相同名称的表,不会抛出一个错误,而会发出一个通知,告知表关系已存在。 * **partition\_table\_name** 分区表的名称。 取值范围:字符串,要符合标识符的命名规范。 * **column\_name** 新表中要创建的字段名。 取值范围:字符串,要符合标识符的命名规范。 * **data\_type** 字段的数据类型。 * **COLLATE collation** COLLATE子句指定列的排序规则(该列必须是可排列的数据类型)。如果没有指定,则使用默认的排序规则。排序规则可以使用“select \* from pg\_collation;”命令从pg\_collation系统表中查询,默认的排序规则为查询结果中以default开始的行。 * **CONSTRAINT constraint\_name** 列约束或表约束的名称。可选的约束子句用于声明约束,新行或者更新的行必须满足这些约束才能成功插入或更新。 定义约束有两种方法: * 列约束:作为一个列定义的一部分,仅影响该列。 * 表约束:不和某个列绑在一起,可以作用于多个列。在B模式数据库下(即sql\_compatibility = 'B')constraint\_name为可选项,在其他模式数据库下,必须加上constraint\_name。 * **index\_name** 索引名。 > \[!TIP]须知 > > * index\_name仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 对于外键约束,constraint\_name和index\_name同时指定时,索引名为constraint\_name。 > * 对于唯一键约束,constraint\_name和index\_name同时指定时,索引名以index\_name。 * **USING method** 指定创建索引的方法。 取值范围参考[参数说明](create_index.md)中的USING method。 > \[!TIP]须知 > > * USING method仅在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库下不支持。 > * 在B模式下,未指定USING method时,对于Astore的存储方式,默认索引方法为btree;对于Ustore的存储方式,默认索引方法为ubtree。 * **ASC | DESC** ASC表示指定按升序排序(默认)。DESC指定按降序排序。 > \[!TIP]须知 > > ASC|DESC只在B模式数据库下(即sql\_compatibility = 'B')支持,其他模式数据库不支持。 * **LIKE source\_table \[ like\_option ... ]** LIKE子句声明一个表,新表自动从这个表里面继承所有字段名及其数据类型和非空约束。 和INHERITS不同,新表与原来的表之间在创建动作完毕之后是完全无关的。在源表做的任何修改都不会传播到新表中,并且也不可能在扫描源表的时候包含新表的数据。 * 字段缺省表达式只有在声明了INCLUDING DEFAULTS之后才会包含进来。缺省是不包含缺省表达式的,即新表中所有字段的缺省值都是NULL。 * 如果指定了INCLUDING GENERATED,则源表列的生成表达式会复制到新表中。默认不复制生成表达式。 * 非空约束将总是复制到新表中,CHECK约束则仅在指定了INCLUDING CONSTRAINTS的时候才复制,而其他类型的约束则永远也不会被复制。此规则同时适用于表约束和列约束。 * 和INHERITS不同,被复制的列和约束并不使用相同的名称进行融合。如果明确的指定了相同的名称或者在另外一个LIKE子句中,将会报错。 * 如果指定了INCLUDING INDEXES,则源表上的索引也将在新表上创建,默认不建立索引。 * 如果指定了INCLUDING STORAGE,则源表列的STORAGE设置也将被拷贝,默认情况下不包含STORAGE设置。 * 如果指定了INCLUDING COMMENTS,则源表列、约束和索引的注释也会被拷贝过来。默认情况下,不拷贝源表的注释。 * 如果指定了INCLUDING RELOPTIONS,则源表的存储参数(即源表的WITH子句)也将拷贝至新表。默认情况下,不拷贝源表的存储参数。 * INCLUDING ALL包含了INCLUDING DEFAULTS、INCLUDING CONSTRAINTS、INCLUDING INDEXES、INCLUDING STORAGE、INCLUDING COMMENTS、INCLUDING PARTITION和INCLUDING RELOPTIONS的内容。 * **AUTO\_INCREMENT \[ = ] value** 这个子句为自动增长列指定一个初始值,value必须为正整数,不得超过2127-1。 > \[!TIP]须知 > > 该子句仅在参数sql\_compatibility=B时有效。 * **\[ DEFAULT ] CHARACTER SET | CHARSET \[ = ] default\_charset ]** 指定模式的默认字符集,单独指定时会将模式的默认字符序设置为指定的字符集的默认字符序。 * **\[ \[ DEFAULT ] COLLATE \[ = ] default\_collation** 指定模式的默认字符序,单独指定时会将模式的默认字符集设置为指定的字符序对应的字符集。 * **WITH ( storage\_parameter \[= value] \[, ... ] )** 这个子句为表或索引指定一个可选的存储参数。参数的详细描述如下所示: * FILLFACTOR 一个表的填充因子(fillfactor)是一个介于10和100之间的百分数。100(完全填充)是默认值。如果指定了较小的填充因子,INSERT操作仅按照填充因子指定的百分率填充表页。每个页上的剩余空间将用于在该页上更新行,这就使得UPDATE有机会在同一页上放置同一条记录的新版本,这比把新版本放置在其他页上更有效。对于一个从不更新的表将填充因子设为100是最佳选择,但是对于频繁更新的表,选择较小的填充因子则更加合适。该参数对于列存表没有意义。 取值范围:10~100 * ORIENTATION 决定了表的数据的存储方式。 取值范围: * COLUMN:表的数据将以列式存储。 * ROW(缺省值):表的数据将以行式存储。 > \[!TIP]须知 > > orientation不支持修改。 * COMPRESSTYPE 行存表参数,设置行存表压缩算法。1代表pglz算法(不推荐使用),2代表zstd算法,3代表pgzstd算法(目前暂不支持),4代表zlib算法,默认不压缩。该参数允许修改,修改对已有数据、变更数据、新增数据同时生效。(仅支持Astore和Ustore下的普通表和分区表) 取值范围:0~4,默认值为0。 * COMPRESS\_LEVEL 行存表参数,设置行存表压缩算法等级,仅当COMPRESSTYPE为2或4时生效。压缩等级越高,表的压缩效果越好,表的访问速度越慢。该参数允许修改,修改对已有数据、变更数据、新增数据同时生效。 取值范围:-31~31,默认值为0。 * COMPRESS\_CHUNK\_SIZE 行存表参数,设置行存表压缩chunk块大小,仅当COMPRESSTYPE不为0时生效。chunk数据块越小,预期能达到的压缩效果越好,同时数据越离散,影响表的访问速度。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:与页面大小有关。在页面大小为8k场景,取值范围为:512、1024、2048、4096。 默认值:4096 * COMPRESS\_PREALLOC\_CHUNKS 行存表参数,设置行存表压缩chunk块预分配数量。预分配数量越大,表的压缩率相对越差,离散度越小,访问性能越好。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:0~7,默认值为0。 * 当COMPRESS\_CHUNK\_SIZE为512和1024时,支持预分配设置最大为7。 * 当COMPRESS\_CHUNK\_SIZE为2048时,支持预分配设置最大为3。 * 当COMPRESS\_CHUNK\_SIZE为4096时,支持预分配设置最大为1。 * COMPRESS\_BYTE\_CONVERT 行存表参数,设置行存表压缩字节转换预处理,仅当COMPRESSTYPE不为0时生效。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:布尔值,默认关闭。 * COMPRESS\_DIFF\_CONVERT 行存表参数,设置行存表压缩字节差分预处理。只能与compress\_byte\_convert一起使用。在一些场景下可以提升压缩效果,同时会导致一定性能劣化。该参数允许修改, 修改对已有数据、变更数据、新增数据同时生效。 取值范围:布尔值,默认关闭。 * STORAGE\_TYPE ``` 指定存储引擎类型,该参数设置成功后就不再支持修改。 取值范围: - USTORE,表示表支持Inplace-Update存储引擎。特别需要注意,使用USTORE表,必须要开启track\_counts和track\_activities参数,否则会引起空间膨胀。 - ASTORE,表示表支持Append-Only存储引擎。 默认值: 不指定表时,默认是Append-Only存储。 ``` * COMPRESSION * 列存表的有效值为LOW/MIDDLE/HIGH/YES/NO,压缩级别依次升高,默认值为LOW。 * 行存表不支持压缩。 * MAX\_BATCHROW 指定了在数据加载过程中一个存储单元可以容纳记录的最大数目。该参数只对列存表有效。 取值范围:10000~60000,默认60000。 * PARTIAL\_CLUSTER\_ROWS 指定了在数据加载过程中进行将局部聚簇存储的记录数目。该参数只对列存表有效。 取值范围:大于等于MAX\_BATCHROW,建议取值为MAX\_BATCHROW的整数倍数。 * DELTAROW\_THRESHOLD 预留参数。该参数只对列存表有效。 取值范围:0~9999 * segment 使用段页式的方式存储。本参数仅支持行存表。不支持列存表、临时表、unlog表。不支持Ustore存储引擎。 取值范围:on/off 默认值:off * **COMPRESS / NOCOMPRESS** 创建一个新表时,需要在创建表语句中指定关键字COMPRESS,这样,当对该表进行批量插入时就会触发压缩特性。该特性会在页范围内扫描所有元组数据,生成字典、压缩元组数据并进行存储。指定关键字NOCOMPRESS则不对表进行压缩。行存表不支持压缩。该参数已废弃,列存表请使用COMPRESSION修改压缩等级。 缺省值为NOCOMPRESS,即不对元组数据进行压缩。 * **TABLESPACE tablespace\_name** 指定新表将要在tablespace\_name表空间内创建。如果没有声明,将使用默认表空间。 * **TO { GROUP groupname | NODE ( nodename \[, … ] ) }** 此语法仅在扩展模式(GUC参数support\_extended\_features为on时)下可用。该模式谨慎打开,主要供内部扩容工具使用,一般用户不应使用该模式。 * **PARTITION BY VALUES (partition\_key)** 创建数值分区。partition\_key为分区键的名称。 * **PARTITION BY RANGE \[COLUMNS]\(partition\_key)** 创建范围分区。partition\_key为分区键的名称。 COLUMNS关键字只能在sql\_compatibility='B'时使用,“PARTITION BY RANGE COLUMNS” 语义同 “PARTITION BY RANGE”。 (1)对于从句是VALUES LESS THAN的语法格式: > \[!TIP]须知 > 对于从句是VALUE LESS THAN的语法格式,范围分区策略的分区键最多支持16列。 该情形下,分区键支持的数据类型为:SMALLINT、INTEGER、BIGINT、DECIMAL、NUMERIC、REAL、DOUBLE PRECISION、CHARACTER VARYING(n)、VARCHAR(n)、CHARACTER(n)、CHAR(n)、CHARACTER、CHAR、TEXT、NVARCHAR、NVARCHAR2、NAME、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 (2)对于从句是START END的语法格式: > \[!TIP]须知 > 对于从句是START END的语法格式,范围分区策略的分区键仅支持1列。 该情形下,分区键支持的数据类型为:SMALLINT、INTEGER、BIGINT、DECIMAL、NUMERIC、REAL、DOUBLE PRECISION、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 (3)对于指定了INTERVAL子句的语法格式: > \[!TIP]须知 > 对于指定了INTERVAL子句的语法格式,范围分区策略的分区键仅支持1列。 该情形下,分区键支持的数据类型为:TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。 * **PARTITION partition\_name VALUES LESS THAN {( { partition\_value | MAXVALUE } \[,...] ) | MAXVALUE }** 指定各分区的信息。partition\_name为范围分区的名称。partition\_value为范围分区的上边界,取值依赖于partition\_key的类型。MAXVALUE表示分区的上边界,它通常用于设置最后一个范围分区的上边界。 > \[!TIP]须知 > > * 每个分区都需要指定一个上边界。 > * 分区上边界的类型应当和分区键的类型一致。 > * 分区列表是按照分区上边界升序排列的,值较小的分区位于值较大的分区之前。 > * 不在括号内的MAVALUE只能在sql\_compatibility='B'时使用,并且只能有一个分区键。 * **PARTITION partition\_name {START (partition\_value) END (partition\_value) EVERY (interval\_value)} | {START (partition\_value) END (partition\_value|MAXVALUE)} | {START(partition\_value)} | {END (partition\_value | MAXVALUE)}** 指定各分区的信息,各参数意义如下: * partition\_name:范围分区的名称或名称前缀,除以下情形外(假定其中的partition\_name是p1),均为分区的名称。 * 若该定义是START+END+EVERY从句,则语义上定义的分区的名称依次为p1\_1, p1\_2, ...。例如对于定义“PARTITION p1 START(1) END(4) EVERY(1)”,则生成的分区是:\[1, 2), \[2, 3) 和 \[3, 4),名称依次为p1\_1, p1\_2和p1\_3,即此处的p1是名称前缀。 * 若该定义是第一个分区定义,且该定义有START值,则范围(MINVALUE, START)将自动作为第一个实际分区,其名称为p1\_0,然后该定义语义描述的分区名称依次为p1\_1, p1\_2, ...。例如对于完整定义“PARTITION p1 START(1), PARTITION p2 START(2)”,则生成的分区是:(MINVALUE, 1), \[1, 2) 和 \[2, MAXVALUE),其名称依次为p1\_0, p1\_1和p2,即此处p1是名称前缀,p2是分区名称。这里MINVALUE表示最小值。 * partition\_value:范围分区的端点值(起始或终点),取值依赖于partition\_key的类型,不可是MAXVALUE。 * interval\_value:对\[START,END) 表示的范围进行切分,interval\_value是指定切分后每个分区的宽度,不可是MAXVALUE;如果(END-START)值不能整除以EVERY值,则仅最后一个分区的宽度小于EVERY值。 * MAXVALUE:表示最大值,它通常用于设置最后一个范围分区的上边界。 > \[!TIP]须知 > > 1. 在创建分区表若第一个分区定义含START值,则范围(MINVALUE,START)将自动作为实际的第一个分区。 > 2. START END语法需要遵循以下限制: > * 每个partition\_start\_end\_item中的START值(如果有的话,下同)必须小于其END值。 > * 相邻的两个partition\_start\_end\_item,第一个的END值必须等于第二个的START值; > * 每个partition\_start\_end\_item中的EVERY值必须是正向递增的,且必须小于(END-START)值; > * 每个分区包含起始值,不包含终点值,即形如:\[起始值,终点值),起始值是MINVALUE时则不包含; > * 一个partition\_start\_end\_item创建的每个分区所属的TABLESPACE一样; > * partition\_name作为分区名称前缀时,其长度不要超过57字节,超过时自动截断; > * 在创建、修改分区表时请注意分区表的分区总数不可超过最大限制(1048575); > 3. 在创建分区表时START END与LESS THAN语法不可混合使用。 > 4. 即使创建分区表时使用START END语法,备份(gs\_dump)出的SQL语句也是VALUES LESS THAN语法格式。 * **INTERVAL ('interval\_expr') \[ STORE IN (tablespace\_name \[, ... ] ) ]** 间隔分区定义信息。 * interval\_expr:自动创建分区的间隔,例如:1 day、1 month。 * STORE IN (tablespace\_name \[, ... ] ):指定存放自动创建分区的表空间列表,如果有指定,则自动创建的分区从表空间列表中循环选择使用,否则使用分区表默认的表空间。 > \[!TIP]须知 > > 列存表不支持间隔分区。 * **PARTITION BY LIST \[COLUMNS] (partition\_key)** 创建列表分区。partition\_key为分区键的名称。 COLUMNS关键字只能在sql\_compatibility='B'时使用,“PARTITION BY LIST COLUMNS” 语义同 “PARTITION BY LIST”。 * 对于partition\_key,列表分区策略的分区键最多支持16列。 * 对于从句是VALUES \[IN] (list\_values)的语法格式,list\_values中包含了对应分区存在的键值,每个分区的键值数量不超过64个。 * 从句"VALUES IN"只能在sql\_compatibility='B'时使用,语义同"VALUES"。 分区键支持的数据类型为:INT1、INT2、INT4、INT8、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过1048575个。 * **PARTITION BY HASH(partition\_key)** 创建哈希分区。partition\_key为分区键的名称。 对于partition\_key,哈希分区策略的分区键仅支持1列。 分区键支持的数据类型为:INT1、INT2、INT4、INT8、NUMERIC、VARCHAR(n)、CHAR、BPCHAR、TEXT、NVARCHAR、NVARCHAR2、TIMESTAMP\[(p)] \[WITHOUT TIME ZONE]、TIMESTAMP\[(p)] \[WITH TIME ZONE]、DATE。分区个数不能超过1048575 个。 * **PARTITION BY KEY(partition\_key)** 只能在sql\_compatibility='B'时使用,语义同“PARTITION BY HASH(partition\_key)”。 * **PARTITIONS integer** 指定分区个数。 integer为分区数,必须为大于0的整数,且不得大于1048575。 * 当在RANGE和LIST分区后指定此子句时,必须显式定义每个分区,且定义分区的数量必须与integer值相等。只能在sql\_compatibility='B'时在RANGE和LIST分区后指定此子句。 * 当在HASH和KEY分区后指定此子句时,若不列出各个分区定义,将自动生成integer个分区,自动生成的分区名为“p+数字”,数字依次为0到integer-1,分区的表空间默认为此表的表空间;也可以显式列出每个分区定义,此时定义分区的数量必须与integer值相等。若既不列出分区定义,也不指定分区数量,将创建唯一一个分区。 * **{ ENABLE | DISABLE } ROW MOVEMENT** 行迁移开关。 如果进行UPDATE操作时,更新了元组在分区键上的值,造成了该元组所在分区发生变化,就会根据该开关给出报错信息,或者进行元组在分区间的转移。 取值范围: * ENABLE(缺省值):行迁移开关打开。 * DISABLE:行迁移开关关闭。 * **NOT NULL** 字段值不允许为NULL。ENABLE用于语法兼容,可省略。 * **NULL** 字段值允许NULL ,这是缺省。 这个子句只是为和非标准SQL数据库兼容。不建议使用。 * **CHECK (condition) \[ NO INHERIT ]** CHECK约束声明一个布尔表达式,每次要插入的新行或者要更新的行的新值必须使表达式结果为真或未知才能成功,否则会抛出一个异常并且不会修改数据库。 声明为字段约束的检查约束应该只引用该字段的数值,而在表约束里出现的表达式可以引用多个字段。 用NO INHERIT标记的约束将不会传递到子表中去。 ENABLE用于语法兼容,可省略。 * **DEFAULT default\_expr** DEFAULT子句给字段指定缺省值。该数值可以是任何不含变量的表达式(不允许使用子查询和对本表中的其他字段的交叉引用)。缺省表达式的数据类型必须和字段类型匹配。 缺省表达式将被用于任何未声明该字段数值的插入操作。如果没有指定缺省值则缺省值为NULL 。 * **GENERATED ALWAYS AS ( generation\_expr ) \[STORED]** 该子句将字段创建为生成列,生成列的值在写入(插入或更新)数据时由generation\_expr计算得到,STORED表示像普通列一样存储生成列的值。 > \[!NOTE]说明 > > * STORED关键字可省略,与不省略STORED语义相同。 > * 生成表达式不能以任何方式引用当前行以外的其他数据。生成表达式不能引用其他生成列,不能引用系统列。生成表达式不能返回结果集,不能使用子查询,不能使用聚集函数,不能使用窗口函数。生成表达式调用的函数只能是不可变(IMMUTABLE)函数。 > * 不能为生成列指定默认值。 > * 生成列不能作为分区键的一部分。 > * 生成列不能和ON UPDATE约束字句的CASCADE,SET NULL,SET DEFAULT动作同时指定。生成列不能和ON DELETE约束字句的SET NULL、SET DEFAULT动作同时指定。 > * 修改和删除生成列的方法和普通列相同。删除生成列依赖的普通列,生成列被自动删除。不能改变生成列所依赖的列的类型。 > * 生成列不能被直接写入。在INSERT或UPDATE命令中, 不能为生成列指定值, 但是可以指定关键字DEFAULT。 > * 生成列的权限控制和普通列一样。 > * 列存表、内存表MOT不支持生成列。外表中仅postgres\_fdw支持生成列。 * **AUTO\_INCREMENT** 指定列为自动增长列。 详见:[AUTO\_INCREMENT](create_table.md)。 * **UNIQUE \[KEY] index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** UNIQUE约束表示表里的一个字段或多个字段的组合必须在全表范围内唯一。 对于唯一约束,NULL被认为是互不相等的。 UNIQUE KEY只能在sql\_compatibility='B'时使用,与UNIQUE语义相同。 * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** 主键约束声明表中的一个或者多个字段只能包含唯一的非NULL值。 一个表只能声明一个主键。 * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(默认):启用约束,创建索引,对已有数据和新加入的数据执行约束。 * ENABLE NOVALIDATE:启用约束,创建索引。对于CHECK约束仅对新加入的数据执行约束,不管表中现有数据。对于UNIQUE和PRIMARY KEY需要建立索引,所以会对已有数据执行约束。 * DISABLE( NOVALIDATE)(默认):关闭约束,删除索引,可以对约束列的数据进行修改等操作。 * DISABLE VALIDATE:关闭约束,删除索引,不能对表进行插入、更新和删除操作。 * **DEFERRABLE | NOT DEFERRABLE** 这两个关键字设置该约束是否可推迟。一个不可推迟的约束将在每条命令之后马上检查。可推迟约束可以推迟到事务结尾使用SET CONSTRAINTS命令检查。缺省是NOT DEFERRABLE。目前,UNIQUE约束、主键约束、外键约束可以接受这个子句。所有其他约束类型都是不可推迟的。 * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** 如果约束是可推迟的,则这个子句声明检查约束的缺省时间。 * 如果约束是INITIALLY IMMEDIATE(缺省),则在每条语句执行之后就立即检查它; * 如果约束是INITIALLY DEFERRED ,则只有在事务结尾才检查它。 约束检查的时间可以用SET CONSTRAINTS命令修改。 * **USING INDEX TABLESPACE tablespace\_name** 为UNIQUE或PRIMARY KEY约束相关的索引声明一个表空间。如果没有提供这个子句,这个索引将在default\_tablespace中创建,如果default\_tablespace为空,将使用数据库的缺省表空间。 ## 示例 * 示例1:创建范围分区表tpcds.web\_returns\_p1,含有8个分区,分区键为integer类型。 分区的范围分别为:wr\_returned\_date\_sk< 2450815、2450815<= wr\_returned\_date\_sk< 2451179、2451179<=wr\_returned\_date\_sk< 2451544、2451544 <= wr\_returned\_date\_sk< 2451910、2451910 <= wr\_returned\_date\_sk< 2452275、2452275 <= wr\_returned\_date\_sk< 2452640、2452640 <= wr\_returned\_date\_sk< 2453005、wr\_returned\_date\_sk>=2453005。 ``` --创建表tpcds.web_returns。 openGauss=# CREATE TABLE tpcds.web_returns ( W_WAREHOUSE_SK INTEGER NOT NULL, W_WAREHOUSE_ID CHAR(16) NOT NULL, W_WAREHOUSE_NAME VARCHAR(20) , W_WAREHOUSE_SQ_FT INTEGER , W_STREET_NUMBER CHAR(10) , W_STREET_NAME VARCHAR(60) , W_STREET_TYPE CHAR(15) , W_SUITE_NUMBER CHAR(10) , W_CITY VARCHAR(60) , W_COUNTY VARCHAR(30) , W_STATE CHAR(2) , W_ZIP CHAR(10) , W_COUNTRY VARCHAR(20) , W_GMT_OFFSET DECIMAL(5,2) ); --创建分区表tpcds.web_returns_p1。 openGauss=# CREATE TABLE tpcds.web_returns_p1 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) WITH (ORIENTATION = COLUMN,COMPRESSION=MIDDLE) PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) ); --从示例数据表导入数据。 openGauss=# INSERT INTO tpcds.web_returns_p1 SELECT * FROM tpcds.web_returns; --删除分区P8。 openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION P8; --增加分区WR_RETURNED_DATE_SK介于2453005和2453105之间。 openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P8 VALUES LESS THAN (2453105); --增加分区WR_RETURNED_DATE_SK介于2453105和MAXVALUE之间。 openGauss=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P9 VALUES LESS THAN (MAXVALUE); --删除分区P8。 openGauss=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION FOR (2453005); --分区P7重命名为P10。 openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION P7 TO P10; --分区P6重命名为P11。 openGauss=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION FOR (2452639) TO P11; --查询分区P10的行数。 openGauss=# SELECT count(*) FROM tpcds.web_returns_p1 PARTITION (P10); count -------- 0 (1 row) --查询分区P1的行数。 openGauss=# SELECT COUNT(*) FROM tpcds.web_returns_p1 PARTITION FOR (2450815); count -------- 0 (1 row) ``` * 示例2:创建范围分区表tpcds.web\_returns\_p2,含有8个分区,分区键类型为integer类型,其中第8个分区上边界为MAXVALUE。 八个分区的范围分别为: wr\_returned\_date\_sk< 2450815、2450815<= wr\_returned\_date\_sk< 2451179、2451179<=wr\_returned\_date\_sk< 2451544、2451544 <= wr\_returned\_date\_sk< 2451910、2451910 <= wr\_returned\_date\_sk< 2452275、2452275 <= wr\_returned\_date\_sk< 2452640、2452640 <= wr\_returned\_date\_sk< 2453005、wr\_returned\_date\_sk>=2453005。 分区表tpcds.web\_returns\_p2的表空间为example1;分区P1到P7没有声明表空间,使用采用分区表tpcds.web\_returns\_p2的表空间example1;指定分区P8的表空间为example2。 假定数据库节点的数据目录/pg\_location/mount1/path1,数据库节点的数据目录/pg\_location/mount2/path2,数据库节点的数据目录/pg\_location/mount3/path3,数据库节点的数据目录/pg\_location/mount4/path4是dwsadmin用户拥有读写权限的空目录。 ``` openGauss=# CREATE TABLESPACE example1 RELATIVE LOCATION 'tablespace1/tablespace_1'; openGauss=# CREATE TABLESPACE example2 RELATIVE LOCATION 'tablespace2/tablespace_2'; openGauss=# CREATE TABLESPACE example3 RELATIVE LOCATION 'tablespace3/tablespace_3'; openGauss=# CREATE TABLESPACE example4 RELATIVE LOCATION 'tablespace4/tablespace_4'; openGauss=# CREATE TABLE tpcds.web_returns_p2 ( WR_RETURNED_DATE_SK INTEGER , WR_RETURNED_TIME_SK INTEGER , WR_ITEM_SK INTEGER NOT NULL, WR_REFUNDED_CUSTOMER_SK INTEGER , WR_REFUNDED_CDEMO_SK INTEGER , WR_REFUNDED_HDEMO_SK INTEGER , WR_REFUNDED_ADDR_SK INTEGER , WR_RETURNING_CUSTOMER_SK INTEGER , WR_RETURNING_CDEMO_SK INTEGER , WR_RETURNING_HDEMO_SK INTEGER , WR_RETURNING_ADDR_SK INTEGER , WR_WEB_PAGE_SK INTEGER , WR_REASON_SK INTEGER , WR_ORDER_NUMBER BIGINT NOT NULL, WR_RETURN_QUANTITY INTEGER , WR_RETURN_AMT DECIMAL(7,2) , WR_RETURN_TAX DECIMAL(7,2) , WR_RETURN_AMT_INC_TAX DECIMAL(7,2) , WR_FEE DECIMAL(7,2) , WR_RETURN_SHIP_COST DECIMAL(7,2) , WR_REFUNDED_CASH DECIMAL(7,2) , WR_REVERSED_CHARGE DECIMAL(7,2) , WR_ACCOUNT_CREDIT DECIMAL(7,2) , WR_NET_LOSS DECIMAL(7,2) ) TABLESPACE example1 PARTITION BY RANGE(WR_RETURNED_DATE_SK) ( PARTITION P1 VALUES LESS THAN(2450815), PARTITION P2 VALUES LESS THAN(2451179), PARTITION P3 VALUES LESS THAN(2451544), PARTITION P4 VALUES LESS THAN(2451910), PARTITION P5 VALUES LESS THAN(2452275), PARTITION P6 VALUES LESS THAN(2452640), PARTITION P7 VALUES LESS THAN(2453005), PARTITION P8 VALUES LESS THAN(MAXVALUE) TABLESPACE example2 ) ENABLE ROW MOVEMENT; --以like方式创建一个分区表。 openGauss=# CREATE TABLE tpcds.web_returns_p3 (LIKE tpcds.web_returns_p2 INCLUDING PARTITION); --修改分区P1的表空间为example2。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P1 TABLESPACE example2; --修改分区P2的表空间为example3。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P2 TABLESPACE example3; --以2453010为分割点切分P8。 openGauss=# ALTER TABLE tpcds.web_returns_p2 SPLIT PARTITION P8 AT (2453010) INTO ( PARTITION P9, PARTITION P10 ); --将P6,P7合并为一个分区。 openGauss=# ALTER TABLE tpcds.web_returns_p2 MERGE PARTITIONS P6, P7 INTO PARTITION P8; --修改分区表迁移属性。 openGauss=# ALTER TABLE tpcds.web_returns_p2 DISABLE ROW MOVEMENT; --删除表和表空间。 openGauss=# DROP TABLE tpcds.web_returns_p1; openGauss=# DROP TABLE tpcds.web_returns_p2; openGauss=# DROP TABLE tpcds.web_returns_p3; openGauss=# DROP TABLESPACE example1; openGauss=# DROP TABLESPACE example2; openGauss=# DROP TABLESPACE example3; openGauss=# DROP TABLESPACE example4; ``` * 示例3:START END语法创建、修改Range分区表。 假定/home/omm/startend\_tbs1、/home/omm/startend\_tbs2、/home/omm/startend\_tbs3、/home/omm/startend\_tbs4是omm用户拥有读写权限的空目录。 ``` -- 创建表空间 openGauss=# CREATE TABLESPACE startend_tbs1 LOCATION '/home/omm/startend_tbs1'; openGauss=# CREATE TABLESPACE startend_tbs2 LOCATION '/home/omm/startend_tbs2'; openGauss=# CREATE TABLESPACE startend_tbs3 LOCATION '/home/omm/startend_tbs3'; openGauss=# CREATE TABLESPACE startend_tbs4 LOCATION '/home/omm/startend_tbs4'; -- 创建临时schema openGauss=# CREATE SCHEMA tpcds; openGauss=# SET CURRENT_SCHEMA TO tpcds; -- 创建分区表,分区键是integer类型 openGauss=# CREATE TABLE tpcds.startend_pt (c1 INT, c2 INT) TABLESPACE startend_tbs1 PARTITION BY RANGE (c2) ( PARTITION p1 START(1) END(1000) EVERY(200) TABLESPACE startend_tbs2, PARTITION p2 END(2000), PARTITION p3 START(2000) END(2500) TABLESPACE startend_tbs3, PARTITION p4 START(2500), PARTITION p5 START(3000) END(5000) EVERY(1000) TABLESPACE startend_tbs4 ) ENABLE ROW MOVEMENT; -- 查看分区表信息 openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs1 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p5_2 | {5000} | startend_tbs4 startend_pt | | startend_tbs1 (12 rows) -- 导入数据,查看分区数据量 openGauss=# INSERT INTO tpcds.startend_pt VALUES (GENERATE_SERIES(0, 4999), GENERATE_SERIES(0, 4999)); openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION FOR (0); count ------- 1 (1 row) openGauss=# SELECT COUNT(*) FROM tpcds.startend_pt PARTITION (p3); count ------- 500 (1 row) -- 增加分区: [5000, 5300), [5300, 5600), [5600, 5900), [5900, 6000) openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p6 START(5000) END(6000) EVERY(300) TABLESPACE startend_tbs4; -- 增加MAXVALUE分区: p7 openGauss=# ALTER TABLE tpcds.startend_pt ADD PARTITION p7 END(MAXVALUE); -- 重命名分区p7为p8 openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION p7 TO p8; -- 删除分区p8 openGauss=# ALTER TABLE tpcds.startend_pt DROP PARTITION p8; -- 重命名5950所在的分区为:p71 openGauss=# ALTER TABLE tpcds.startend_pt RENAME PARTITION FOR(5950) TO p71; -- 分裂4500所在的分区[4000, 5000) openGauss=# ALTER TABLE tpcds.startend_pt SPLIT PARTITION FOR(4500) INTO(PARTITION q1 START(4000) END(5000) EVERY(250) TABLESPACE startend_tbs3); -- 修改分区p2的表空间为startend_tbs4 openGauss=# ALTER TABLE tpcds.startend_pt MOVE PARTITION p2 TABLESPACE startend_tbs4; -- 查看分区情形 openGauss=# SELECT relname, boundaries, spcname FROM pg_partition p JOIN pg_tablespace t ON p.reltablespace=t.oid and p.parentid='tpcds.startend_pt'::regclass ORDER BY 1; relname | boundaries | spcname -------------+------------+--------------- p1_0 | {1} | startend_tbs2 p1_1 | {201} | startend_tbs2 p1_2 | {401} | startend_tbs2 p1_3 | {601} | startend_tbs2 p1_4 | {801} | startend_tbs2 p1_5 | {1000} | startend_tbs2 p2 | {2000} | startend_tbs4 p3 | {2500} | startend_tbs3 p4 | {3000} | startend_tbs1 p5_1 | {4000} | startend_tbs4 p6_1 | {5300} | startend_tbs4 p6_2 | {5600} | startend_tbs4 p6_3 | {5900} | startend_tbs4 p71 | {6000} | startend_tbs4 q1_1 | {4250} | startend_tbs3 q1_2 | {4500} | startend_tbs3 q1_3 | {4750} | startend_tbs3 q1_4 | {5000} | startend_tbs3 startend_pt | | startend_tbs1 (19 rows) -- 删除表和表空间 openGauss=# DROP SCHEMA tpcds CASCADE; openGauss=# DROP TABLESPACE startend_tbs1; openGauss=# DROP TABLESPACE startend_tbs2; openGauss=# DROP TABLESPACE startend_tbs3; openGauss=# DROP TABLESPACE startend_tbs4; ``` * 示例4:创建间隔分区表sales,初始包含2个分区,分区键为DATE类型。 分区的范围分别为:time\_id < '2019-02-01 00:00:00'、 '2019-02-01 00:00:00' <= time\_id < '2019-02-02 00:00:00' 。 ``` --创建表sales openGauss=# CREATE TABLE sales (prod_id NUMBER(6), cust_id NUMBER, time_id DATE, channel_id CHAR(1), promo_id NUMBER(6), quantity_sold NUMBER(3), amount_sold NUMBER(10,2) ) PARTITION BY RANGE (time_id) INTERVAL('1 day') ( PARTITION p1 VALUES LESS THAN ('2019-02-01 00:00:00'), PARTITION p2 VALUES LESS THAN ('2019-02-02 00:00:00') ); -- 数据插入分区p1 openGauss=# INSERT INTO sales VALUES(1, 12, '2019-01-10 00:00:00', 'a', 1, 1, 1); -- 数据插入分区p2 openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-01 00:00:00', 'a', 1, 1, 1); -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (2 rows) -- 插入数据没有匹配的分区,新创建一个分区,并将数据插入该分区 -- 新分区的范围为 '2019-02-05 00:00:00' <= time_id < '2019-02-06 00:00:00' openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-05 00:00:00', 'a', 1, 1, 1); -- 插入数据没有匹配的分区,新创建一个分区,并将数据插入该分区 -- 新分区的范围为 '2019-02-03 00:00:00' <= time_id < '2019-02-04 00:00:00' openGauss=# INSERT INTO sales VALUES(1, 12, '2019-02-03 00:00:00', 'a', 1, 1, 1); -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'sales' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------------------- sys_p1 | i | {"2019-02-06 00:00:00"} sys_p2 | i | {"2019-02-04 00:00:00"} p1 | r | {"2019-02-01 00:00:00"} p2 | r | {"2019-02-02 00:00:00"} (4 rows) ``` * 示例5:创建LIST分区表test\_list,初始包含4个分区,分区键为INT类型。4个分区的范围分别为:2000、3000、4000、5000。 ``` --创建表test_list openGauss=# create table test_list (col1 int, col2 int) partition by list(col1) ( partition p1 values (2000), partition p2 values (3000), partition p3 values (4000), partition p4 values (5000) ); -- 数据插入 openGauss=# INSERT INTO test_list VALUES(2000, 2000); INSERT 0 1 openGauss=# INSERT INTO test_list VALUES(3000, 3000); INSERT 0 1 -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} p4 | l | {5000} (4 rows) -- 插入数据没有匹配到分区,报错处理 openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- 添加分区 openGauss=# alter table test_list add partition p5 values (6000); ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p5 | l | {6000} p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (5 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); INSERT 0 1 -- 分区表和普通表交换数据 openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ 2000 | 2000 (1 row) openGauss=# alter table test_list exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_list partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 2000 | 2000 (1 row) -- truncate分区 openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ 3000 | 3000 (1 row) openGauss=# alter table test_list truncate partition p2; ALTER TABLE openGauss=# select * from test_list partition (p2); col1 | col2 ------+------ (0 rows) -- 删除分区 openGauss=# alter table test_list drop partition p5; ALTER TABLE openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_list' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p4 | l | {5000} p1 | l | {2000} p2 | l | {3000} p3 | l | {4000} (4 rows) openGauss=# INSERT INTO test_list VALUES(6000, 6000); ERROR: inserted partition key does not map to any table partition -- 删除分区表 openGauss=# drop table test_list; ``` * 示例6:创建HASH分区表test\_hash,初始包含2个分区,分区键为INT类型。 ``` --创建表test_hash openGauss=# create table test_hash (col1 int, col2 int) partition by hash(col1) ( partition p1, partition p2 ); -- 数据插入 openGauss=# INSERT INTO test_hash VALUES(1, 1); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(2, 2); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(3, 3); INSERT 0 1 openGauss=# INSERT INTO test_hash VALUES(4, 4); INSERT 0 1 -- 查看分区信息 openGauss=# SELECT t1.relname, partstrategy, boundaries FROM pg_partition t1, pg_class t2 WHERE t1.parentid = t2.oid AND t2.relname = 'test_hash' AND t1.parttype = 'p'; relname | partstrategy | boundaries ---------+--------------+------------ p1 | h | {0} p2 | h | {1} (2 rows) -- 查看数据 openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ 1 | 1 2 | 2 (2 rows) -- 分区表和普通表交换数据 openGauss=# create table t1 (col1 int, col2 int); CREATE TABLE openGauss=# alter table test_hash exchange partition (p1) with table t1; ALTER TABLE openGauss=# select * from test_hash partition (p1); col1 | col2 ------+------ (0 rows) openGauss=# select * from t1; col1 | col2 ------+------ 3 | 3 4 | 4 (2 rows) -- truncate分区 openGauss=# alter table test_hash truncate partition p2; ALTER TABLE openGauss=# select * from test_hash partition (p2); col1 | col2 ------+------ (0 rows) -- 删除分区表 openGauss=# drop table test_hash; ``` - 示例7:创建LIST分区表t\_multi\_keys\_list,初始包含5个分区,两个分区键分别为INT类型和VARCHAR类型。 ``` --创建表t_multi_keys_list openGauss=# CREATE TABLE t_multi_keys_list (a int, b varchar(4), c int) PARTITION BY LIST (a,b) ( PARTITION p1 VALUES ( (0,NULL) ), PARTITION p2 VALUES ( (0,'1'), (0,'2'), (0,'3'), (1,'1'), (1,'2') ), PARTITION p3 VALUES ( (NULL,'0'), (2,'1') ), PARTITION p4 VALUES ( (3,'2'), (NULL,NULL) ), PARTITION pd VALUES ( DEFAULT ) ); ``` ## 相关链接 [ALTER TABLE PARTITION](alter_table_partition.md),[DROP TABLE](drop_table.md) --- --- url: /en/docs/latest/sql_reference/create_table_subpartition.md --- # CREATE TABLE SUBPARTITION ## Function **CREATE TABLE SUBPARTITION** creates a level-2 partitioned table. A partitioned table is a logical table that is divided into several physical partitions for storage based on a specific plan. A partitioned table is a logical table and does not store data. Data is stored in physical partitions. For a level-2 partitioned table, the top-level node table and level-1 partitioned table are logical tables and do not store data. Only the level-2 partitioned (leaf node) stores data. The partitioning solution of a level-2 partitioned table is a combination of the partitioning solutions of two level-1 partitions. For details about the partitioning solution of a level-1 partitioned table, see CREATE TABLE PARTITION. Common combination solutions for level-2 partitioned tables include range-range partitioning, range-list partitioning, range-hash partitioning, list-range partitioning, list-list partitioning, list-hash partitioning, hash-range partitioning, hash-list partitioning, and hash-hash partitioning. Currently, level-2 partitioned tables can only be row-store tables. ## Precautions * A level-2 partitioned table has two partition keys, and each partition key supports only one column. The two partition keys cannot be the same column. * If the constraint key of the unique constraint and primary key constraint contains all partition keys, a local index is created for the constraints. Otherwise, a global index is created. If a local unique index is created, all partition keys must be included. * When a level-2 partitioned table is created, if the specified level-2 partition is not displayed under the level-1 partition, a level-2 partition with the same range is automatically created. * The number of level-2 partitions (leaf nodes) in a level-2 partitioned table cannot exceed 1048575. There is no limit on the number of level-1 partitions, but there must be at least one level-2 partition under a level-1 partition. * The maximum number of level-2 partitions is 1048575. Generally, it is impossible to create so many partitions, because too many partitions may cause insufficient memory. Create partitions based on the value of **local\_syscache\_threshold**. The memory used by the level-2 partitioned tables is about (number of level-2 partitions x 3/1024) MB. Theoretically, the memory occupied by the partitions cannot be greater than the value of **local\_syscache\_threshold**. In addition, some space must be reserved for other functions. * Level-2 partitioned tables support only row store and do not support column-store and hash bucket. * Clusters are not supported. * When specifying a partition for query, for example, **select \* from tablename partition/subpartition** (*partitionname*), ensure that the keywords **partition** and **subpartition** are correct. If they are incorrect, no error is reported during the query. In this case, the query is performed based on the table alias. * Encrypted databases, ledger databases, and row-level security are not supported. * In the **PARTITION FOR (values)** syntax for level-2 partitioned tables, values can only be constants. * In the **PARTITION/SUBPARTITION FOR (values)** syntax for level-2 partitioned tables, if data type conversion is required for values, you are advised to use forcible type conversion to prevent the implicit type conversion result from being inconsistent with the expected result. * Currently, the statement specifying a partition cannot perform global index scan. ## Syntax ``` CREATE TABLE [ IF NOT EXISTS ] subpartition_table_name ( { column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ] | table_constraint | LIKE source_table [ like_option [...] ] }[, ... ] ) [ AUTO_INCREMENT [ = ] value ] [ WITH ( {storage_parameter = value} [, ... ] ) ] [ COMPRESS | NOCOMPRESS ] [ TABLESPACE tablespace_name ] PARTITION BY {RANGE | LIST | HASH} (partition_key) SUBPARTITION BY {RANGE | LIST | HASH} (subpartition_key) ( PARTITION partition_name1 [ VALUES LESS THAN (val1) | VALUES (val1[, …]) ] [ TABLESPACE tablespace ] [ COMMENT {=| } 'text' ] ( { SUBPARTITION subpartition_name1 [ VALUES LESS THAN (val1_1) | VALUES (val1_1[, …])] [ TABLESPACE tablespace ] [COMMENT {=| } 'text' ] } [, ...] )[, ...] )[ { ENABLE | DISABLE } ROW MOVEMENT ]; ``` * Column constraint: ``` [ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) | DEFAULT default_e xpr | GENERATED ALWAYS AS ( generation_expr ) STORED | AUTO_INCREMENT | UNIQUE index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ ENABLE [VALIDATE | NOVALIDATE] | DISABLE [VALIDATE | NOVALIDATE] ] [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * Table constraint: ``` [ CONSTRAINT [ constraint_name ] ] { CHECK ( expression ) | UNIQUE [ index_name ][ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | PRIMARY KEY [ USING method ] ( { column_name [ ASC | DESC ] } [, ... ] ) index_parameters | FOREIGN KEY [ index_name ] ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE | INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ COMMENT {=| } 'text' ] ``` * LIKE options: ``` { INCLUDING | EXCLUDING } { DEFAULTS | GENERATED | CONSTRAINTS | INDEXES | STORAGE | COMMENTS | RELOPTIONS| ALL } ``` * Index parameters: ``` [ WITH ( {storage_parameter = value} [, ... ] ) ] [ USING INDEX TABLESPACE tablespace_name ] ``` ## Parameter Description * **IF NOT EXISTS** Does not throw an error if a relationship with the same name existed. A notice is issued in this case. * **subpartition\_table\_name** Specifies the name of a level-2 partitioned table. Value range: a string. It must comply with the identifier naming convention. * **column\_name** Specifies the name of a column to be created in the new table. Value range: a string. It must comply with the identifier naming convention. * **data\_type** Specifies the data type of the column. * **COLLATE collation** Assigns a collation to the column (which must be of a collatable data type). If no collation is specified, the default collation is used. You can run the **select \* from pg\_collation;** command to query collation rules from the **pg\_collation** system catalog. The default collation rule is the row starting with **default** in the query result. * **CONSTRAINT constraint\_name** Specifies the name of a column or table constraint. The optional constraint clauses specify constraints that new or updated rows must satisfy for an INSERT or UPDATE operation to succeed. There are two ways to define constraints: * A column constraint is defined as part of a column definition, and it is bound to a particular column. * A table constraint is not bound to a particular column but can apply to more than one column. > \[!TIP]NOTICE > \>constraint\_name is optional in B-compatible mode (**sql\_compatibility = 'B'**). For other modes, constraint\_name must be added. * **index\_name** Specifies an index name. > \[!TIP]NOTICE > > * index\_name is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * For foreign key constraints, if constraint\_name and index\_name are specified at the same time, constraint\_name is used as the index name. > * For a unique key constraint, if both constraint\_name and index\_name are specified, index\_name is used as the index name. * **USING method** Specifies the name of the index method to be used. For details about the value range, see [USING method](create_index.md). > \[!TIP]NOTICE > > * The USING method is supported only in B-compatible databases (that is, sql\_compatibility = 'B'). > * In B-compatible mode, if USING method is not specified, the default index method is btree for ASTORE or ubtree for USTORE. * **ASC | DESC** **ASC** specifies an ascending (default) sort order. **DESC** specifies a descending sort order. > \[!TIP]NOTICE > ASC|DESC is supported only in B-compatible databases (sql\_compatibility = 'B'). * **LIKE source\_table \[ like\_option ... ]** Level-2 partitioned tables do not support this function. * **AUTO\_INCREMENT \[ = ] value** This clause specifies an initial value for an auto-increment column. The value must be a positive integer and cannot exceed 2127-1. > \[!TIP]NOTICE > This clause takes effect only when **sql\_compatibility** is set to **B**. * **WITH ( storage\_parameter \[= value] \[, ... ] )** Specifies an optional storage parameter for a table or an index. Optional parameters are as follows: * FILLFACTOR The fill factor of a table is a percentage from 10 to 100. **100** (complete filling) is the default value. When a smaller fill factor is specified, INSERT operations fill table pages only to the indicated percentage. The remaining space on each page is reserved for updating rows on that page. This gives UPDATE a chance to place the updated copy of a row on the same page, which is more efficient than placing it on a different page. For a table whose entries are never updated, setting the fill factor to **100** (complete filling) is the best choice, but in heavily updated tables a smaller fill factor would be appropriate. The parameter has no meaning for column-store tables. Value range: 10–100 * ORIENTATION Determines the data storage mode of the table. Value range: * **COLUMN**: The data will be stored in columns. * **ROW** (default value): The data will be stored in rows. > \[!TIP]NOTICE > **ORIENTATION** cannot be modified. * COMPRESSLEVEL Specifies the table data compression ratio and duration at the same compression level. This divides a compression level into sublevels, providing more choices for compression ratio and duration. As the value becomes greater, the compression ratio becomes higher and duration longer at the same compression level. Value range: 0 to 3. The default value is **0**. * COMPRESSTYPE Specifies the row-store table compression algorithm. The value **1** indicates the PGLZ algorithm, the value **2** indicates the ZSTD algorithm, the value **3** indicates the PGZSTD algorithm (currently not supported), and the value **4** indicates the ZLIB algorithm. By default, indexes are not compressed. (Only common tables in the Astore engine are supported.) Value range: 0 to 4. The default value is **0**. * COMPRESS\_LEVEL Specifies the row-store table compression algorithm level. This parameter is valid only when **COMPRESSTYPE** is set to **2** or **4**. A higher compression level indicates a better table compression effect and a slower table access speed. (Only common tables in the Astore engine are supported.) Value range: –31 to 31. The default value is **0**. * COMPRESS\_CHUNK\_SIZE Specifies the size of a row-store table compression chunk. A smaller chunk size indicates a better compression effect, and a larger data dispersion degree indicates a slower table access speed. (Only common tables in the Astore engine are supported.) Value range: subject to the page size. When the page size is 8 KB, the value can be **512**, **1024**, **2048**, or **4096**. Default value: **4096** * COMPRESS\_PREALLOC\_CHUNKS Specifies the number of pre-allocated row-store table compression chunks. A larger number of pre-allocated chunks indicates a lower table compression ratio, and a smaller data dispersion degree indicates a better access performance. (Only common tables in the Astore engine are supported.) Value range: 0 to 7. The default value is **0**. * The maximum value of this parameter is **7** when **COMPRESS\_CHUNK\_SIZE** is set to **512** or **1024**. * The maximum value of this parameter is **3** when **COMPRESS\_CHUNK\_SIZE** is set to **2048**. * The maximum value of this parameter is **1** when **COMPRESS\_CHUNK\_SIZE** is set to **4096**. * COMPRESS\_BYTE\_CONVERT Sets the preprocessing of row-store table compression byte conversion. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * COMPRESS\_DIFF\_CONVERT Sets the preprocessing of row-store table compression differentiation. This parameter can be used together only with **COMPRESS\_BYTE\_CONVERT**. In some scenarios, the compression effect can be improved, but the performance deteriorates. Value range: Boolean value. By default, this function is disabled. * STORAGE\_TYPE Specifies the storage engine type. This parameter cannot be modified once it is set. Value range: * **USTORE** indicates that tables support the inplace-update storage engine. Note that the **track\_counts** and **track\_activities** parameters must be enabled when the Ustore table is used. Otherwise, space expansion may occur. * **ASTORE** indicates that tables support the append-only storage engine. Default value: If no table is specified, data is stored in append-only mode by default. * COMPRESSION * Value range: **LOW**, **MIDDLE**, **HIGH**, **YES**, and **NO** for column-store tables, with compression level increasing in ascending order. The default value is **LOW**. * Row-store tables do not support compression. * MAX\_BATCHROW Specifies the maximum number of records in a storage unit during data loading. The parameter is only valid for column-store tables. Value range: 10000 to 60000. The default value is **60000**. * PARTIAL\_CLUSTER\_ROWS Specifies the number of records to be partially clustered for storage during data loading. The parameter is only valid for column-store tables. Value range: greater than or equal to **MAX\_BATCHROW**. You are advised to set this parameter to an integer multiple of **MAX\_BATCHROW**. * DELTAROW\_THRESHOLD A reserved parameter. The parameter is only valid for column-store tables. Value range: 0 to 9999 * segment The data is stored in segment-page mode. This parameter supports only row-store tables. Column-store tables, temporary tables, and unlogged tables are not supported. The Ustore storage engine is not supported. Value range: **on** and **off** Default value: **off** * **COMPRESS / NOCOMPRESS** Specifies keyword COMPRESS during the creation of a table, so that the compression feature is triggered in case of BULK INSERT operations. If this feature is enabled, a scan is performed for all tuple data within the page to generate a dictionary and then the tuple data is compressed and stored. If **NOCOMPRESS** is specified, the table is not compressed. Row-store tables do not support compression. Default value: **NOCOMPRESS**, that is, tuple data is not compressed before storage. * **TABLESPACE tablespace\_name** Specifies that the new table will be created in the **tablespace\_name** tablespace. If the tablespace is not specified, the default tablespace is used. * **PARTITION BY {RANGE | LIST | HASH} (partition\_key)** * For **partition\_key**, the partitioning policy supports only one column of partition keys. * The data types supported by the partition key are the same as those supported by the level-1 partitioned table. * **SUBPARTITION BY {RANGE | LIST | HASH} (subpartition\_key)** * For **subpartition\_key**, the partitioning policy supports only one column of partition keys. * The data types supported by the partition key are the same as those supported by the level-1 partitioned table. * **{ ENABLE | DISABLE } ROW MOVEMENT** Specifies whether to enable row movement. If the tuple value is updated on the partition key during the UPDATE operation, the partition where the tuple is located is altered. Setting this parameter enables error messages to be reported or movement of the tuple between partitions. Value range: * **ENABLE** (default value): Row movement is enabled. * **DISABLE**: Row movement is disabled. * **NOT NULL** The column is not allowed to contain null values. **ENABLE** can be omitted. * **NULL** Indicates that the column is allowed to contain **NULL** values. This is the default setting. This clause is only provided for compatibility with non-standard SQL databases. It is not recommended. * **CHECK (condition) \[ NO INHERIT ]** Specifies an expression producing a Boolean result where the INSERT or UPDATE operation of new or updated rows can succeed only when the expression result is **TRUE** or **UNKNOWN**; otherwise, an error is thrown and the database is not altered. A check constraint specified as a column constraint should reference only the column's values, while an expression in a table constraint can reference multiple columns. A constraint marked with **NO INHERIT** will not propagate to child tables. **ENABLE** can be omitted. * **DEFAULT default\_expr** Assigns a default data value to a column. The value can be any variable-free expressions. (Subqueries and cross-references to other columns in the current table are not allowed.) The data type of the default expression must match that of the column. The default expression will be used in any INSERT operation that does not specify a value for the column. If there is no default value for a column, then the default value is **NULL**. * **GENERATED ALWAYS AS ( generation\_expr ) STORED** This clause creates a column as a generated column. The value of the generated column is calculated by **generation\_expr** when data is written (inserted or updated). **STORED** indicates that the value of the generated column is stored as a common column. > \[!NOTE]NOTE > > * The generation expression cannot refer to data other than the current row in any way. The generation expression cannot reference other generation columns or system columns. The generation expression cannot return a result set. No subquery, aggregate function, or window function can be used. The function called by the generation expression can only be an immutable function. > * Default values cannot be specified for generated columns. > * The generated column cannot be used as a part of the partition key. > * Do not specify the generated column and the CASCADE, SET NULL, and SET DEFAULT actions of the ON UPDATE constraint at the same time. Do not specify the generated column and the SET NULL, and SET DEFAULT actions of the ON DELETE constraint at the same time. > * The method of modifying and deleting generated columns is the same as that of common columns. Delete the common column that the generated column depends on. The generated column is automatically deleted. The type of the column on which the generated column depends cannot be changed. > * The generated column cannot be directly written. In the INSERT or UPDATE statement, values cannot be specified for generated columns, but the keyword DEFAULT can be specified. > * The permission control for generated columns is the same as that for common columns. > * Columns cannot be generated for column-store tables and MOTs. In foreign tables, only **postgres\_fdw** supports generated columns. * **AUTO\_INCREMENT** Specifies an auto-increment column. For details, see [AUTO\_INCREMENT](create_table.md). * **UNIQUE index\_parameters** **UNIQUE ( column\_name \[, ... ] ) index\_parameters** Specifies that a group of one or more columns of a table can contain only unique values. For the purpose of a unique constraint, null is not considered equal. * **PRIMARY KEY index\_parameters** **PRIMARY KEY ( column\_name \[, ... ] ) index\_parameters** Specifies that a column or columns of a table can contain only unique (non-duplicate) and non-null values. Only one primary key can be specified for a table. * **ENABLE \[VALIDATE | NOVALIDATE] | DISABLE \[VALIDATE | NOVALIDATE]** * ENABLE( VALIDATE)(default): Enable constraints, create indexes, and enforce constraints on both existing data and newly added data. * ENABLE NOVALIDATE: Enable constraints and create indexes. For CHECK constraints, the constraints are only enforced for newly added data, regardless of the existing data in the table. For UNIQUE and PRIMARY KEY, indexes need to be established, so the constraints will be enforced for the existing data. * DISABLE( NOVALIDATE)(default): Disable constraints, delete indexes, and operations such as modifying the data of the constraint columns can be performed. * DISABLE VALIDATE: Disable constraints and delete indexes. Insertion, update and deletion operations on the table cannot be performed. * **DEFERRABLE | NOT DEFERRABLE** They determine whether the constraint is deferrable. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable can be postponed until the end of the transaction using the **SET CONSTRAINTS** command. **NOT DEFERRABLE** is the default value. Currently, only UNIQUE constraints, primary key constraints, and foreign key constraints accept this clause. All the other constraints are not deferrable. * **INITIALLY IMMEDIATE | INITIALLY DEFERRED** If a constraint is deferrable, this clause specifies the default time to check the constraint. * If the constraint is **INITIALLY IMMEDIATE** (default value), it is checked after each statement. * If the constraint is **INITIALLY DEFERRED**, it is checked only at the end of the transaction. The constraint check time can be altered using the **SET CONSTRAINTS** statement. * **USING INDEX TABLESPACE tablespace\_name** Allows selection of the tablespace in which the index associated with a **UNIQUE** or **PRIMARY KEY** constraint will be created. If not specified, the index is created in **default\_tablespace**. If **default\_tablespace** is empty, the default tablespace of the database is used. * COMMENT {=| } 'text': In the partition of a partitioned table, this column is meaningless and is used only for syntax compatibility. An alarm is displayed when the syntax is used in the database. ## Examples * Example 1: Create level-2 partitioned tables of various combination types. ``` CREATE TABLE list_list ( month_code VARCHAR2 ( 30 ) NOT NULL , dept_code VARCHAR2 ( 30 ) NOT NULL , user_no VARCHAR2 ( 30 ) NOT NULL , sales_amt int ) PARTITION BY LIST (month_code) SUBPARTITION BY LIST (dept_code) ( PARTITION p_201901 VALUES ( '201902' ) ( SUBPARTITION p_201901_a VALUES ( '1' ), SUBPARTITION p_201901_b VALUES ( '2' ) ), PARTITION p_201902 VALUES ( '201903' ) ( SUBPARTITION p_201902_a VALUES ( '1' ), SUBPARTITION p_201902_b VALUES ( '2' ) ) ); insert into list_list values('201902', '1', '1', 1); insert into list_list values('201902', '2', '1', 1); insert into list_list values('201902', '1', '1', 1); insert into list_list values('201903', '2', '1', 1); insert into list_list values('201903', '1', '1', 1); insert into list_list values('201903', '2', '1', 1); select * from list_list; month_code | dept_code | user_no | sales_amt ------------+-----------+---------+----------- 201903 | 2 | 1 | 1 201903 | 2 | 1 | 1 201903 | 1 | 1 | 1 201902 | 2 | 1 | 1 201902 | 1 | 1 | 1 201902 | 1 | 1 | 1 (6 rows) drop table list_list; CREATE TABLE list_hash ( month_code VARCHAR2 ( 30 ) NOT NULL , dept_code VARCHAR2 ( 30 ) NOT NULL , user_no VARCHAR2 ( 30 ) NOT NULL , sales_amt int ) PARTITION BY LIST (month_code) SUBPARTITION BY HASH (dept_code) ( PARTITION p_201901 VALUES ( '201902' ) ( SUBPARTITION p_201901_a, SUBPARTITION p_201901_b ), PARTITION p_201902 VALUES ( '201903' ) ( SUBPARTITION p_201902_a, SUBPARTITION p_201902_b ) ); insert into list_hash values('201902', '1', '1', 1); insert into list_hash values('201902', '2', '1', 1); insert into list_hash values('201902', '3', '1', 1); insert into list_hash values('201903', '4', '1', 1); insert into list_hash values('201903', '5', '1', 1); insert into list_hash values('201903', '6', '1', 1); select * from list_hash; month_code | dept_code | user_no | sales_amt ------------+-----------+---------+----------- 201903 | 4 | 1 | 1 201903 | 5 | 1 | 1 201903 |